@twilio/conversations 2.1.0 → 3.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/builds/lib.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"lib.js","sources":["../../../node_modules/tslib/tslib.es6.js","../src/logger.ts","../src/configuration.ts","../src/util/index.ts","../src/interfaces/attributes.ts","../src/user.ts","../src/services/network.ts","../src/interfaces/notification-types.ts","../src/participant.ts","../src/data/participants.ts","../src/media.ts","../src/aggregated-delivery-receipt.ts","../src/rest-paginator.ts","../src/detailed-delivery-receipt.ts","../src/message.ts","../src/data/messages.ts","../src/unsent-message.ts","../src/message-builder.ts","../src/conversation.ts","../src/util/deferred.ts","../src/data/conversations.ts","../src/data/users.ts","../src/services/typing-indicator.ts","../src/push-notification.ts","../src/command-executor.ts","../src/client.ts"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","import * as loglevelLog from \"loglevel\";\nimport { LogLevelDesc } from \"loglevel\";\n\nfunction prepareLine(prefix, args) {\n return [`${new Date().toISOString()} Conversations ${prefix}:`].concat(\n Array.from(args)\n );\n}\n\nconst log: loglevelLog.Logger = loglevelLog.getLogger(\"twilio-conversations\"); // twilio-conversations is used by Flex SDK. Please DO NOT change\n\nclass Logger {\n private prefix = \"\";\n\n private constructor(prefix: string) {\n this.prefix =\n prefix !== null && prefix !== undefined && prefix.length > 0\n ? prefix + \" \"\n : \"\";\n }\n\n static scope(prefix: string): Logger {\n return new Logger(prefix);\n }\n\n setLevel(level: LogLevelDesc) {\n log.setLevel(level);\n }\n\n static setLevel(level: LogLevelDesc) {\n log.setLevel(level);\n }\n\n trace(...args) {\n log.trace.apply(null, prepareLine(this.prefix + \"T\", args));\n }\n\n debug(...args) {\n log.debug.apply(null, prepareLine(this.prefix + \"D\", args));\n }\n\n info(...args) {\n log.info.apply(null, prepareLine(this.prefix + \"I\", args));\n }\n\n warn(...args) {\n log.warn.apply(null, prepareLine(this.prefix + \"W\", args));\n }\n\n error(...args) {\n log.error.apply(null, prepareLine(this.prefix + \"E\", args));\n }\n\n static trace(...args) {\n log.trace.apply(null, prepareLine(\"T\", args));\n }\n\n static debug(...args) {\n log.debug.apply(null, prepareLine(\"D\", args));\n }\n\n static info(...args) {\n log.info.apply(null, prepareLine(\"I\", args));\n }\n\n static warn(...args) {\n log.warn.apply(null, prepareLine(\"W\", args));\n }\n\n static error(...args) {\n log.error.apply(null, prepareLine(\"E\", args));\n }\n}\n\nexport { Logger };\n","import { ConfigurationResponse } from \"./interfaces/commands/configuration\";\nimport { parse as parseDuration, toSeconds } from \"iso8601-duration\";\nimport { Logger } from \"./logger\";\nimport { ConversationLimits } from \"./interfaces/conversation-limits\";\nimport { ClientOptions } from \"./client\";\n\nconst TYPING_TIMEOUT = 5;\nconst HTTP_CACHE_LIFETIME = \"PT5S\";\nconst CONSUMPTION_HORIZON_SENDING_INTERVAL = \"PT5S\";\nconst USER_INFOS_TO_SUBSCRIBE = 100;\n\nconst MINIMUM_RETRY_DELAY = 1000;\nconst MAXIMUM_RETRY_DELAY = 4000;\nconst MAXIMUM_ATTEMPTS_COUNT = 3;\nconst RETRY_WHEN_THROTTLED = true;\n\ninterface BackoffConfiguration {\n min: number;\n max: number;\n maxAttemptsCount: number;\n}\n\nclass Configuration {\n public readonly links: {\n myConversations: string;\n conversations: string;\n users: string;\n currentUser: string;\n typing: string;\n mediaService: string;\n mediaSetService: string;\n messagesReceipts: string;\n };\n\n public readonly limits: ConversationLimits;\n\n public readonly productId?: string;\n\n public readonly typingIndicatorTimeoutOverride?: number;\n public readonly typingIndicatorTimeoutDefault: number = TYPING_TIMEOUT * 1000;\n public readonly backoffConfiguration: BackoffConfiguration;\n public readonly retryWhenThrottled: boolean;\n\n public readonly consumptionReportInterval: number;\n public readonly userInfosToSubscribe: number;\n public readonly httpCacheInterval: number;\n public readonly reachabilityEnabled: boolean;\n\n public readonly userIdentity: string;\n public readonly userInfo: string;\n public readonly myConversations: string;\n\n constructor(\n options: ClientOptions = {},\n configurationResponse: ConfigurationResponse,\n logger: Logger\n ) {\n const constructorOptions =\n options.Chat || options.IPMessaging || options || {};\n\n this.productId = constructorOptions.productId;\n\n this.links = {\n myConversations: configurationResponse.links.my_conversations,\n conversations: configurationResponse.links.conversations,\n users: configurationResponse.links.users,\n currentUser: configurationResponse.links.current_user,\n typing: configurationResponse.links.typing,\n mediaService: configurationResponse.links.media_service,\n mediaSetService: configurationResponse.links.media_set_service,\n messagesReceipts: configurationResponse.links.messages_receipts,\n };\n\n this.limits = {\n mediaAttachmentsCountLimit:\n configurationResponse.options.media_attachments_count_limit,\n mediaAttachmentSizeLimitInMb:\n configurationResponse.options.media_attachment_size_limit_in_mb,\n mediaAttachmentsTotalSizeLimitInMb:\n configurationResponse.options.media_attachments_total_size_limit_in_mb,\n emailHistoriesAllowedMimeTypes:\n configurationResponse.options.email_histories_allowed_mime_types,\n emailBodiesAllowedMimeTypes:\n configurationResponse.options.email_bodies_allowed_mime_types,\n };\n\n this.typingIndicatorTimeoutOverride =\n constructorOptions.typingIndicatorTimeoutOverride;\n this.backoffConfiguration = {\n min: MINIMUM_RETRY_DELAY,\n max: MAXIMUM_RETRY_DELAY,\n maxAttemptsCount: MAXIMUM_ATTEMPTS_COUNT,\n ...constructorOptions.backoffConfigOverride,\n };\n this.retryWhenThrottled =\n constructorOptions.retryWhenThrottledOverride !== undefined\n ? constructorOptions.retryWhenThrottledOverride\n : RETRY_WHEN_THROTTLED;\n this.userInfosToSubscribe =\n constructorOptions.userInfosToSubscribeOverride ??\n configurationResponse.options.user_infos_to_subscribe ??\n USER_INFOS_TO_SUBSCRIBE;\n this.reachabilityEnabled =\n configurationResponse.options.reachability_enabled;\n this.userIdentity = configurationResponse.identity;\n this.userInfo = configurationResponse.sync_objects.my_user_info;\n this.myConversations = configurationResponse.sync_objects.my_conversations;\n\n const httpCacheInterval =\n constructorOptions.httpCacheIntervalOverride ??\n configurationResponse.options.http_cache_interval ??\n HTTP_CACHE_LIFETIME;\n\n try {\n this.httpCacheInterval = toSeconds(parseDuration(httpCacheInterval));\n } catch {\n logger.error(\n `Failed to parse http cache interval ${httpCacheInterval}, using default value ${HTTP_CACHE_LIFETIME}`\n );\n this.httpCacheInterval = toSeconds(parseDuration(HTTP_CACHE_LIFETIME));\n }\n\n const consumptionReportInterval =\n constructorOptions.consumptionReportIntervalOverride ??\n configurationResponse.options.consumption_report_interval ??\n CONSUMPTION_HORIZON_SENDING_INTERVAL;\n\n try {\n this.consumptionReportInterval = toSeconds(\n parseDuration(consumptionReportInterval)\n );\n } catch {\n logger.error(\n `Failed to parse consumption report interval ${consumptionReportInterval}, using default value ${CONSUMPTION_HORIZON_SENDING_INTERVAL}`\n );\n this.consumptionReportInterval = toSeconds(\n parseDuration(CONSUMPTION_HORIZON_SENDING_INTERVAL)\n );\n }\n }\n}\n\nexport { Configuration };\n","import { Logger } from \"../logger\";\nimport { JSONValue } from \"../types\";\n\n/**\n * Deep-clone an object. Note that this does not work on object containing\n * functions.\n * @param {object} obj - the object to deep-clone\n * @returns {object}\n */\nfunction deepClone<T>(obj: T): T {\n return JSON.parse(JSON.stringify(obj)) as T;\n}\n\nfunction parseToNumber(value) {\n if (typeof value !== \"undefined\" && !isNaN(Number(value))) {\n return Number(value);\n }\n return null;\n}\n\n// timeString cannot be typed `string` because in member.ts\n// call to parseTime(data.lastReadTimestamp) uses number not a string for timestamp.\nfunction parseTime(timeString): Date | null {\n try {\n return new Date(timeString);\n } catch (e) {\n return null;\n }\n}\n\nfunction parseAttributes(\n rawAttributes,\n warningMessage: string,\n log: Logger\n): JSONValue {\n let attributes = {};\n if (rawAttributes) {\n try {\n attributes = JSON.parse(rawAttributes);\n } catch (e) {\n log.warn(warningMessage, e);\n }\n }\n\n return attributes;\n}\n\n/**\n * Construct URI with query parameters\n */\nclass UriBuilder {\n private base: string;\n private args: string[];\n private paths: string[];\n\n constructor(base: string) {\n this.base = base.replace(/\\/$/, \"\");\n this.args = [];\n this.paths = [];\n }\n\n public arg(name: string, value: string | number | boolean): UriBuilder {\n if (typeof value !== \"undefined\") {\n this.args.push(\n encodeURIComponent(name) + \"=\" + encodeURIComponent(value)\n );\n }\n return this;\n }\n\n public path(name: string): UriBuilder {\n this.paths.push(encodeURIComponent(name));\n return this;\n }\n\n public build(): string {\n let result = this.base;\n if (this.paths.length) {\n result += \"/\" + this.paths.join(\"/\");\n }\n\n if (this.args.length) {\n result += \"?\" + this.args.join(\"&\");\n }\n return result;\n }\n}\n\nexport { deepClone, UriBuilder, parseToNumber, parseTime, parseAttributes };\n","import { custom } from \"@twilio/declarative-type-validator\";\n\n// Any JSON value\nexport const attributesValidator = custom((value) => [\n [\"string\", \"number\", \"boolean\", \"object\"].includes(typeof value),\n \"a JSON type\",\n]);\n\nexport const optionalAttributesValidator = custom((value) => [\n [\"undefined\", \"string\", \"number\", \"boolean\", \"object\"].includes(typeof value),\n \"an optional JSON type\",\n]);\n","import { Logger } from \"./logger\";\nimport { SyncClient } from \"twilio-sync\";\nimport { parseAttributes } from \"./util\";\nimport { validateTypesAsync } from \"@twilio/declarative-type-validator\";\nimport { attributesValidator } from \"./interfaces/attributes\";\nimport { Configuration } from \"./configuration\";\nimport { CommandExecutor } from \"./command-executor\";\nimport {\n EditUserRequest,\n EditUserResponse,\n} from \"./interfaces/commands/edit-user\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport isEqual from \"lodash.isequal\";\nimport { JSONValue } from \"./types\";\n\ntype UserEvents = {\n updated: (data: { user: User; updateReasons: UserUpdateReason[] }) => void;\n userSubscribed: (user: User) => void;\n userUnsubscribed: (user: User) => void;\n};\n\nconst log = Logger.scope(\"User\");\n\ninterface UserState {\n identity: string;\n entityName: string;\n friendlyName: string | null;\n attributes: JSONValue;\n online: boolean | null;\n notifiable: boolean | null;\n}\n\ninterface UpdateValue {\n value: string;\n notifiable: boolean | null;\n online: boolean | null;\n}\n\ninterface UserServices {\n syncClient: SyncClient;\n commandExecutor: CommandExecutor;\n}\n\ninterface UserLinks {\n self: string;\n}\n\ntype SubscriptionState = \"initializing\" | \"subscribed\" | \"unsubscribed\";\n\n/**\n * The reason for the `updated` event being emitted by a user.\n */\ntype UserUpdateReason =\n | \"friendlyName\"\n | \"attributes\"\n | \"reachabilityOnline\"\n | \"reachabilityNotifiable\";\n\ninterface UserUpdatedEventArgs {\n user: User;\n updateReasons: UserUpdateReason[];\n}\n\n/**\n * Extended user information.\n * Note that `isOnline` and `isNotifiable` properties are eligible\n * for use only if the reachability function is enabled.\n * You may check if it is enabled by reading the value of {@link Client.reachabilityEnabled}.\n */\nclass User extends ReplayEventEmitter<UserEvents> {\n private links!: UserLinks;\n private configuration!: Configuration;\n private readonly services: UserServices;\n\n private entity;\n private state: UserState;\n private promiseToFetch: Promise<User> | null = null;\n private subscribed: SubscriptionState;\n\n private _initializationPromise: Promise<void>;\n private _resolveInitializationPromise;\n\n /**\n * @internal\n */\n constructor(\n identity: string,\n entityName: string,\n configuration: Configuration | null,\n services: UserServices\n ) {\n super();\n\n this.services = services;\n\n this.subscribed = \"initializing\";\n this.setMaxListeners(0);\n\n this.state = {\n identity,\n entityName,\n friendlyName: null,\n attributes: {},\n online: null,\n notifiable: null,\n };\n\n this._initializationPromise = new Promise((resolve) => {\n this._resolveInitializationPromise = resolve;\n });\n\n if (configuration !== null) {\n this._resolveInitialization(configuration, identity, entityName, false);\n }\n }\n\n /**\n * Fired when the properties or the reachability status of the message has been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the following properties:\n * * {@link User} `user` - the user in question\n * * {@link UserUpdateReason}[] `updateReasons` - array of reasons for the update\n * @event\n */\n public readonly updated = \"updated\";\n\n /**\n * Fired when the client has subscribed to the user.\n *\n * Parameters:\n * 1. {@link User} `user` - the user in question\n * @event\n */\n public readonly userSubscribed = \"userSubscribed\";\n\n /**\n * Fired when the client has unsubscribed from the user.\n *\n * Parameters:\n * 1. {@link User} `user` - the user in question\n * @event\n */\n public readonly userUnsubscribed = \"userUnsubscribed\";\n\n /**\n * User identity.\n */\n public get identity(): string {\n return this.state.identity;\n }\n\n public set identity(identity: string) {\n this.state.identity = identity;\n }\n\n public set entityName(name: string) {\n this.state.entityName = name;\n }\n\n /**\n * Custom attributes of the user.\n */\n public get attributes() {\n return this.state.attributes;\n }\n\n /**\n * Friendly name of the user, null if not set.\n */\n public get friendlyName(): string | null {\n return this.state.friendlyName;\n }\n\n /**\n * Status of the real-time conversation connection of the user.\n */\n public get isOnline(): boolean | null {\n return this.state.online;\n }\n\n /**\n * User push notification registration status.\n */\n public get isNotifiable(): boolean | null {\n return this.state.notifiable;\n }\n\n /**\n * True if this user is receiving real-time status updates.\n */\n public get isSubscribed(): boolean {\n return this.subscribed == \"subscribed\";\n }\n\n // Handles service updates\n async _update(\n key: string,\n value: { value: string; notifiable: boolean | null; online: boolean | null }\n ) {\n await this._initializationPromise;\n\n const updateReasons: UserUpdateReason[] = [];\n log.debug(\"User for\", this.state.identity, \"updated:\", key, value);\n switch (key) {\n case \"friendlyName\":\n if (this.state.friendlyName !== value.value) {\n updateReasons.push(\"friendlyName\");\n this.state.friendlyName = value.value;\n }\n break;\n case \"attributes\":\n const updateAttributes = parseAttributes(\n value.value,\n `Retrieved malformed attributes from the server for user: ${this.state.identity}`,\n log\n );\n if (!isEqual(this.state.attributes, updateAttributes)) {\n this.state.attributes = updateAttributes;\n updateReasons.push(\"attributes\");\n }\n break;\n case \"reachability\":\n if (this.state.online !== value.online) {\n this.state.online = value.online;\n updateReasons.push(\"reachabilityOnline\");\n }\n if (this.state.notifiable !== value.notifiable) {\n this.state.notifiable = value.notifiable;\n updateReasons.push(\"reachabilityNotifiable\");\n }\n break;\n default:\n return;\n }\n if (updateReasons.length > 0) {\n this.emit(\"updated\", { user: this, updateReasons: updateReasons });\n }\n }\n\n // Fetch reachability info\n private async _updateReachabilityInfo(map, update) {\n await this._initializationPromise;\n\n if (!this.configuration.reachabilityEnabled) {\n return Promise.resolve();\n }\n\n return map\n .get(\"reachability\")\n .then(update)\n .catch((err) => {\n log.warn(\n \"Failed to get reachability info for \",\n this.state.identity,\n err\n );\n });\n }\n\n // Fetch user\n async _fetch(): Promise<User> {\n await this._initializationPromise;\n\n if (!this.state.entityName) {\n return this;\n }\n\n this.promiseToFetch = this.services.syncClient\n .map({\n id: this.state.entityName,\n mode: \"open_existing\",\n includeItems: true,\n })\n .then((map) => {\n this.entity = map;\n map.on(\"itemUpdated\", (args) => {\n log.debug(\n this.state.entityName +\n \" (\" +\n this.state.identity +\n \") itemUpdated: \" +\n args.item.key\n );\n return this._update(args.item.key, args.item.data);\n });\n return Promise.all([\n map\n .get(\"friendlyName\")\n .then((item) => this._update(item.key, item.data as UpdateValue)),\n map\n .get(\"attributes\")\n .then((item) => this._update(item.key, item.data as UpdateValue)),\n this._updateReachabilityInfo(map, (item) =>\n this._update(item.key, item.data)\n ),\n ]);\n })\n .then(() => {\n log.debug(\"Fetched for\", this.identity);\n this.subscribed = \"subscribed\";\n this.emit(\"userSubscribed\", this);\n return this;\n })\n .catch((err) => {\n this.promiseToFetch = null;\n throw err;\n });\n return this.promiseToFetch;\n }\n\n async _ensureFetched() {\n await this._initializationPromise;\n return this.promiseToFetch || this._fetch();\n }\n\n /**\n * Edit user attributes.\n * @param attributes New attributes.\n */\n @validateTypesAsync(attributesValidator)\n public async updateAttributes(attributes: JSONValue): Promise<User> {\n await this._initializationPromise;\n\n if (this.subscribed == \"unsubscribed\") {\n throw new Error(\"Can't modify unsubscribed object\");\n }\n\n await this.services.commandExecutor.mutateResource<\n EditUserRequest,\n EditUserResponse\n >(\"post\", this.links.self, {\n attributes: JSON.stringify(attributes),\n });\n\n return this;\n }\n\n /**\n * Update the friendly name of the user.\n * @param friendlyName New friendly name.\n */\n @validateTypesAsync([\"string\"])\n public async updateFriendlyName(friendlyName: string): Promise<User> {\n await this._initializationPromise;\n\n if (this.subscribed == \"unsubscribed\") {\n throw new Error(\"Can't modify unsubscribed object\");\n }\n\n await this.services.commandExecutor.mutateResource<\n EditUserRequest,\n EditUserResponse\n >(\"post\", this.links.self, {\n friendly_name: friendlyName,\n });\n\n return this;\n }\n\n /**\n * Remove the user from the subscription list.\n * @return A promise of completion.\n */\n async unsubscribe(): Promise<void> {\n await this._initializationPromise;\n\n if (this.promiseToFetch) {\n await this.promiseToFetch;\n this.entity.close();\n this.promiseToFetch = null;\n this.subscribed = \"unsubscribed\";\n this.emit(\"userUnsubscribed\", this);\n }\n }\n\n public _resolveInitialization(\n configuration: Configuration,\n identity: string,\n entityName: string,\n emitUpdated: boolean\n ): void {\n this.configuration = configuration;\n this.identity = identity;\n this.entityName = entityName;\n this.links = {\n self: `${this.configuration.links.users}/${this.identity}`,\n };\n this._resolveInitializationPromise();\n\n if (emitUpdated) {\n this.emit(\"updated\", {\n user: this,\n updateReasons: [\n \"friendlyName\",\n \"attributes\",\n \"reachabilityOnline\",\n \"reachabilityNotifiable\",\n ],\n });\n }\n }\n}\n\nexport {\n User,\n UserServices,\n SubscriptionState,\n UserUpdateReason,\n UserUpdatedEventArgs,\n};\n","import { Retrier } from \"@twilio/operation-retrier\";\nimport { Transport, TransportResult } from \"twilsock\";\nimport { Configuration } from \"../configuration\";\n\nimport Timeout = NodeJS.Timeout;\n\ninterface CacheEntry {\n response: TransportResult<unknown>;\n timestamp: number;\n}\n\nexport interface NetworkServices {\n transport: Transport;\n}\n\nclass Network {\n private readonly configuration: Configuration;\n private readonly services: NetworkServices;\n private cacheLifetime: number;\n\n private readonly cache: Map<string, CacheEntry>;\n private timer!: number | NodeJS.Timeout;\n\n constructor(configuration, services) {\n this.configuration = configuration;\n this.services = services;\n this.cache = new Map<string, CacheEntry>();\n this.cacheLifetime = this.configuration.httpCacheInterval * 100;\n this.cleanupCache();\n }\n\n private isExpired(timestamp: number): boolean {\n return !this.cacheLifetime || Date.now() - timestamp > this.cacheLifetime;\n }\n\n private cleanupCache() {\n for (const [k, v] of this.cache) {\n if (this.isExpired(v.timestamp)) {\n this.cache.delete(k);\n }\n }\n\n if (this.cache.size === 0) {\n clearInterval(this.timer as Timeout);\n }\n }\n\n pokeTimer() {\n this.timer =\n this.timer ||\n setInterval(() => this.cleanupCache(), this.cacheLifetime * 2);\n }\n\n private executeWithRetry<T>(\n request,\n retryWhenThrottled = false\n ): Promise<TransportResult<T>> {\n return new Promise((resolve, reject) => {\n const codesToRetryOn = [502, 503, 504];\n if (retryWhenThrottled) {\n codesToRetryOn.push(429);\n }\n\n const retrier = new Retrier(this.configuration.backoffConfiguration);\n retrier.on(\"attempt\", () => {\n request()\n .then((result) => retrier.succeeded(result))\n .catch((err) => {\n if (codesToRetryOn.indexOf(err.status) > -1) {\n retrier.failed(err);\n } else if (err.message === \"Twilsock disconnected\") {\n // Ugly hack. We must make a proper exceptions for twilsock\n retrier.failed(err);\n } else {\n // Fatal error\n retrier.removeAllListeners();\n retrier.cancel();\n reject(err);\n }\n });\n });\n\n retrier.on(\"succeeded\", (result) => {\n resolve(result);\n });\n retrier.on(\"cancelled\", (err) => reject(err));\n retrier.on(\"failed\", (err) => reject(err));\n\n retrier.start();\n });\n }\n\n async get<T>(url: string): Promise<TransportResult<T>> {\n const cacheEntry = this.cache.get(url);\n if (cacheEntry && !this.isExpired(cacheEntry.timestamp)) {\n return cacheEntry.response as TransportResult<T>;\n }\n\n const headers = {};\n const response = await this.executeWithRetry<T>(\n () =>\n this.services.transport.get<T>(\n url,\n headers,\n this.configuration.productId\n ),\n this.configuration.retryWhenThrottled\n );\n this.cache.set(url, { response, timestamp: Date.now() });\n this.pokeTimer();\n return response;\n }\n}\n\nexport { Network };\n","class NotificationTypes {\n static readonly TYPING_INDICATOR = \"twilio.ipmsg.typing_indicator\";\n static readonly NEW_MESSAGE = \"twilio.conversations.new_message\";\n static readonly ADDED_TO_CONVERSATION =\n \"twilio.conversations.added_to_conversation\";\n // static readonly INVITED_TO_CHANNEL = 'twilio.channel.invited_to_channel';\n static readonly REMOVED_FROM_CONVERSATION =\n \"twilio.conversations.removed_from_conversation\";\n static readonly CONSUMPTION_UPDATE = \"twilio.channel.consumption_update\";\n}\n\nexport { NotificationTypes };\n","import { Users } from \"./data/users\";\nimport { User } from \"./user\";\nimport { parseTime, parseAttributes } from \"./util\";\nimport { Logger } from \"./logger\";\nimport { Conversation } from \"./conversation\";\nimport { attributesValidator } from \"./interfaces/attributes\";\nimport { validateTypesAsync } from \"@twilio/declarative-type-validator\";\nimport { CommandExecutor } from \"./command-executor\";\nimport { EditParticipantRequest } from \"./interfaces/commands/edit-participant\";\nimport { ParticipantResponse } from \"./interfaces/commands/participant-response\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport isEqual from \"lodash.isequal\";\nimport { JSONValue } from \"./types\";\n\ntype ParticipantEvents = {\n typingEnded: (participant: Participant) => void;\n typingStarted: (participant: Participant) => void;\n updated: (data: {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n }) => void;\n};\n\nconst log = Logger.scope(\"Participant\");\n\ninterface ParticipantDescriptor {\n attributes?: JSONValue;\n dateCreated: Date | null;\n dateUpdated: Date | null;\n identity: string;\n roleSid?: string;\n lastConsumedMessageIndex: number | null;\n lastConsumptionTimestamp: number;\n type: ParticipantType;\n userInfo: string;\n bindings?: ParticipantBindings;\n}\n\ninterface ParticipantState {\n attributes: JSONValue;\n dateCreated: Date | null;\n dateUpdated: Date | null;\n identity: string;\n isTyping: boolean;\n lastReadMessageIndex: number | null;\n lastReadTimestamp: Date | null;\n roleSid: string;\n sid: string;\n type: ParticipantType;\n typingTimeout: number | null;\n userInfo: string;\n bindings?: ParticipantBindings;\n}\n\ninterface ParticipantServices {\n users: Users;\n commandExecutor: CommandExecutor;\n}\n\ninterface ParticipantLinks {\n self: string;\n}\n\n/**\n * The reason for the `updated` event being emitted by a participant.\n */\ntype ParticipantUpdateReason =\n | \"attributes\"\n | \"dateCreated\"\n | \"dateUpdated\"\n | \"roleSid\"\n | \"lastReadMessageIndex\"\n | \"lastReadTimestamp\"\n | \"bindings\";\n\n/**\n * Type of a participant.\n */\ntype ParticipantType = \"chat\" | \"sms\" | \"whatsapp\" | \"email\";\n\ninterface ParticipantUpdatedEventArgs {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n}\n\n/**\n * Bindings for conversation participant.\n */\ninterface ParticipantBindings {\n email?: ParticipantEmailBinding;\n}\n\n/**\n * Email participation level.\n * to = to/from\n * cc = cc\n */\ntype ParticipantEmailLevel = \"to\" | \"cc\";\n\n/**\n * Bindings for email participant.\n */\ninterface ParticipantEmailBinding {\n name: string;\n address: string;\n level: ParticipantEmailLevel;\n}\n\n/**\n * A participant represents a remote client in a conversation.\n */\nclass Participant extends ReplayEventEmitter<ParticipantEvents> {\n private state: ParticipantState;\n private readonly links: ParticipantLinks;\n private readonly services: ParticipantServices;\n\n /**\n * Conversation that the remote client is a participant of.\n */\n public readonly conversation: Conversation;\n\n /**\n * The server-assigned unique identifier for the participant.\n */\n public get sid(): string {\n return this.state.sid;\n }\n\n /**\n * Custom attributes of the participant.\n */\n public get attributes(): JSONValue {\n return this.state.attributes;\n }\n\n /**\n * Date this participant was created on.\n */\n public get dateCreated(): Date | null {\n return this.state.dateCreated;\n }\n\n /**\n * Date this participant was last updated on.\n */\n public get dateUpdated(): Date | null {\n return this.state.dateUpdated;\n }\n\n /**\n * Identity of the participant.\n */\n public get identity(): string | null {\n return this.state.identity;\n }\n\n /**\n * Indicates whether the participant is currently typing.\n */\n public get isTyping(): boolean {\n return this.state.isTyping;\n }\n\n /**\n * The index of the last read message by the participant.\n * Note that retrieving messages on a client endpoint does not mean that messages are read,\n * please consider reading about the [Read Horizon feature](https://www.twilio.com/docs/api/chat/guides/consumption-horizon)\n * to find out about the proper way to mark messages as read.\n */\n public get lastReadMessageIndex(): number | null {\n return this.state.lastReadMessageIndex;\n }\n\n /**\n * Date of the most recent read horizon update.\n */\n public get lastReadTimestamp(): Date | null {\n return this.state.lastReadTimestamp;\n }\n\n public get roleSid(): string {\n return this.state.roleSid;\n }\n\n /**\n * Type of the participant.\n */\n public get type(): ParticipantType {\n return this.state.type;\n }\n\n /**\n * Get the bindings mapping for the current participant.\n * Available binding depends on the participant type.\n * You could access it as `participant.bindings.sms?.address` or\n * using the type dynamically `participant.bindings[participant.type]`\n * just be aware that the binding information has different structure for\n * each participant type.\n * See also {ParticipantEmailBinding}, the only available currently binding descriptor.\n */\n public get bindings(): ParticipantBindings {\n return this.state.bindings ?? {};\n }\n\n /**\n * @internal\n */\n constructor(\n data: ParticipantDescriptor,\n sid: string,\n conversation: Conversation,\n links: ParticipantLinks,\n services: ParticipantServices\n ) {\n super();\n\n this.conversation = conversation;\n this.links = links;\n this.services = services;\n this.state = {\n attributes: parseAttributes(\n data.attributes,\n \"Retrieved malformed attributes from the server for participant: \" +\n sid,\n log\n ),\n dateCreated: data.dateCreated ? parseTime(data.dateCreated) : null,\n dateUpdated: data.dateCreated ? parseTime(data.dateUpdated) : null,\n sid: sid,\n typingTimeout: null,\n isTyping: false,\n identity: data.identity,\n roleSid: data.roleSid ?? \"\",\n lastReadMessageIndex: Number.isInteger(data.lastConsumedMessageIndex)\n ? data.lastConsumedMessageIndex\n : null,\n lastReadTimestamp: data.lastConsumptionTimestamp\n ? parseTime(data.lastConsumptionTimestamp)\n : null,\n type: data.type || \"chat\",\n userInfo: data.userInfo,\n bindings: data.bindings ?? {},\n };\n\n if (!data.identity && !data.type) {\n throw new Error(\n \"Received invalid Participant object from server: Missing identity or type of Participant.\"\n );\n }\n }\n\n /**\n * Fired when the participant has started typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant in question\n * @event\n */\n static readonly typingStarted = \"typingStarted\";\n\n /**\n * Fired when the participant has stopped typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant in question\n * @event\n */\n static readonly typingEnded = \"typingEnded\";\n\n /**\n * Fired when the fields of the participant have been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the following properties:\n * * {@link Participant} participant - the participant in question\n * * {@link ParticipantUpdateReason}[] updateReasons - array of reasons for the update\n * @event\n */\n static readonly updated = \"updated\";\n\n /**\n * Internal method used to start or reset the typing indicator timeout (with event emitting).\n * @internal\n */\n _startTyping(timeout) {\n if (this.state.typingTimeout) {\n clearTimeout(this.state.typingTimeout);\n }\n\n this.state.isTyping = true;\n this.emit(\"typingStarted\", this);\n\n this.conversation.emit(\"typingStarted\", this);\n\n this.state.typingTimeout = Number(\n setTimeout(() => this._endTyping(), timeout)\n );\n return this;\n }\n\n /**\n * Internal method function used to stop the typing indicator timeout (with event emitting).\n * @internal\n */\n _endTyping() {\n if (!this.state.typingTimeout) {\n return;\n }\n\n this.state.isTyping = false;\n this.emit(\"typingEnded\", this);\n\n this.conversation.emit(\"typingEnded\", this);\n\n clearInterval(this.state.typingTimeout);\n this.state.typingTimeout = null;\n }\n\n /**\n * Internal method function used update local object's property roleSid with a new value.\n * @internal\n */\n _update(data) {\n const updateReasons: ParticipantUpdateReason[] = [];\n\n const updateAttributes = parseAttributes(\n data.attributes,\n \"Retrieved malformed attributes from the server for participant: \" +\n this.state.sid,\n log\n );\n\n if (data.attributes && !isEqual(this.state.attributes, updateAttributes)) {\n this.state.attributes = updateAttributes;\n updateReasons.push(\"attributes\");\n }\n\n const updatedDateUpdated = parseTime(data.dateUpdated);\n if (\n data.dateUpdated &&\n updatedDateUpdated?.getTime() !==\n (this.state.dateUpdated && this.state.dateUpdated.getTime())\n ) {\n this.state.dateUpdated = updatedDateUpdated;\n updateReasons.push(\"dateUpdated\");\n }\n\n const updatedDateCreated = parseTime(data.dateCreated);\n if (\n data.dateCreated &&\n updatedDateCreated?.getTime() !==\n (this.state.dateCreated && this.state.dateCreated.getTime())\n ) {\n this.state.dateCreated = updatedDateCreated;\n updateReasons.push(\"dateCreated\");\n }\n\n if (data.roleSid && this.state.roleSid !== data.roleSid) {\n this.state.roleSid = data.roleSid;\n updateReasons.push(\"roleSid\");\n }\n\n if (\n (Number.isInteger(data.lastConsumedMessageIndex) ||\n data.lastConsumedMessageIndex === null) &&\n this.state.lastReadMessageIndex !== data.lastConsumedMessageIndex\n ) {\n this.state.lastReadMessageIndex = data.lastConsumedMessageIndex;\n updateReasons.push(\"lastReadMessageIndex\");\n }\n\n if (data.lastConsumptionTimestamp) {\n const lastReadTimestamp = new Date(data.lastConsumptionTimestamp);\n if (\n !this.state.lastReadTimestamp ||\n this.state.lastReadTimestamp.getTime() !== lastReadTimestamp.getTime()\n ) {\n this.state.lastReadTimestamp = lastReadTimestamp;\n updateReasons.push(\"lastReadTimestamp\");\n }\n }\n\n if (data.bindings && !isEqual(this.state.bindings, data.bindings)) {\n this.state.bindings = data.bindings;\n updateReasons.push(\"bindings\");\n }\n\n if (updateReasons.length > 0) {\n this.emit(\"updated\", { participant: this, updateReasons: updateReasons });\n }\n\n return this;\n }\n\n /**\n * Get the user for this participant and subscribes to it. Supported only for participants of type `chat`.\n */\n async getUser(): Promise<User> {\n if (this.type != \"chat\") {\n throw new Error(\n \"Getting User is not supported for this Participant type: \" + this.type\n );\n }\n\n return this.services.users.getUser(\n this.state.identity,\n this.state.userInfo\n );\n }\n\n /**\n * Remove the participant from the conversation.\n */\n async remove() {\n return this.conversation.removeParticipant(this);\n }\n\n /**\n * Update the attributes of the participant.\n * @param attributes New attributes.\n */\n @validateTypesAsync(attributesValidator)\n async updateAttributes(attributes: JSONValue): Promise<Participant> {\n await this.services.commandExecutor.mutateResource<\n EditParticipantRequest,\n ParticipantResponse\n >(\"post\", this.links.self, {\n attributes: JSON.stringify(attributes),\n });\n\n return this;\n }\n}\n\nexport {\n ParticipantDescriptor,\n ParticipantServices,\n Participant,\n ParticipantUpdateReason,\n ParticipantType,\n ParticipantUpdatedEventArgs,\n ParticipantBindings,\n ParticipantEmailBinding,\n ParticipantEmailLevel,\n};\n","import {\n ParticipantDescriptor,\n Participant,\n ParticipantUpdatedEventArgs,\n ParticipantUpdateReason,\n ParticipantEmailBinding,\n} from \"../participant\";\nimport { Logger } from \"../logger\";\n\nimport { Conversation } from \"../conversation\";\n\nimport { SyncMap, SyncClient } from \"twilio-sync\";\nimport { Users } from \"./users\";\nimport { CommandExecutor } from \"../command-executor\";\nimport { AddParticipantRequest } from \"../interfaces/commands/add-participant\";\nimport { Configuration } from \"../configuration\";\nimport { ParticipantResponse } from \"../interfaces/commands/participant-response\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport { JSONValue } from \"../types\";\n\ntype ParticipantsEvents = {\n participantJoined: (participant: Participant) => void;\n participantLeft: (participant: Participant) => void;\n participantUpdated: (data: {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n }) => void;\n};\n\nconst log = Logger.scope(\"Participants\");\n\nexport interface ParticipantsServices {\n syncClient: SyncClient;\n users: Users;\n commandExecutor: CommandExecutor;\n}\n\ninterface ParticipantsLinks {\n participants: string;\n}\n\nexport interface ParticipantBindingOptions {\n email?: ParticipantEmailBinding;\n}\n\n/**\n * @classdesc Represents the collection of participants for the conversation\n * @fires Participants#participantJoined\n * @fires Participants#participantLeft\n * @fires Participants#participantUpdated\n */\nclass Participants extends ReplayEventEmitter<ParticipantsEvents> {\n private readonly configuration: Configuration;\n private readonly services: ParticipantsServices;\n private readonly links: ParticipantsLinks;\n\n rosterEntityPromise: Promise<SyncMap> | null = null;\n\n public readonly conversation: Conversation;\n public readonly participants: Map<string, Participant>;\n\n constructor(\n conversation: Conversation,\n participants: Map<string, Participant>,\n links: ParticipantsLinks,\n configuration: Configuration,\n services: ParticipantsServices\n ) {\n super();\n this.conversation = conversation;\n this.participants = participants;\n this.links = links;\n this.configuration = configuration;\n this.services = services;\n }\n\n async unsubscribe(): Promise<void> {\n if (this.rosterEntityPromise) {\n const entity = await this.rosterEntityPromise;\n entity.close();\n this.rosterEntityPromise = null;\n }\n }\n\n subscribe(rosterObjectName: string) {\n return (this.rosterEntityPromise =\n this.rosterEntityPromise ||\n this.services.syncClient\n .map({ id: rosterObjectName, mode: \"open_existing\" })\n .then((rosterMap) => {\n rosterMap.on(\"itemAdded\", (args) => {\n log.debug(this.conversation.sid + \" itemAdded: \" + args.item.key);\n this.upsertParticipant(args.item.key, args.item.data).then(\n (participant) => {\n this.emit(\"participantJoined\", participant);\n }\n );\n });\n\n rosterMap.on(\"itemRemoved\", (args) => {\n log.debug(this.conversation.sid + \" itemRemoved: \" + args.key);\n const participantSid = args.key;\n if (!this.participants.has(participantSid)) {\n return;\n }\n const leftParticipant = this.participants.get(participantSid);\n this.participants.delete(participantSid);\n if (!leftParticipant) {\n return;\n }\n this.emit(\"participantLeft\", leftParticipant);\n });\n\n rosterMap.on(\"itemUpdated\", (args) => {\n log.debug(this.conversation.sid + \" itemUpdated: \" + args.item.key);\n this.upsertParticipant(args.item.key, args.item.data);\n });\n\n const participantsPromises: Promise<Participant>[] = [];\n const rosterMapHandler = (paginator) => {\n paginator.items.forEach((item) => {\n participantsPromises.push(\n this.upsertParticipant(item.key, item.data)\n );\n });\n return paginator.hasNextPage\n ? paginator.nextPage().then(rosterMapHandler)\n : null;\n };\n\n return rosterMap\n .getItems()\n .then(rosterMapHandler)\n .then(() => Promise.all(participantsPromises))\n .then(() => rosterMap);\n })\n .catch((err) => {\n this.rosterEntityPromise = null;\n if (this.services.syncClient.connectionState != \"disconnected\") {\n log.error(\n \"Failed to get roster object for conversation\",\n this.conversation.sid,\n err\n );\n }\n log.debug(\n \"ERROR: Failed to get roster object for conversation\",\n this.conversation.sid,\n err\n );\n throw err;\n }));\n }\n\n async upsertParticipant(\n participantSid: string,\n data: ParticipantDescriptor\n ): Promise<Participant> {\n let participant = this.participants.get(participantSid);\n if (participant) {\n return participant._update(data);\n }\n\n const links = {\n self: `${this.links.participants}/${participantSid}`,\n };\n\n participant = new Participant(\n data,\n participantSid,\n this.conversation,\n links,\n this.services\n );\n this.participants.set(participantSid, participant);\n participant.on(\"updated\", (args: ParticipantUpdatedEventArgs) =>\n this.emit(\"participantUpdated\", args)\n );\n return participant;\n }\n\n /**\n * @returns {Promise<Array<Participant>>} returns list of participants {@see Participant}\n */\n async getParticipants(): Promise<Participant[]> {\n return this.rosterEntityPromise\n ? this.rosterEntityPromise.then(() => {\n const participants: Participant[] = [];\n this.participants.forEach((participant) =>\n participants.push(participant)\n );\n return participants;\n })\n : [];\n }\n\n /**\n * Get participant by SID from conversation\n * @returns {Promise<Participant>}\n */\n async getParticipantBySid(\n participantSid: string\n ): Promise<Participant | null> {\n return this.rosterEntityPromise\n ? this.rosterEntityPromise.then(() => {\n const participant = this.participants.get(participantSid);\n if (!participant) {\n throw new Error(\n \"Participant with SID \" + participantSid + \" was not found\"\n );\n }\n return participant;\n })\n : null;\n }\n\n /**\n * Get participant by identity from conversation\n * @returns {Promise<Participant>}\n */\n async getParticipantByIdentity(\n identity: string\n ): Promise<Participant | null> {\n let foundParticipant: Participant | null = null;\n return this.rosterEntityPromise\n ? this.rosterEntityPromise.then(() => {\n this.participants.forEach((participant) => {\n if (participant.identity === identity) {\n foundParticipant = participant;\n }\n });\n if (!foundParticipant) {\n throw new Error(\n \"Participant with identity \" + identity + \" was not found\"\n );\n }\n return foundParticipant;\n })\n : null;\n }\n\n /**\n * Add a chat participant to the conversation\n * @returns {Promise<ParticipantResponse>}\n */\n async add(\n identity: string,\n attributes: JSONValue\n ): Promise<ParticipantResponse> {\n return await this.services.commandExecutor.mutateResource<\n AddParticipantRequest,\n ParticipantResponse\n >(\"post\", this.links.participants, {\n identity,\n attributes:\n typeof attributes !== \"undefined\"\n ? JSON.stringify(attributes)\n : undefined,\n });\n }\n\n /**\n * Add a non-chat participant to the conversation.\n *\n * @param proxyAddress\n * @param address\n * @param attributes\n * @param bindingOptions\n * @returns {Promise<any>}\n */\n addNonChatParticipant(\n proxyAddress: string,\n address: string,\n attributes: JSONValue = {},\n bindingOptions: ParticipantBindingOptions = {}\n ): Promise<ParticipantResponse> {\n return this.services.commandExecutor.mutateResource<\n AddParticipantRequest,\n ParticipantResponse\n >(\"post\", this.links.participants, {\n attributes:\n typeof attributes !== \"undefined\"\n ? JSON.stringify(attributes)\n : undefined,\n messaging_binding: {\n address,\n proxy_address: proxyAddress,\n name: bindingOptions?.email?.name,\n level: bindingOptions?.email?.level,\n },\n });\n }\n\n /**\n * Remove the participant with a given identity from a conversation.\n */\n remove(identity: string): Promise<void> {\n return this.services.commandExecutor.mutateResource(\n \"delete\",\n `${this.links.participants}/${identity}`\n );\n }\n}\n\nexport { Participants };\n\n/**\n * Fired when participant joined conversation\n * @event Participants#participantJoined\n * @type {Participant}\n */\n\n/**\n * Fired when participant left conversation\n * @event Participants#participantLeft\n * @type {Participant}\n */\n\n/**\n * Fired when participant updated\n * @event Participants#participantUpdated\n * @type {Object}\n * @property {Participant} participant - Updated Participant\n * @property {Participant#UpdateReason[]} updateReasons - Array of Participant's updated event reasons\n */\n","import {\n McsClient,\n McsMedia,\n MediaCategory as McsMediaCategory,\n} from \"@twilio/mcs-client\";\n\n/**\n * Category of media. Possible values are as follows:\n * * `'media'`\n * * `'body'`\n * * `'history'`\n */\ntype MediaCategory = McsMediaCategory;\n\ninterface MediaState {\n sid: string;\n category: MediaCategory;\n filename: string | null;\n contentType: string;\n size: number;\n}\n\ninterface MediaServices {\n mcsClient: McsClient;\n}\n\n/**\n * Represents a media information for a message in a conversation.\n */\nclass Media {\n private state: MediaState;\n private services: MediaServices;\n private mcsMedia: McsMedia | null = null;\n\n /**\n * @internal\n */\n constructor(data: MediaState | McsMedia, services: MediaServices) {\n this.services = services;\n\n if (data instanceof McsMedia) {\n this.mcsMedia = data as McsMedia;\n }\n\n this.state = {\n sid: data.sid,\n category: data.category,\n filename: data.filename,\n contentType: data.contentType,\n size: data.size,\n };\n }\n\n /**\n * Server-assigned unique identifier for the media.\n */\n public get sid(): string {\n return this.state.sid;\n }\n\n /**\n * File name. Null if absent.\n */\n public get filename(): string | null {\n return this.state.filename;\n }\n\n /**\n * Content type of the media.\n */\n public get contentType(): string {\n return this.state.contentType;\n }\n\n /**\n * Size of the media in bytes.\n */\n public get size(): number {\n return this.state.size;\n }\n\n /**\n * Media category, can be one of the {@link MediaCategory} values.\n */\n public get category(): MediaCategory {\n return this.state.category;\n }\n\n /**\n * Returns the direct content URL for the media.\n *\n * This URL is impermanent, it will expire in several minutes and cannot be cached.\n * If the URL becomes expired, you need to request a new one.\n * Each call to this function produces a new temporary URL.\n */\n public async getContentTemporaryUrl(): Promise<string | null> {\n await this._fetchMcsMedia();\n return this.mcsMedia?.getContentUrl() ?? null;\n }\n\n /**\n * Returns cached direct content URL for the media.\n *\n * This URL will expire in several minutes. This function does not refresh the URL and can be used to query it several times\n * without causing network traffic.\n * If the URL becomes expired, you need to request a new one using getContentTemporaryUrl().\n *\n * @returns {Promise<String>}\n */\n public async getCachedTemporaryUrl(): Promise<string | null> {\n await this._fetchMcsMedia();\n return this.mcsMedia?.getCachedContentUrl() ?? null;\n }\n\n private async _fetchMcsMedia() {\n if (!this.mcsMedia) {\n if (this.services.mcsClient) {\n this.mcsMedia = await this.services.mcsClient.get(this.state.sid);\n } else {\n throw new Error(\"Media Content Service is unavailable\");\n }\n }\n }\n}\n\nexport { Media, MediaState, MediaServices, MediaCategory };\n","/**\n * Signifies the amount of participants which have the status for the message.\n */\ntype DeliveryAmount = \"none\" | \"some\" | \"all\";\n\ninterface AggregatedDeliveryDescriptor {\n total: number;\n delivered: DeliveryAmount;\n failed: DeliveryAmount;\n read: DeliveryAmount;\n sent: DeliveryAmount;\n undelivered: DeliveryAmount;\n}\n\n/**\n * Contains aggregated information about delivery statuses of a message across all participants\n * of a conversation.\n *\n * At any moment during the message delivery to a participant, the message can have zero or more of following\n * delivery statuses:\n * * Message is considered as **sent** to a participant if the nearest upstream carrier accepted the message.\n * * Message is considered as **delivered** to a participant if Twilio has received confirmation of message\n * delivery from the upstream carrier, and, where available, the destination handset.\n * * Message considered as **undelivered** to a participant if Twilio has received a delivery receipt\n * indicating that the message was not delivered. This can happen for many reasons including carrier content\n * filtering and the availability of the destination handset.\n * * Message considered as **read** by a participant if the message has been delivered and opened by the\n * recipient in a conversation. The recipient must have enabled the read receipts.\n * * Message considered as **failed** to be delivered to a participant if the message could not be sent.\n * This can happen for various reasons including queue overflows, account suspensions and media\n * errors (in the case of MMS for instance).\n *\n * {@link AggregatedDeliveryReceipt} class contains an aggregated value {@link DeliveryAmount} for each delivery status.\n */\nclass AggregatedDeliveryReceipt {\n private state: AggregatedDeliveryDescriptor;\n\n /**\n * @internal\n */\n constructor(data: AggregatedDeliveryDescriptor) {\n this.state = data;\n }\n\n /**\n * Maximum number of delivery events expected for the message.\n */\n public get total(): number {\n return this.state.total;\n }\n\n /**\n * Message is considered as **sent** to a participant if the nearest upstream carrier accepted the message.\n *\n * @return Amount of participants that have the **sent** delivery status for the message.\n */\n public get sent(): DeliveryAmount {\n return this.state.sent;\n }\n\n /**\n * Message is considered as **delivered** to a participant if Twilio has received confirmation of message\n * delivery from the upstream carrier, and, where available, the destination handset.\n *\n * @return Amount of participants that have the **delivered** delivery status for the message.\n */\n public get delivered(): DeliveryAmount {\n return this.state.delivered;\n }\n\n /**\n * Message is considered as **read** by a participant, if the message has been delivered and opened by the\n * recipient in a conversation. The recipient must have enabled the read receipts.\n *\n * @return Amount of participants that have the **read** delivery status for the message.\n */\n public get read(): DeliveryAmount {\n return this.state.read;\n }\n\n /**\n * Message is considered as **undelivered** to a participant if Twilio has received a delivery receipt\n * indicating that the message was not delivered. This can happen for many reasons including carrier content\n * filtering and the availability of the destination handset.\n *\n * @return Ammount of participants that have the **undelivered** delivery status for the message.\n */\n public get undelivered(): DeliveryAmount {\n return this.state.undelivered;\n }\n\n /**\n * Message is considered as **failed** to be delivered to a participant if the message could not be sent.\n * This can happen for various reasons including queue overflows, account suspensions and media\n * errors (in the case of MMS for instance). Twilio does not charge you for failed messages.\n *\n * @return Amount of participants that have the **failed** delivery status for the message.\n */\n public get failed(): DeliveryAmount {\n return this.state.failed;\n }\n\n _update(data: AggregatedDeliveryDescriptor): void {\n this.state = data;\n }\n\n _isEquals(data: AggregatedDeliveryDescriptor): boolean {\n const isTotalSame = this.total === data.total;\n const isSentSame = this.sent === data.sent;\n const isDeliveredSame = this.delivered === data.delivered;\n const isReadSame = this.read === data.read;\n const isUndeliveredSame = this.undelivered === data.undelivered;\n const isFailedSame = this.failed === data.failed;\n\n return (\n isTotalSame &&\n isSentSame &&\n isDeliveredSame &&\n isReadSame &&\n isUndeliveredSame &&\n isFailedSame\n );\n }\n}\n\nexport {\n AggregatedDeliveryReceipt,\n AggregatedDeliveryDescriptor,\n DeliveryAmount,\n};\n","import { Paginator } from \"./interfaces/paginator\";\n\ninterface PaginatorState<T> {\n source: (token: string) => Promise<RestPaginator<T>>;\n nextToken: string;\n prevToken: string;\n items: T[];\n}\n\n/**\n * Pagination helper class.\n */\nclass RestPaginator<T> implements Paginator<T> {\n private state: PaginatorState<T>;\n\n /**\n * Indicates the existence of the next page.\n */\n public get hasNextPage(): boolean {\n return !!this.state.nextToken;\n }\n\n /**\n * Indicates the existence of the previous page\n */\n public get hasPrevPage(): boolean {\n return !!this.state.prevToken;\n }\n\n /**\n * Array of elements on the current page.\n */\n public get items(): T[] {\n return this.state.items;\n }\n\n /**\n * @internal\n */\n constructor(items, source, prevToken, nextToken) {\n this.state = {\n prevToken,\n nextToken,\n source,\n items,\n };\n }\n\n /**\n * Request the next page. Does not modify the existing object.\n */\n nextPage(): Promise<RestPaginator<T>> {\n return this.hasNextPage\n ? this.state.source(this.state.nextToken)\n : Promise.reject(new Error(\"No next page\"));\n }\n\n /**\n * Request the previous page. Does not modify the existing object.\n */\n prevPage(): Promise<RestPaginator<T>> {\n return this.hasPrevPage\n ? this.state.source(this.state.prevToken)\n : Promise.reject(new Error(\"No previous page\"));\n }\n}\n\nexport { RestPaginator };\n","/**\n * Message delivery status.\n */\ntype DeliveryStatus =\n | \"sent\"\n | \"delivered\"\n | \"failed\"\n | \"read\"\n | \"undelivered\"\n | \"queued\";\n\ninterface DetailedDeliveryReceiptDescriptor {\n sid: string;\n message_sid: string;\n conversation_sid: string;\n channel_message_sid: string;\n participant_sid: string;\n status: DeliveryStatus;\n error_code: string | null;\n date_created: string;\n date_updated: string;\n}\n\n/**\n * Represents a delivery receipt of a message.\n */\nclass DetailedDeliveryReceipt {\n /**\n * Unique identifier for the delivery receipt.\n */\n sid: string;\n\n /**\n * Unique identifier for the message in the conversation.\n */\n messageSid: string;\n\n /**\n * Unique identifier for the conversation.\n */\n conversationSid: string;\n\n /**\n * Unique identifier for the `‘channel’` message (e.g., `WAxx` for WhatsApp, `SMxx` for SMS).\n */\n channelMessageSid: string;\n\n /**\n * Unique identifier for the participant.\n */\n participantSid: string;\n\n /**\n * Status of the message delivery.\n */\n status: DeliveryStatus;\n\n /**\n * Numeric error code mapped from Status callback code. Information about the error codes can be found\n * [here](https://www.twilio.com/docs/sms/api/message-resource#delivery-related-errors).\n */\n errorCode: string | 0;\n\n /**\n * Date this delivery receipt was created on.\n */\n dateCreated: string;\n\n /**\n * Date this delivery receipt was last updated on.\n */\n dateUpdated: string;\n\n /**\n * @internal\n */\n constructor(descriptor: DetailedDeliveryReceiptDescriptor) {\n this.sid = descriptor.sid;\n this.messageSid = descriptor.message_sid;\n this.conversationSid = descriptor.conversation_sid;\n this.channelMessageSid = descriptor.channel_message_sid;\n this.participantSid = descriptor.participant_sid;\n this.status = descriptor.status || \"queued\";\n this.errorCode = descriptor.error_code || 0;\n this.dateCreated = descriptor.date_created;\n this.dateUpdated = descriptor.date_updated;\n }\n}\n\nexport {\n DetailedDeliveryReceipt,\n DetailedDeliveryReceiptDescriptor,\n DeliveryStatus,\n};\n","import { parseAttributes, UriBuilder } from \"./util\";\nimport { Logger } from \"./logger\";\nimport { Conversation } from \"./conversation\";\nimport { McsClient, MediaCategory } from \"@twilio/mcs-client\";\nimport { Media } from \"./media\";\nimport { Participant } from \"./participant\";\nimport {\n AggregatedDeliveryDescriptor,\n AggregatedDeliveryReceipt,\n} from \"./aggregated-delivery-receipt\";\nimport {\n validateTypes,\n validateTypesAsync,\n nonEmptyString,\n custom,\n} from \"@twilio/declarative-type-validator\";\nimport { attributesValidator } from \"./interfaces/attributes\";\nimport { Network } from \"./services/network\";\nimport { RestPaginator } from \"./rest-paginator\";\nimport { DetailedDeliveryReceipt } from \"./detailed-delivery-receipt\";\nimport { Paginator } from \"./interfaces/paginator\";\nimport { Configuration } from \"./configuration\";\nimport { CommandExecutor } from \"./command-executor\";\nimport { EditMessageRequest } from \"./interfaces/commands/edit-message\";\nimport { MessageResponse } from \"./interfaces/commands/message-response\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport isEqual from \"lodash.isequal\";\nimport { JSONValue } from \"./types\";\nimport { ResponseMeta } from \"./interfaces/commands/response-meta\";\nimport { DeliveryReceiptResponse } from \"./interfaces/commands/delivery-receipt-response\";\n\ntype MessageEvents = {\n updated: (data: {\n message: Message;\n updateReasons: MessageUpdateReason[];\n }) => void;\n};\n\nconst log = Logger.scope(\"Message\");\n\ninterface MessageState {\n sid: string;\n index: number;\n author: string | null;\n subject: string | null;\n body: string | null;\n dateUpdated: Date | null;\n lastUpdatedBy: string | null;\n attributes: JSONValue;\n timestamp: Date | null;\n type: MessageType;\n media: Media | null;\n medias: Media[] | null;\n participantSid: string | null;\n aggregatedDeliveryReceipt: AggregatedDeliveryReceipt | null;\n}\n\ninterface MessageServices {\n mcsClient: McsClient;\n network: Network;\n commandExecutor: CommandExecutor;\n}\n\ninterface MessageLinks {\n self: string;\n conversation: string;\n messages_receipts: string;\n}\n\n/**\n * The reason for the `updated` event being emitted by a message.\n */\ntype MessageUpdateReason =\n | \"body\"\n | \"lastUpdatedBy\"\n | \"dateCreated\"\n | \"dateUpdated\"\n | \"attributes\"\n | \"author\"\n | \"deliveryReceipt\"\n | \"subject\";\n\n/**\n * Type of a message.\n */\ntype MessageType = \"text\" | \"media\";\n\ninterface MessageUpdatedEventArgs {\n message: Message;\n updateReasons: MessageUpdateReason[];\n}\n\nexport interface MessageData {\n sid: string;\n text?: string;\n type?: MessageType;\n author: string | null;\n subject: string | null;\n lastUpdatedBy?: string | null;\n attributes?: JSONValue;\n dateUpdated: string;\n timestamp?: string;\n medias?: Media[];\n media?: Media;\n memberSid?: string;\n delivery?: AggregatedDeliveryDescriptor;\n}\n\n/**\n * A message in a conversation.\n */\nclass Message extends ReplayEventEmitter<MessageEvents> {\n /**\n * Conversation that the message is in.\n */\n public readonly conversation: Conversation;\n\n private readonly links: MessageLinks;\n private readonly configuration: Configuration;\n private readonly services: MessageServices;\n\n private state: MessageState;\n\n /**\n * @internal\n */\n constructor(\n index: number,\n data: MessageData,\n conversation: Conversation,\n links: MessageLinks,\n configuration: Configuration,\n services: MessageServices\n ) {\n super();\n\n this.conversation = conversation;\n\n this.links = links;\n this.configuration = configuration;\n this.services = services;\n\n this.state = {\n sid: data.sid,\n index: index,\n author: data.author,\n subject: data.subject,\n body: data.text ?? null,\n timestamp: data.timestamp ? new Date(data.timestamp) : null,\n dateUpdated: data.dateUpdated ? new Date(data.dateUpdated) : null,\n lastUpdatedBy: data.lastUpdatedBy ?? null,\n attributes: parseAttributes(\n data.attributes,\n `Got malformed attributes for the message ${data.sid}`,\n log\n ),\n type: data.type ?? \"text\",\n media:\n data.type && data.type === \"media\" && data.media\n ? new Media(data.media, this.services)\n : null,\n medias:\n data.type && data.type === \"media\" && data.medias\n ? data.medias.map((m) => new Media(m, this.services))\n : null,\n participantSid: data.memberSid ?? null,\n aggregatedDeliveryReceipt: data.delivery\n ? new AggregatedDeliveryReceipt(data.delivery)\n : null,\n };\n }\n\n /**\n * Fired when the properties or the body of the message has been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the following properties:\n * * {@link Message} message - the message in question\n * * {@link MessageUpdateReason}[] updateReasons - array of reasons for the update\n */\n static readonly updated = \"updated\";\n\n /**\n * The server-assigned unique identifier for the message.\n */\n public get sid(): string {\n return this.state.sid;\n }\n\n /**\n * Name of the user that sent the message.\n */\n public get author(): string | null {\n return this.state.author;\n }\n\n /**\n * Message subject. Used only in email conversations.\n */\n public get subject(): string | null {\n return this.state.subject;\n }\n\n /**\n * Body of the message.\n */\n public get body(): string | null {\n return this.state.body;\n }\n\n /**\n * Date this message was last updated on.\n */\n public get dateUpdated(): Date | null {\n return this.state.dateUpdated;\n }\n\n /**\n * Index of the message in the conversation's messages list.\n * By design of the Conversations system, the message indices may have arbitrary gaps between them,\n * that does not necessarily mean they were deleted or otherwise modified - just that\n * messages may have some non-contiguous indices even if they are being sent immediately one after another.\n *\n * Trying to use indices for some calculations is going to be unreliable.\n *\n * To calculate the number of unread messages it is better to use the read horizon API.\n * See {@link Conversation.getUnreadMessagesCount} for details.\n */\n public get index(): number {\n return this.state.index;\n }\n\n /**\n * Identity of the last user that updated the message.\n */\n public get lastUpdatedBy(): string | null {\n return this.state.lastUpdatedBy;\n }\n\n /**\n * Date this message was created on.\n */\n public get dateCreated(): Date | null {\n return this.state.timestamp;\n }\n\n /**\n * Custom attributes of the message.\n */\n public get attributes(): JSONValue {\n return this.state.attributes;\n }\n\n /**\n * Type of the message.\n */\n public get type(): MessageType {\n return this.state.type;\n }\n\n /**\n * One of the attached media (if present).\n * @deprecated Use attachedMedia instead. Note that the latter is now an array.\n */\n public get media(): Media | null {\n return this.state.media;\n }\n\n /**\n * Return all media attachments, except email body/history attachments, without temporary urls.\n */\n public get attachedMedia(): Array<Media> | null {\n return this.getMediaByCategory([\"media\"]);\n }\n\n /**\n * The server-assigned unique identifier of the authoring participant.\n */\n public get participantSid(): string | null {\n return this.state.participantSid;\n }\n\n /**\n * Aggregated information about the message delivery statuses across all participants of a conversation..\n */\n public get aggregatedDeliveryReceipt(): AggregatedDeliveryReceipt | null {\n return this.state.aggregatedDeliveryReceipt;\n }\n\n /**\n * Return a (possibly empty) array of media matching a specific set of categories.\n * Allowed category is so far only 'media'.\n * @param categories Array of categories to match.\n * @returns Array of media descriptors matching given categories.\n */\n public getMediaByCategory(\n categories: Array<MediaCategory>\n ): Array<Media> | null {\n return (this.state.medias ?? []).filter((m) =>\n categories.includes(m.category)\n );\n }\n\n /**\n * Get a media descriptor for an email body attachment of a provided type.\n * Allowed body types are returned in the Conversation.limits().emailBodiesAllowedMimeTypes array.\n * @param type Type of email body to request, defaults to `text/plain`.\n */\n @validateTypes([nonEmptyString, \"undefined\"])\n public getEmailBody(type = \"text/plain\"): Media | null {\n return (\n this.getMediaByCategory([\"body\"])\n ?.filter((m) => m.contentType == type)\n .shift() ?? null\n );\n }\n\n /**\n * Get a media descriptor for an email history attachment of a provided type.\n * Allowed body types are returned in the Conversation.limits().emailHistoriesAllowedMimeTypes array.\n * @param type Type of email history to request, defaults to `text/plain`.\n */\n @validateTypes([nonEmptyString, \"undefined\"])\n public getEmailHistory(type = \"text/plain\"): Media | null {\n return (\n this.getMediaByCategory([\"history\"])\n ?.filter((m) => m.contentType == type)\n .shift() ?? null\n );\n }\n\n _update(data) {\n const updateReasons: MessageUpdateReason[] = [];\n\n if (\n (data.text || typeof data.text === \"string\") &&\n data.text !== this.state.body\n ) {\n this.state.body = data.text;\n updateReasons.push(\"body\");\n }\n\n if (data.subject && data.subject !== this.state.subject) {\n this.state.subject = data.subject;\n updateReasons.push(\"subject\");\n }\n\n if (data.lastUpdatedBy && data.lastUpdatedBy !== this.state.lastUpdatedBy) {\n this.state.lastUpdatedBy = data.lastUpdatedBy;\n updateReasons.push(\"lastUpdatedBy\");\n }\n\n if (data.author && data.author !== this.state.author) {\n this.state.author = data.author;\n updateReasons.push(\"author\");\n }\n\n if (\n data.dateUpdated &&\n new Date(data.dateUpdated).getTime() !==\n (this.state.dateUpdated && this.state.dateUpdated.getTime())\n ) {\n this.state.dateUpdated = new Date(data.dateUpdated);\n updateReasons.push(\"dateUpdated\");\n }\n\n if (\n data.timestamp &&\n new Date(data.timestamp).getTime() !==\n (this.state.timestamp && this.state.timestamp.getTime())\n ) {\n this.state.timestamp = new Date(data.timestamp);\n updateReasons.push(\"dateCreated\");\n }\n\n const updatedAttributes = parseAttributes(\n data.attributes,\n `Got malformed attributes for the message ${this.sid}`,\n log\n );\n if (!isEqual(this.state.attributes, updatedAttributes)) {\n this.state.attributes = updatedAttributes;\n updateReasons.push(\"attributes\");\n }\n\n const updatedAggregatedDelivery = data.delivery;\n const currentAggregatedDelivery = this.state.aggregatedDeliveryReceipt;\n const isUpdatedAggregateDeliveryValid =\n !!updatedAggregatedDelivery &&\n !!updatedAggregatedDelivery.total &&\n !!updatedAggregatedDelivery.delivered &&\n !!updatedAggregatedDelivery.failed &&\n !!updatedAggregatedDelivery.read &&\n !!updatedAggregatedDelivery.sent &&\n !!updatedAggregatedDelivery.undelivered;\n if (isUpdatedAggregateDeliveryValid) {\n if (!currentAggregatedDelivery) {\n this.state.aggregatedDeliveryReceipt = new AggregatedDeliveryReceipt(\n updatedAggregatedDelivery\n );\n updateReasons.push(\"deliveryReceipt\");\n } else if (\n !currentAggregatedDelivery._isEquals(updatedAggregatedDelivery)\n ) {\n currentAggregatedDelivery._update(updatedAggregatedDelivery);\n updateReasons.push(\"deliveryReceipt\");\n }\n }\n\n if (updateReasons.length > 0) {\n this.emit(\"updated\", { message: this, updateReasons: updateReasons });\n }\n }\n\n /**\n * Get the participant who is the author of the message.\n */\n public async getParticipant(): Promise<Participant> {\n let participant: Participant | null = null;\n if (this.state.participantSid) {\n participant = await this.conversation\n .getParticipantBySid(this.state.participantSid)\n .catch(() => {\n log.debug(\n `Participant with sid \"${this.participantSid}\" not found for message ${this.sid}`\n );\n return null;\n });\n }\n if (!participant && this.state.author) {\n participant = await this.conversation\n .getParticipantByIdentity(this.state.author)\n .catch(() => {\n log.debug(\n `Participant with identity \"${this.author}\" not found for message ${this.sid}`\n );\n return null;\n });\n }\n if (participant) {\n return participant;\n }\n let errorMesage = \"Participant with \";\n if (this.state.participantSid) {\n errorMesage += \"SID '\" + this.state.participantSid + \"' \";\n }\n if (this.state.author) {\n if (this.state.participantSid) {\n errorMesage += \"or \";\n }\n errorMesage += \"identity '\" + this.state.author + \"' \";\n }\n if (errorMesage === \"Participant with \") {\n errorMesage = \"Participant \";\n }\n errorMesage += \"was not found\";\n throw new Error(errorMesage);\n }\n\n /**\n * Get the delivery receipts of the message.\n */\n public async getDetailedDeliveryReceipts(): Promise<\n DetailedDeliveryReceipt[]\n > {\n let paginator: Paginator<DetailedDeliveryReceipt> =\n await this._getDetailedDeliveryReceiptsPaginator();\n let detailedDeliveryReceipts: DetailedDeliveryReceipt[] = [];\n\n while (true) {\n detailedDeliveryReceipts = [\n ...detailedDeliveryReceipts,\n ...paginator.items,\n ];\n\n if (!paginator.hasNextPage) {\n break;\n }\n\n paginator = await paginator.nextPage();\n }\n\n return detailedDeliveryReceipts;\n }\n\n /**\n * Remove the message.\n */\n public async remove(): Promise<Message> {\n await this.services.commandExecutor.mutateResource(\n \"delete\",\n this.links.self\n );\n\n return this;\n }\n\n /**\n * Edit the message body.\n * @param body New body of the message.\n */\n @validateTypesAsync(\"string\")\n public async updateBody(body: string): Promise<Message> {\n await this.services.commandExecutor.mutateResource<\n EditMessageRequest,\n MessageResponse\n >(\"post\", this.links.self, {\n body,\n });\n\n return this;\n }\n\n /**\n * Edit the message attributes.\n * @param attributes New attributes.\n */\n @validateTypesAsync(attributesValidator)\n public async updateAttributes(attributes: JSONValue): Promise<Message> {\n await this.services.commandExecutor.mutateResource<\n EditMessageRequest,\n MessageResponse\n >(\"post\", this.links.self, {\n attributes:\n typeof attributes !== \"undefined\"\n ? JSON.stringify(attributes)\n : undefined,\n });\n\n return this;\n }\n\n /**\n * Get content URLs for all media attachments in the given set using single operation.\n * @param contentSet Set of media attachments to query for content URL.\n */\n @validateTypesAsync(\n custom((value) => [\n value instanceof Array &&\n value.length > 0 &&\n value.reduce((a, c) => a && c instanceof Media, true),\n \"a non-empty array of Media\",\n ])\n )\n public async attachTemporaryUrlsFor(\n contentSet: Media[] | null\n ): Promise<Media[]> {\n // We ignore existing mcsMedia members of each of the media entries.\n // Instead we just collect their sids and pull new descriptors from a mediaSet GET endpoint.\n const sids = contentSet?.map((m) => m.sid);\n if (this.services.mcsClient && sids) {\n return (await this.services.mcsClient.mediaSetGet(sids)).map((item) => {\n return new Media(item, this.services);\n });\n } else {\n throw new Error(\"Media Content Service is unavailable\");\n }\n }\n\n private async _getDetailedDeliveryReceiptsPaginator(options?: {\n pageToken?: string;\n pageSize?: number;\n }): Promise<Paginator<DetailedDeliveryReceipt>> {\n const messagesReceiptsUrl = this.configuration.links.messagesReceipts\n .replace(\"%s\", this.conversation.sid)\n .replace(\"%s\", this.sid);\n const url = new UriBuilder(messagesReceiptsUrl)\n .arg(\"PageToken\", options?.pageToken as string)\n .arg(\"PageSize\", options?.pageSize as number)\n .build();\n const response = await this.services.network.get<\n { delivery_receipts: DeliveryReceiptResponse[] } & ResponseMeta\n >(url);\n\n return new RestPaginator<DetailedDeliveryReceipt>(\n response.body.delivery_receipts.map(\n (x) => new DetailedDeliveryReceipt(x)\n ),\n (pageToken, pageSize) =>\n this._getDetailedDeliveryReceiptsPaginator({ pageToken, pageSize }),\n response.body.meta.previous_token,\n response.body.meta.next_token\n );\n }\n}\n\nexport {\n Message,\n MessageServices,\n MessageType,\n MessageUpdateReason,\n MessageUpdatedEventArgs,\n};\n","import { Logger } from \"../logger\";\n\nimport {\n Message,\n MessageData,\n MessageUpdatedEventArgs,\n MessageUpdateReason,\n} from \"../message\";\nimport {\n Conversation,\n SendEmailOptions,\n SendMediaOptions,\n} from \"../conversation\";\nimport { UnsentMessage } from \"../unsent-message\";\n\nimport { SyncList, SyncClient } from \"twilio-sync\";\nimport { SyncPaginator } from \"../sync-paginator\";\n\nimport { McsClient, McsMedia } from \"@twilio/mcs-client\";\nimport { Network } from \"../services/network\";\nimport { Configuration } from \"../configuration\";\nimport { CommandExecutor } from \"../command-executor\";\nimport { SendMessageRequest } from \"../interfaces/commands/send-message\";\nimport { MessageResponse } from \"../interfaces/commands/message-response\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport { JSONValue } from \"../types\";\n\ntype MessagesEvents = {\n messageAdded: (message: Message) => void;\n messageRemoved: (message: Message) => void;\n messageUpdated: (data: {\n message: Message;\n updateReasons: MessageUpdateReason[];\n }) => void;\n};\n\nconst log = Logger.scope(\"Messages\");\n\nexport interface MessagesServices {\n mcsClient: McsClient;\n network: Network;\n syncClient: SyncClient;\n commandExecutor: CommandExecutor;\n}\n\n/**\n * Represents the collection of messages in a conversation\n */\nclass Messages extends ReplayEventEmitter<MessagesEvents> {\n public readonly conversation: Conversation;\n private readonly configuration: Configuration;\n private readonly services: MessagesServices;\n private readonly messagesByIndex: Map<number, Message>;\n private messagesListPromise: Promise<SyncList> | null;\n\n public constructor(\n conversation: Conversation,\n configuration: Configuration,\n services: MessagesServices\n ) {\n super();\n\n this.conversation = conversation;\n this.configuration = configuration;\n this.services = services;\n\n this.messagesByIndex = new Map();\n this.messagesListPromise = null;\n }\n\n /**\n * Subscribe to the Messages Event Stream\n * @param name - The name of Sync object for the Messages resource.\n */\n public async subscribe(name: string) {\n if (this.messagesListPromise) {\n return this.messagesListPromise;\n }\n\n this.messagesListPromise = this.services.syncClient.list({\n id: name,\n mode: \"open_existing\",\n });\n\n try {\n const list = await this.messagesListPromise;\n\n list.on(\"itemAdded\", (args) => {\n log.debug(`${this.conversation.sid} itemAdded: ${args.item.index}`);\n\n const links = {\n self: `${this.conversation.links.messages}/${args.item.data.sid}`,\n conversation: this.conversation.links.self,\n messages_receipts: `${this.conversation.links.messages}/${args.item.data.sid}/Receipts`,\n };\n const message = new Message(\n args.item.index,\n args.item.data,\n this.conversation,\n links,\n this.configuration,\n this.services\n );\n\n if (this.messagesByIndex.has(message.index)) {\n log.debug(\n \"Message arrived, but is already known and ignored\",\n this.conversation.sid,\n message.index\n );\n return;\n }\n\n this.messagesByIndex.set(message.index, message);\n\n message.on(\"updated\", (args: MessageUpdatedEventArgs) =>\n this.emit(\"messageUpdated\", args)\n );\n\n this.emit(\"messageAdded\", message);\n });\n\n list.on(\"itemRemoved\", (args) => {\n log.debug(`#{this.conversation.sid} itemRemoved: ${args.index}`);\n\n const index = args.index;\n\n if (this.messagesByIndex.has(index)) {\n const message = this.messagesByIndex.get(index);\n if (!message) {\n return;\n }\n\n this.messagesByIndex.delete(message.index);\n message.removeAllListeners(\"updated\");\n this.emit(\"messageRemoved\", message);\n }\n });\n\n list.on(\"itemUpdated\", (args) => {\n log.debug(`${this.conversation.sid} itemUpdated: ${args.item.index}`);\n\n const message = this.messagesByIndex.get(args.item.index);\n\n if (message) {\n message._update(args.item.data);\n }\n });\n\n return list;\n } catch (err) {\n this.messagesListPromise = null;\n\n if (this.services.syncClient.connectionState !== \"disconnected\") {\n log.error(\n \"Failed to get messages object for conversation\",\n this.conversation.sid,\n err\n );\n }\n\n log.debug(\n \"ERROR: Failed to get messages object for conversation\",\n this.conversation.sid,\n err\n );\n\n throw err;\n }\n }\n\n public async unsubscribe() {\n if (!this.messagesListPromise) {\n return;\n }\n\n const entity = await this.messagesListPromise;\n entity.close();\n this.messagesListPromise = null;\n }\n\n /**\n * Send Message to the conversation, message could include both text and multiple media attachments.\n * @param message Message to post\n * @returns Returns a promise which can fail\n */\n public async sendV2(message: UnsentMessage): Promise<MessageResponse> {\n log.debug(\n \"Sending message V2\",\n message.mediaContent,\n message.attributes,\n message.emailOptions\n );\n\n const media: McsMedia[] = [];\n\n for (const [category, mediaContent] of message.mediaContent) {\n log.debug(\n `Adding media to a message as ${\n mediaContent instanceof FormData ? \"FormData\" : \"SendMediaOptions\"\n }`,\n mediaContent\n );\n\n media.push(\n mediaContent instanceof FormData\n ? await this.services.mcsClient.postFormData(mediaContent, category)\n : await this.services.mcsClient.post(\n mediaContent.contentType ?? \"\",\n mediaContent.media ?? \"\",\n category,\n mediaContent.filename\n )\n );\n }\n\n return await this.services.commandExecutor.mutateResource<\n SendMessageRequest,\n MessageResponse\n >(\"post\", this.conversation.links.messages, {\n body: message.text,\n subject: message.emailOptions?.subject,\n media_sids: media.map((m) => m.sid),\n attributes:\n typeof message.attributes !== \"undefined\"\n ? JSON.stringify(message.attributes)\n : undefined,\n });\n }\n\n /**\n * Send Message to the conversation\n * @param message Message to post\n * @param attributes Message attributes\n * @param emailOptions Options that modify E-mail integration behaviors.\n * @returns Returns promise which can fail\n */\n public async send(\n message: null | string | FormData | SendMediaOptions,\n attributes: JSONValue = {},\n emailOptions?: SendEmailOptions\n ): Promise<MessageResponse> {\n log.debug(\"Sending text message\", message, attributes, emailOptions);\n\n return await this.services.commandExecutor.mutateResource<\n SendMessageRequest,\n MessageResponse\n >(\"post\", this.conversation.links.messages, {\n body: message ?? \"\",\n attributes:\n typeof attributes !== \"undefined\"\n ? JSON.stringify(attributes)\n : undefined,\n subject: emailOptions?.subject,\n });\n }\n\n /**\n * Send Media Message to the conversation\n * @param mediaContent Media content to post\n * @param attributes Message attributes\n * @param emailOptions Email options\n * @returns Returns promise which can fail\n */\n public async sendMedia(\n mediaContent: FormData | SendMediaOptions,\n attributes: JSONValue = {},\n emailOptions?: SendEmailOptions\n ) {\n log.debug(\"Sending media message\", mediaContent, attributes, emailOptions);\n log.debug(\n `Sending media message as ${\n mediaContent instanceof FormData ? \"FormData\" : \"SendMediaOptions\"\n }`,\n mediaContent,\n attributes\n );\n\n const media: McsMedia =\n mediaContent instanceof FormData\n ? await this.services.mcsClient.postFormData(mediaContent)\n : await this.services.mcsClient.post(\n mediaContent.contentType ?? \"\",\n mediaContent.media ?? \"\",\n \"media\",\n mediaContent.filename\n );\n\n // emailOptions are currently ignored for media messages.\n return await this.services.commandExecutor.mutateResource<\n SendMessageRequest,\n MessageResponse\n >(\"post\", this.conversation.links.messages, {\n media_sids: [media.sid],\n attributes:\n typeof attributes !== \"undefined\"\n ? JSON.stringify(attributes)\n : undefined,\n });\n }\n\n /**\n * Returns messages from conversation using paginator interface\n * @param pageSize Number of messages to return in single chunk. By default it's 30.\n * @param anchor Most early message id which is already known, or 'end' by default\n * @param direction Pagination order 'backwards' or 'forward', 'forward' by default\n * @returns Last page of messages by default\n */\n public async getMessages(\n pageSize: number | undefined,\n anchor: number | \"end\" | undefined,\n direction: \"forward\" | \"backwards\" = \"backwards\"\n ): Promise<SyncPaginator<Message>> {\n return this._getMessages(pageSize, anchor, direction);\n }\n\n private _wrapPaginator(order, page, op) {\n // Due to an inconsistency between Sync and Chat conventions, next and\n // previous pages should be swapped.\n const shouldReverse = order === \"desc\";\n\n const nextPage = () =>\n page.nextPage().then((page) => this._wrapPaginator(order, page, op));\n const previousPage = () =>\n page.prevPage().then((page) => this._wrapPaginator(order, page, op));\n\n return op(page.items).then((items) => ({\n items: items.sort((x, y) => {\n return x.index - y.index;\n }),\n hasPrevPage: shouldReverse ? page.hasNextPage : page.hasPrevPage,\n hasNextPage: shouldReverse ? page.hasPrevPage : page.hasNextPage,\n prevPage: shouldReverse ? nextPage : previousPage,\n nextPage: shouldReverse ? previousPage : nextPage,\n }));\n }\n\n private _upsertMessage(index: number, value: MessageData) {\n const cachedMessage = this.messagesByIndex.get(index);\n\n if (cachedMessage) {\n return cachedMessage;\n }\n\n const links = {\n self: `${this.conversation.links.messages}/${value.sid}`,\n conversation: this.conversation.links.self,\n messages_receipts: `${this.conversation.links.messages}/${value.sid}/Receipts`,\n };\n const message = new Message(\n index,\n value,\n this.conversation,\n links,\n this.configuration,\n this.services\n );\n\n this.messagesByIndex.set(message.index, message);\n\n message.on(\"updated\", (args: MessageUpdatedEventArgs) =>\n this.emit(\"messageUpdated\", args)\n );\n\n return message;\n }\n\n /**\n * Returns last messages from conversation\n * @param {Number} [pageSize] Number of messages to return in single chunk. By default it's 30.\n * @param {String} [anchor] Most early message id which is already known, or 'end' by default\n * @param {String} [direction] Pagination order 'backwards' or 'forward', or 'forward' by default\n * @returns {Promise<SyncPaginator<Message>>} last page of messages by default\n * @private\n */\n private async _getMessages(\n pageSize = 30,\n anchor: number | \"end\" = \"end\",\n direction: \"forward\" | \"backwards\" = \"forward\"\n ): Promise<SyncPaginator<Message>> {\n const order = direction === \"backwards\" ? \"desc\" : \"asc\";\n const list = await this.messagesListPromise;\n const page = await list?.getItems({\n from: anchor !== \"end\" ? anchor : void 0,\n pageSize,\n order,\n limit: pageSize, // @todo Limit equals pageSize by default in Sync. This is probably not ideal.\n });\n\n return await this._wrapPaginator(order, page, (items) =>\n Promise.all(\n items.map((item) => this._upsertMessage(item.index, item.data))\n )\n );\n }\n}\n\nexport { Messages };\n","import { MediaCategory } from \"@twilio/mcs-client\";\nimport { parseToNumber } from \"./util\";\nimport { SendEmailOptions, SendMediaOptions } from \"./conversation\";\nimport { JSONValue } from \"./types\";\n\n/**\n * An unsent message. Returned from {@link MessageBuilder.build}.\n */\nclass UnsentMessage {\n public text?: string;\n public attributes: JSONValue = {};\n public mediaContent: [MediaCategory, FormData | SendMediaOptions][] = [];\n public emailOptions: SendEmailOptions = {};\n\n /**\n * @internal\n */\n constructor(private messagesEntity) {}\n\n /**\n * Send the prepared message to the conversation.\n * @returns Index of the new message in the conversation.\n */\n async send(): Promise<number | null> {\n const response = await this.messagesEntity.sendV2(this);\n return parseToNumber(response.index);\n }\n}\n\nexport { UnsentMessage };\n","import { ConversationLimits } from \"./interfaces/conversation-limits\";\nimport { SendMediaOptions } from \"./conversation\";\nimport { UnsentMessage } from \"./unsent-message\";\nimport { JSONValue } from \"./types\";\nimport { Messages } from \"./data/messages\";\n\n/**\n * Message builder. Allows the message to be built and sent via method chaining.\n *\n * Example:\n *\n * ```ts\n * await testConversation.prepareMessage()\n * .setBody('Hello!')\n * .setAttributes({foo: 'bar'})\n * .addMedia(media1)\n * .addMedia(media2)\n * .build()\n * .send();\n * ```\n */\nclass MessageBuilder {\n private readonly message: UnsentMessage;\n private emailBodies: Map<string, FormData | SendMediaOptions>;\n private emailHistories: Map<string, FormData | SendMediaOptions>;\n\n /**\n * @internal\n */\n constructor(\n private readonly limits: ConversationLimits,\n messagesEntity: Messages\n ) {\n this.message = new UnsentMessage(messagesEntity);\n this.emailBodies = new Map<string, FormData | SendMediaOptions>();\n this.emailHistories = new Map<string, FormData | SendMediaOptions>();\n }\n\n /**\n * Sets the message body.\n * @param text Contents of the body.\n */\n setBody(text: string): MessageBuilder {\n this.message.text = text;\n return this;\n }\n\n /**\n * Sets the message subject.\n * @param subject Contents of the subject.\n */\n setSubject(subject: string): MessageBuilder {\n this.message.emailOptions.subject = subject;\n return this;\n }\n\n /**\n * Sets the message attributes.\n * @param attributes Message attributes.\n */\n setAttributes(attributes: JSONValue): MessageBuilder {\n this.message.attributes = attributes;\n return this;\n }\n\n /**\n * Set email body with given MIME-type.\n * @param mimeType Format of the body to set (text/plain or text/html).\n * @param body Body payload in selected format.\n */\n setEmailBody(\n mimeType: string,\n body: FormData | SendMediaOptions\n ): MessageBuilder {\n this.emailBodies.set(mimeType, body);\n return this;\n }\n\n /**\n * Set email history with given MIME-type.\n * @param mimeType Format of the history to set (text/plain or text/html).\n * @param history History payload in selected format.\n */\n setEmailHistory(\n mimeType: string,\n history: FormData | SendMediaOptions\n ): MessageBuilder {\n this.emailHistories.set(mimeType, history);\n return this;\n }\n\n /**\n * Adds media to the message.\n * @param payload Media to add.\n */\n addMedia(payload: FormData | SendMediaOptions): MessageBuilder {\n if (typeof FormData === \"undefined\" && payload instanceof FormData) {\n throw new Error(\"Could not add FormData content whilst not in a browser\");\n }\n if (!(payload instanceof FormData)) {\n const mediaOptions = payload as SendMediaOptions;\n if (!mediaOptions.contentType || !mediaOptions.media) {\n throw new Error(\n \"Media content in SendMediaOptions must contain non-empty contentType and media\"\n );\n }\n }\n this.message.mediaContent.push([\"media\", payload]);\n return this;\n }\n\n /**\n * Builds the message, making it ready to be sent.\n */\n build(): UnsentMessage {\n this.emailBodies.forEach((_, key) => {\n if (!this.limits.emailBodiesAllowedMimeTypes.includes(key)) {\n throw new Error(`Unsupported email body MIME type ${key}`);\n }\n });\n this.emailHistories.forEach((_, key) => {\n if (!this.limits.emailHistoriesAllowedMimeTypes.includes(key)) {\n throw new Error(`Unsupported email history MIME type ${key}`);\n }\n });\n if (\n this.emailBodies.size > this.limits.emailBodiesAllowedMimeTypes.length\n ) {\n throw new Error(\n `Too many email bodies attached to the message (${this.emailBodies.size} > ${this.limits.emailBodiesAllowedMimeTypes.length})`\n );\n }\n if (\n this.emailHistories.size >\n this.limits.emailHistoriesAllowedMimeTypes.length\n ) {\n throw new Error(\n `Too many email histories attached to the message (${this.emailHistories.size} > ${this.limits.emailHistoriesAllowedMimeTypes.length})`\n );\n }\n\n if (\n this.message.mediaContent.length > this.limits.mediaAttachmentsCountLimit\n ) {\n throw new Error(\n `Too many media attachments in the message (${this.message.mediaContent.length} > ${this.limits.mediaAttachmentsCountLimit})`\n );\n }\n\n // @todo we don't know the sizes of the attachments in FormData\n // @todo insertion below makes build() method non-repeatable - probably move to UnsentMessage.send() or even sendV2()?\n\n this.emailBodies.forEach((body) => {\n this.message.mediaContent.push([\"body\", body]);\n });\n\n this.emailHistories.forEach((history) => {\n this.message.mediaContent.push([\"history\", history]);\n });\n\n return this.message;\n }\n\n private getPayloadContentType(\n payload: FormData | SendMediaOptions\n ): string | null {\n if (typeof FormData !== \"undefined\" && payload instanceof FormData) {\n return payload.get(\"Content-Type\") as string;\n }\n return (payload as SendMediaOptions).contentType;\n }\n}\n\nexport { MessageBuilder };\n","import { Logger } from \"./logger\";\n\nimport { ParticipantBindingOptions, Participants } from \"./data/participants\";\nimport {\n Participant,\n ParticipantUpdatedEventArgs,\n ParticipantUpdateReason,\n} from \"./participant\";\nimport { Messages } from \"./data/messages\";\nimport {\n Message,\n MessageUpdatedEventArgs,\n MessageUpdateReason,\n} from \"./message\";\n\nimport { UriBuilder, parseToNumber } from \"./util\";\nimport { Users } from \"./data/users\";\nimport { Paginator } from \"./interfaces/paginator\";\nimport { ConversationsDataSource } from \"./data/conversations\";\nimport { McsClient } from \"@twilio/mcs-client\";\n\nimport { SyncClient, SyncDocument } from \"twilio-sync\";\nimport { TypingIndicator } from \"./services/typing-indicator\";\nimport { Network } from \"./services/network\";\nimport {\n validateTypesAsync,\n custom,\n literal,\n nonEmptyString,\n nonNegativeInteger,\n objectSchema,\n} from \"@twilio/declarative-type-validator\";\nimport {\n attributesValidator,\n optionalAttributesValidator,\n} from \"./interfaces/attributes\";\nimport { Configuration } from \"./configuration\";\nimport { CommandExecutor } from \"./command-executor\";\nimport { AddParticipantRequest } from \"./interfaces/commands/add-participant\";\nimport { EditConversationRequest } from \"./interfaces/commands/edit-conversation\";\nimport { ConversationResponse } from \"./interfaces/commands/conversation-response\";\nimport { ParticipantResponse } from \"./interfaces/commands/participant-response\";\nimport { EditNotificationLevelRequest } from \"./interfaces/commands/edit-notification-level\";\nimport {\n EditLastReadMessageIndexRequest,\n EditLastReadMessageIndexResponse,\n} from \"./interfaces/commands/edit-last-read-message-index\";\nimport { ConversationLimits } from \"./interfaces/conversation-limits\";\nimport { MessageBuilder } from \"./message-builder\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport isEqual from \"lodash.isequal\";\nimport { JSONValue } from \"./types\";\n\ntype ConversationEvents = {\n participantJoined: (participant: Participant) => void;\n participantLeft: (participant: Participant) => void;\n participantUpdated: (data: {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n }) => void;\n messageAdded: (message: Message) => void;\n messageRemoved: (message: Message) => void;\n messageUpdated: (data: {\n message: Message;\n updateReasons: MessageUpdateReason[];\n }) => void;\n typingEnded: (participant: Participant) => void;\n typingStarted: (participant: Participant) => void;\n updated: (data: {\n conversation: Conversation;\n updateReasons: ConversationUpdateReason[];\n }) => void;\n removed: (conversation: Conversation) => void;\n};\n\nconst log = Logger.scope(\"Conversation\");\n\nconst fieldMappings = {\n lastMessage: \"lastMessage\",\n attributes: \"attributes\",\n createdBy: \"createdBy\",\n dateCreated: \"dateCreated\",\n dateUpdated: \"dateUpdated\",\n friendlyName: \"friendlyName\",\n lastConsumedMessageIndex: \"lastConsumedMessageIndex\",\n notificationLevel: \"notificationLevel\",\n sid: \"sid\",\n status: \"status\",\n uniqueName: \"uniqueName\",\n state: \"state\",\n bindings: \"bindings\",\n};\n\nfunction parseTime(timeString) {\n try {\n return new Date(timeString);\n } catch (e) {\n return null;\n }\n}\n\nexport interface ConversationServices {\n users: Users;\n typingIndicator: TypingIndicator;\n network: Network;\n mcsClient: McsClient;\n syncClient: SyncClient;\n commandExecutor: CommandExecutor;\n}\n\ninterface ConversationInternalState {\n uniqueName: string | null;\n status: ConversationStatus;\n attributes: JSONValue;\n createdBy?: string;\n dateCreated: Date | null;\n dateUpdated: Date | null;\n friendlyName: string | null;\n lastReadMessageIndex: number | null;\n lastMessage?: LastMessage;\n notificationLevel?: NotificationLevel;\n state?: ConversationState;\n bindings: ConversationBindings;\n}\n\ninterface ConversationDescriptor {\n channel: string;\n entityName: string;\n uniqueName: string;\n attributes: JSONValue;\n createdBy?: string;\n friendlyName?: string;\n lastConsumedMessageIndex: number;\n dateCreated: Date | null;\n dateUpdated: Date | null;\n notificationLevel?: NotificationLevel;\n bindings?: ConversationBindings;\n}\n\ninterface ConversationLinks {\n self: string;\n messages: string;\n participants: string;\n}\n\n/**\n * The reason for the `updated` event being emitted by a conversation.\n */\ntype ConversationUpdateReason =\n | \"attributes\"\n | \"createdBy\"\n | \"dateCreated\"\n | \"dateUpdated\"\n | \"friendlyName\"\n | \"lastReadMessageIndex\"\n | \"state\"\n | \"status\"\n | \"uniqueName\"\n | \"lastMessage\"\n | \"notificationLevel\"\n | \"bindings\";\n\n/**\n * The status of the conversation, relative to the client: whether\n * the conversation has been `joined` or the client is\n * `notParticipating` in the conversation.\n */\ntype ConversationStatus = \"notParticipating\" | \"joined\";\n\n/**\n * The user's notification level for the conversation. Determines\n * whether the currently logged-in user will receive pushes for events\n * in this conversation. Can be either `muted` or `default`, where\n * `default` defers to the global service push configuration.\n */\ntype NotificationLevel = \"default\" | \"muted\";\n\n/**\n * The state of the conversation.\n */\ninterface ConversationState {\n /**\n * The current state.\n */\n current: \"active\" | \"inactive\" | \"closed\";\n\n /**\n * Date at which the latest conversation state update happened.\n */\n dateUpdated: Date;\n}\n\ninterface ConversationUpdatedEventArgs {\n conversation: Conversation;\n updateReasons: ConversationUpdateReason[];\n}\n\n/**\n * Binding for email conversation.\n */\ninterface ConversationBindings {\n email?: ConversationEmailBinding;\n sms?: ConversationSmsBinding;\n}\n\n/**\n * Binding for email conversation.\n */\ninterface ConversationEmailBinding {\n name?: string;\n projected_address: string;\n}\n\ninterface ConversationSmsBinding {\n address?: string;\n}\n\n/**\n * Configuration for attaching a media file to a message.\n * These options can be passed to {@link Conversation.sendMessage} and\n * {@link MessageBuilder.addMedia}.\n */\ninterface SendMediaOptions {\n /**\n * Content type of media.\n */\n contentType: null | string;\n\n /**\n * Optional filename.\n */\n filename?: string;\n\n /**\n * Content to post.\n */\n media: null | string | Buffer | Blob;\n}\n\n/**\n * These options can be passed to {@link Conversation.sendMessage}.\n */\ninterface SendEmailOptions {\n /**\n * Message subject. Ignored for media messages.\n */\n subject?: string;\n}\n\n/**\n * Information about the last message of a conversation.\n */\ninterface LastMessage {\n /**\n * Message's index.\n */\n index?: number;\n\n /**\n * Message's creation date.\n */\n dateCreated?: Date;\n}\n\n/**\n * A conversation represents communication between multiple Conversations clients\n */\nclass Conversation extends ReplayEventEmitter<ConversationEvents> {\n /**\n * Unique system identifier of the conversation.\n */\n public readonly sid: string;\n public readonly links: ConversationLinks;\n\n private readonly configuration: Configuration;\n private readonly services: ConversationServices;\n private channelState: ConversationInternalState;\n private statusSource!: ConversationsDataSource;\n\n private entityPromise!: Promise<void | SyncDocument> | null;\n private entityName: string;\n private entity!: SyncDocument | null;\n private messagesEntity: Messages;\n private participantsEntity: Participants;\n private readonly participants: Map<string, Participant>;\n\n /**\n * @internal\n */\n constructor(\n descriptor: ConversationDescriptor,\n sid: string,\n links: ConversationLinks,\n configuration: Configuration,\n services: ConversationServices\n ) {\n super();\n\n this.sid = sid;\n this.links = links;\n this.configuration = configuration;\n this.services = services;\n\n const attributes = descriptor.attributes || {};\n const createdBy = descriptor.createdBy;\n const dateCreated = parseTime(descriptor.dateCreated);\n const dateUpdated = parseTime(descriptor.dateUpdated);\n const friendlyName = descriptor.friendlyName || null;\n const lastReadMessageIndex = Number.isInteger(\n descriptor.lastConsumedMessageIndex\n )\n ? descriptor.lastConsumedMessageIndex\n : null;\n const uniqueName = descriptor.uniqueName || null;\n\n try {\n JSON.stringify(attributes);\n } catch (e) {\n throw new Error(\"Attributes must be a valid JSON object.\");\n }\n\n this.entityName = descriptor.channel;\n this.channelState = {\n uniqueName,\n status: \"notParticipating\",\n attributes,\n createdBy,\n dateCreated,\n dateUpdated,\n friendlyName,\n lastReadMessageIndex,\n bindings: descriptor.bindings ?? {},\n };\n\n if (descriptor.notificationLevel) {\n this.channelState.notificationLevel = descriptor.notificationLevel;\n }\n\n const participantsLinks = {\n participants: this.links.participants,\n };\n\n this.participants = new Map();\n this.participantsEntity = new Participants(\n this,\n this.participants,\n participantsLinks,\n this.configuration,\n this.services\n );\n this.participantsEntity.on(\"participantJoined\", (participant) =>\n this.emit(\"participantJoined\", participant)\n );\n this.participantsEntity.on(\"participantLeft\", (participant) =>\n this.emit(\"participantLeft\", participant)\n );\n this.participantsEntity.on(\n \"participantUpdated\",\n (args: ParticipantUpdatedEventArgs) =>\n this.emit(\"participantUpdated\", args)\n );\n\n this.messagesEntity = new Messages(this, configuration, services);\n this.messagesEntity.on(\"messageAdded\", (message) =>\n this._onMessageAdded(message)\n );\n this.messagesEntity.on(\"messageUpdated\", (args: MessageUpdatedEventArgs) =>\n this.emit(\"messageUpdated\", args)\n );\n this.messagesEntity.on(\"messageRemoved\", (message) =>\n this.emit(\"messageRemoved\", message)\n );\n }\n\n /**\n * Fired when a participant has joined the conversation.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - participant that joined the conversation\n * @event\n */\n static readonly participantJoined = \"participantJoined\";\n\n /**\n * Fired when a participant has left the conversation.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - participant that left the conversation\n * @event\n */\n static readonly participantLeft = \"participantLeft\";\n\n /**\n * Fired when data of a participant has been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the following properties:\n * * {@link Participant} `participant` - participant that has received the update\n * * {@link ParticipantUpdateReason}[] `updateReasons` - array of reasons for update\n * @event\n */\n static readonly participantUpdated = \"participantUpdated\";\n\n /**\n * Fired when a new message has been added to the conversation.\n *\n * Parameters:\n * 1. {@link Message} `message` - message that has been added\n * @event\n */\n static readonly messageAdded = \"messageAdded\";\n\n /**\n * Fired when message is removed from the conversation's message list.\n *\n * Parameters:\n * 1. {@link Message} `message` - message that has been removed\n * @event\n */\n static readonly messageRemoved = \"messageRemoved\";\n\n /**\n * Fired when data of a message has been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the following properties:\n * * {@link Message} `message` - message that has received the update\n * * {@link MessageUpdateReason}[] `updateReasons` - array of reasons for update\n * @event\n */\n static readonly messageUpdated = \"messageUpdated\";\n\n /**\n * Fired when a participant has stopped typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant that has stopped typing\n * @event\n */\n static readonly typingEnded = \"typingEnded\";\n\n /**\n * Fired when a participant has started typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant that has started typing\n * @event\n */\n static readonly typingStarted = \"typingStarted\";\n\n /**\n * Fired when the data of the conversation has been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the following properties:\n * * {@link Conversation} `conversation` - conversation that has received the update\n * * {@link ConversationUpdateReason}[] `updateReasons` - array of reasons for update\n * @event\n */\n static readonly updated = \"updated\";\n\n /**\n * Fired when the conversation was destroyed or the currently-logged-in user has left private conversation.\n *\n * Parameters:\n * 1. {@link Conversation} `conversation` - conversation that has been removed\n * @event\n */\n static readonly removed = \"removed\";\n\n /**\n * Unique name of the conversation.\n */\n public get uniqueName(): string | null {\n return this.channelState.uniqueName;\n }\n\n /**\n * Status of the conversation.\n */\n public get status(): ConversationStatus {\n return this.channelState.status;\n }\n\n /**\n * Name of the conversation.\n */\n public get friendlyName(): string | null {\n return this.channelState.friendlyName;\n }\n\n /**\n * Date this conversation was last updated on.\n */\n public get dateUpdated(): Date | null {\n return this.channelState.dateUpdated;\n }\n\n /**\n * Date this conversation was created on.\n */\n public get dateCreated(): Date | null {\n return this.channelState.dateCreated;\n }\n\n /**\n * Identity of the user that created this conversation.\n */\n public get createdBy(): string {\n return this.channelState.createdBy ?? \"\";\n }\n\n /**\n * Custom attributes of the conversation.\n */\n public get attributes(): JSONValue {\n return this.channelState.attributes;\n }\n\n /**\n * Index of the last message the user has read in this conversation.\n */\n public get lastReadMessageIndex(): number | null {\n return this.channelState.lastReadMessageIndex;\n }\n\n /**\n * Last message sent to this conversation.\n */\n public get lastMessage(): LastMessage | undefined {\n return this.channelState.lastMessage ?? undefined;\n }\n\n /**\n * User notification level for this conversation.\n */\n public get notificationLevel(): NotificationLevel {\n return this.channelState.notificationLevel ?? \"default\";\n }\n\n public get bindings(): ConversationBindings {\n return this.channelState.bindings;\n }\n\n /**\n * Current conversation limits.\n */\n public get limits(): ConversationLimits {\n return this.configuration.limits;\n }\n\n /**\n * State of the conversation.\n */\n public get state(): ConversationState | undefined {\n return this.channelState.state;\n }\n\n /**\n * Load and subscribe to this conversation and do not subscribe to its participants and messages.\n * This or _subscribeStreams will need to be called before any events on conversation will fire.\n * @internal\n */\n _subscribe() {\n return (this.entityPromise =\n this.entityPromise ??\n this.services.syncClient\n .document({ id: this.entityName, mode: \"open_existing\" })\n .then((entity) => {\n this.entity = entity;\n this.entity.on(\"updated\", (args) => {\n this._update(args.data);\n });\n this.entity.on(\"removed\", () => this.emit(\"removed\", this));\n this._update(this.entity.data);\n return entity;\n })\n .catch((err) => {\n this.entity = null;\n this.entityPromise = null;\n if (this.services.syncClient.connectionState != \"disconnected\") {\n log.error(\"Failed to get conversation object\", err);\n }\n log.debug(\"ERROR: Failed to get conversation object\", err);\n throw err;\n }));\n }\n\n /**\n * Load the attributes of this conversation and instantiate its participants and messages.\n * This or _subscribe will need to be called before any events on the conversation will fire.\n * This will need to be called before any events on participants or messages will fire\n * @internal\n */\n async _subscribeStreams() {\n try {\n await this._subscribe();\n log.trace(\"_subscribeStreams, this.entity.data=\", this.entity?.data);\n const messagesObjectName = (this.entity?.data as Record<string, string>)\n .messages;\n const rosterObjectName = (this.entity?.data as Record<string, string>)\n .roster;\n await Promise.all([\n this.messagesEntity.subscribe(messagesObjectName),\n this.participantsEntity.subscribe(rosterObjectName),\n ]);\n } catch (err) {\n if (this.services.syncClient.connectionState !== \"disconnected\") {\n log.error(\"Failed to subscribe on conversation objects\", this.sid, err);\n }\n log.debug(\n \"ERROR: Failed to subscribe on conversation objects\",\n this.sid,\n err\n );\n throw err;\n }\n }\n\n /**\n * Stop listening for and firing events on this conversation.\n * @internal\n */\n async _unsubscribe() {\n if (this.entity) {\n await this.entity.close();\n this.entity = null;\n this.entityPromise = null;\n }\n\n return Promise.all([\n this.participantsEntity.unsubscribe(),\n this.messagesEntity.unsubscribe(),\n ]);\n }\n\n /**\n * Set conversation status.\n * @internal\n */\n _setStatus(status: ConversationStatus, source: ConversationsDataSource) {\n this.statusSource = source;\n\n if (this.channelState.status === status) {\n return;\n }\n\n this.channelState.status = status;\n\n if (status === \"joined\") {\n this._subscribeStreams().catch((err) => {\n log.debug(\"ERROR while setting conversation status \" + status, err);\n if (this.services.syncClient.connectionState !== \"disconnected\") {\n throw err;\n }\n });\n } else if (this.entityPromise) {\n this._unsubscribe().catch((err) => {\n log.debug(\"ERROR while setting conversation status \" + status, err);\n if (this.services.syncClient.connectionState !== \"disconnected\") {\n throw err;\n }\n });\n }\n }\n\n /**\n * Get the source of the conversation update.\n * @internal\n */\n _statusSource(): ConversationsDataSource {\n return this.statusSource;\n }\n\n private static preprocessUpdate(update, conversationSid) {\n try {\n if (typeof update.attributes === \"string\") {\n update.attributes = JSON.parse(update.attributes);\n } else if (update.attributes) {\n JSON.stringify(update.attributes);\n }\n } catch (e) {\n log.warn(\n \"Retrieved malformed attributes from the server for conversation: \" +\n conversationSid\n );\n update.attributes = {};\n }\n\n try {\n if (update.dateCreated) {\n update.dateCreated = new Date(update.dateCreated);\n }\n } catch (e) {\n log.warn(\n \"Retrieved malformed dateCreated from the server for conversation: \" +\n conversationSid\n );\n delete update.dateCreated;\n }\n\n try {\n if (update.dateUpdated) {\n update.dateUpdated = new Date(update.dateUpdated);\n }\n } catch (e) {\n log.warn(\n \"Retrieved malformed dateUpdated from the server for conversation: \" +\n conversationSid\n );\n delete update.dateUpdated;\n }\n\n try {\n if (update.lastMessage && update.lastMessage.timestamp) {\n update.lastMessage.timestamp = new Date(update.lastMessage.timestamp);\n }\n } catch (e) {\n log.warn(\n \"Retrieved malformed lastMessage.timestamp from the server for conversation: \" +\n conversationSid\n );\n delete update.lastMessage.timestamp;\n }\n }\n\n /**\n * Update the local conversation object with new values.\n * @internal\n */\n _update(update) {\n log.trace(\"_update\", update);\n\n Conversation.preprocessUpdate(update, this.sid);\n const updateReasons = new Set<ConversationUpdateReason>();\n\n for (const key of Object.keys(update)) {\n const localKey = fieldMappings[key];\n\n if (!localKey) {\n continue;\n }\n\n switch (localKey) {\n case fieldMappings.status:\n if (\n !update.status ||\n update.status === \"unknown\" ||\n this.channelState.status === update.status\n ) {\n break;\n }\n\n this.channelState.status = update.status;\n updateReasons.add(localKey);\n\n break;\n case fieldMappings.attributes:\n if (isEqual(this.channelState.attributes, update.attributes)) {\n break;\n }\n\n this.channelState.attributes = update.attributes;\n updateReasons.add(localKey);\n\n break;\n case fieldMappings.lastConsumedMessageIndex:\n if (\n update.lastConsumedMessageIndex === undefined ||\n update.lastConsumedMessageIndex ===\n this.channelState.lastReadMessageIndex\n ) {\n break;\n }\n\n this.channelState.lastReadMessageIndex =\n update.lastConsumedMessageIndex;\n updateReasons.add(\"lastReadMessageIndex\");\n\n break;\n case fieldMappings.lastMessage:\n if (this.channelState.lastMessage && !update.lastMessage) {\n delete this.channelState.lastMessage;\n updateReasons.add(localKey);\n\n break;\n }\n\n this.channelState.lastMessage = this.channelState.lastMessage || {};\n\n if (\n update.lastMessage?.index !== undefined &&\n update.lastMessage.index !== this.channelState.lastMessage.index\n ) {\n this.channelState.lastMessage.index = update.lastMessage.index;\n updateReasons.add(localKey);\n }\n\n if (\n update.lastMessage?.timestamp !== undefined &&\n this.channelState.lastMessage?.dateCreated?.getTime() !==\n update.lastMessage.timestamp.getTime()\n ) {\n this.channelState.lastMessage.dateCreated =\n update.lastMessage.timestamp;\n updateReasons.add(localKey);\n }\n\n if (isEqual(this.channelState.lastMessage, {})) {\n delete this.channelState.lastMessage;\n }\n\n break;\n case fieldMappings.state:\n const state = update.state || undefined;\n\n if (state !== undefined) {\n state.dateUpdated = new Date(state.dateUpdated);\n }\n\n if (isEqual(this.channelState.state, state)) {\n break;\n }\n\n this.channelState.state = state;\n updateReasons.add(localKey);\n\n break;\n case fieldMappings.bindings:\n if (isEqual(this.channelState.bindings, update.bindings)) {\n break;\n }\n\n this.channelState.bindings = update.bindings;\n updateReasons.add(localKey);\n\n break;\n default:\n const isDate = update[key] instanceof Date;\n const keysMatchAsDates =\n isDate &&\n this.channelState[localKey]?.getTime() === update[key].getTime();\n const keysMatchAsNonDates = !isDate && this[localKey] === update[key];\n\n if (keysMatchAsDates || keysMatchAsNonDates) {\n break;\n }\n\n this.channelState[localKey] = update[key];\n updateReasons.add(localKey);\n }\n }\n\n if (updateReasons.size > 0) {\n this.emit(\"updated\", {\n conversation: this,\n updateReasons: [...updateReasons],\n });\n }\n }\n\n /**\n * @internal\n */\n private _onMessageAdded(message) {\n for (const participant of this.participants.values()) {\n if (participant.identity === message.author) {\n participant._endTyping();\n break;\n }\n }\n this.emit(\"messageAdded\", message);\n }\n\n private async _setLastReadMessageIndex(\n index: number | null\n ): Promise<number> {\n const result = await this.services.commandExecutor.mutateResource<\n EditLastReadMessageIndexRequest,\n EditLastReadMessageIndexResponse\n >(\"post\", `${this.configuration.links.myConversations}/${this.sid}`, {\n last_read_message_index: index,\n });\n\n return result.unread_messages_count;\n }\n\n /**\n * Add a participant to the conversation by its identity.\n * @param identity Identity of the Client to add.\n * @param attributes Attributes to be attached to the participant.\n */\n @validateTypesAsync(nonEmptyString, optionalAttributesValidator)\n async add(\n identity: string,\n attributes?: JSONValue\n ): Promise<ParticipantResponse> {\n return this.participantsEntity.add(identity, attributes ?? {});\n }\n\n /**\n * Add a non-chat participant to the conversation.\n * @param proxyAddress Proxy (Twilio) address of the participant.\n * @param address User address of the participant.\n * @param attributes Attributes to be attached to the participant.\n * @param bindingOptions Options for adding email participants - name and CC/To level.\n */\n @validateTypesAsync(\n nonEmptyString,\n nonEmptyString,\n optionalAttributesValidator\n )\n async addNonChatParticipant(\n proxyAddress: string,\n address: string,\n attributes: JSONValue = {},\n bindingOptions: ParticipantBindingOptions = {}\n ): Promise<ParticipantResponse> {\n return this.participantsEntity.addNonChatParticipant(\n proxyAddress,\n address,\n attributes ?? {},\n bindingOptions ?? {}\n );\n }\n\n /**\n * Advance the conversation's last read message index to the current read horizon.\n * Rejects if the user is not a participant of the conversation.\n * Last read message index is updated only if the new index value is higher than the previous.\n * @param index Message index to advance to.\n * @return Resulting unread messages count in the conversation.\n */\n @validateTypesAsync(nonNegativeInteger)\n async advanceLastReadMessageIndex(index: number): Promise<number> {\n await this._subscribeStreams();\n\n if (index < (this.lastReadMessageIndex || 0)) {\n return await this._setLastReadMessageIndex(this.lastReadMessageIndex);\n }\n\n return await this._setLastReadMessageIndex(index);\n }\n\n /**\n * Delete the conversation and unsubscribe from its events.\n */\n async delete(): Promise<Conversation> {\n await this.services.commandExecutor.mutateResource(\n \"delete\",\n this.links.self\n );\n\n return this;\n }\n\n /**\n * Get the custom attributes of this Conversation.\n */\n async getAttributes(): Promise<JSONValue> {\n await this._subscribe();\n return this.attributes;\n }\n\n /**\n * Returns messages from the conversation using the paginator interface.\n * @param pageSize Number of messages to return in a single chunk. Default is 30.\n * @param anchor Index of the newest message to fetch. Default is from the end.\n * @param direction Query direction. By default it queries backwards\n * from newer to older. The `\"forward\"` value will query in the opposite direction.\n * @return A page of messages.\n */\n @validateTypesAsync(\n [\"undefined\", nonNegativeInteger],\n [\"undefined\", nonNegativeInteger],\n [\"undefined\", literal(\"backwards\", \"forward\")]\n )\n async getMessages(\n pageSize?: number,\n anchor?: number,\n direction?: \"backwards\" | \"forward\"\n ): Promise<Paginator<Message>> {\n await this._subscribeStreams();\n return this.messagesEntity.getMessages(pageSize, anchor, direction);\n }\n\n /**\n * Get a list of all the participants who are joined to this conversation.\n */\n async getParticipants(): Promise<Participant[]> {\n await this._subscribeStreams();\n return this.participantsEntity.getParticipants();\n }\n\n /**\n * Get conversation participants count.\n *\n * This method is semi-realtime. This means that this data will be eventually correct,\n * but will also be possibly incorrect for a few seconds. The Conversations system does not\n * provide real time events for counter values changes.\n *\n * This is useful for any UI badges, but it is not recommended to build any core application\n * logic based on these counters being accurate in real time.\n */\n async getParticipantsCount(): Promise<number> {\n const url = new UriBuilder(this.configuration.links.conversations)\n .path(this.sid)\n .build();\n const response = await this.services.network.get<ConversationResponse>(url);\n\n return response.body.participants_count ?? 0;\n }\n\n /**\n * Get a participant by its SID.\n * @param participantSid Participant SID.\n */\n @validateTypesAsync(nonEmptyString)\n async getParticipantBySid(\n participantSid: string\n ): Promise<Participant | null> {\n return this.participantsEntity.getParticipantBySid(participantSid);\n }\n\n /**\n * Get a participant by its identity.\n * @param identity Participant identity.\n */\n @validateTypesAsync(nonEmptyString)\n async getParticipantByIdentity(\n identity: string | null = \"\"\n ): Promise<Participant | null> {\n return this.participantsEntity.getParticipantByIdentity(identity ?? \"\");\n }\n\n /**\n * Get the total message count in the conversation.\n *\n * This method is semi-realtime. This means that this data will be eventually correct,\n * but will also be possibly incorrect for a few seconds. The Conversations system does not\n * provide real time events for counter values changes.\n *\n * This is useful for any UI badges, but it is not recommended to build any core application\n * logic based on these counters being accurate in real time.\n */\n async getMessagesCount(): Promise<number> {\n const url = new UriBuilder(this.configuration.links.conversations)\n .path(this.sid)\n .build();\n const response = await this.services.network.get<ConversationResponse>(url);\n\n return response.body.messages_count ?? 0;\n }\n\n /**\n * Get unread messages count for the user if they are a participant of this conversation.\n * Rejects if the user is not a participant of the conversation.\n *\n * Use this method to obtain the number of unread messages together with\n * {@link Conversation.updateLastReadMessageIndex} instead of relying on the\n * message indices which may have gaps. See {@link Message.index} for details.\n *\n * This method is semi-realtime. This means that this data will be eventually correct,\n * but will also be possibly incorrect for a few seconds. The Conversations system does not\n * provide real time events for counter values changes.\n *\n * This is useful for any UI badges, but it is not recommended to build any core application\n * logic based on these counters being accurate in real time.\n */\n async getUnreadMessagesCount(): Promise<number | null> {\n const url = new UriBuilder(this.configuration.links.myConversations)\n .path(this.sid)\n .build();\n const response = await this.services.network.get<ConversationResponse>(url);\n\n if (response.body.conversation_sid !== this.sid) {\n throw new Error(\n \"Conversation was not found in the user conversations list\"\n );\n }\n\n const unreadMessageCount = response.body.unread_messages_count;\n\n if (typeof unreadMessageCount === \"number\") {\n return unreadMessageCount;\n }\n\n return null;\n }\n\n /**\n * Join the conversation and subscribe to its events.\n */\n async join(): Promise<Conversation> {\n await this.services.commandExecutor.mutateResource<\n AddParticipantRequest,\n ParticipantResponse\n >(\"post\", this.links.participants, {\n identity: this.configuration.userIdentity,\n });\n\n return this;\n }\n\n /**\n * Leave the conversation.\n */\n async leave(): Promise<Conversation> {\n if (this.channelState.status === \"joined\") {\n await this.services.commandExecutor.mutateResource(\n \"delete\",\n `${this.links.participants}/${this.configuration.userIdentity}`\n );\n }\n\n return this;\n }\n\n /**\n * Remove a participant from the conversation. When a string is passed as the\n * argument, it will assume that the string is an identity or SID.\n * @param participant Identity, SID or the participant object to remove.\n */\n /* eslint-disable @typescript-eslint/ban-ts-comment */\n // @ts-ignore TODO: fix validateTypesAsync typing\n @validateTypesAsync([nonEmptyString, Participant])\n async removeParticipant(participant: string | Participant): Promise<void> {\n await this.participantsEntity.remove(\n typeof participant === \"string\" ? participant : participant.sid\n );\n }\n\n /**\n * Send a message to the conversation.\n * @param message Message body for the text message,\n * `FormData` or {@link SendMediaOptions} for media content. Sending FormData is supported only with the browser engine.\n * @param messageAttributes Attributes for the message.\n * @param emailOptions Email options for the message.\n * @return Index of the new message.\n */\n @validateTypesAsync(\n [\n \"string\",\n literal(null),\n // Wrapping it into a custom rule is necessary because the FormData class is not available on initialization.\n custom((value) => [value instanceof FormData, \"an instance of FormData\"]),\n objectSchema(\"media options\", {\n contentType: nonEmptyString,\n media: custom((value) => {\n let isValid =\n (typeof value === \"string\" && value.length > 0) ||\n value instanceof Uint8Array ||\n value instanceof ArrayBuffer;\n\n if (typeof Blob === \"function\") {\n isValid = isValid || value instanceof Blob;\n }\n\n return [\n isValid,\n \"a non-empty string, an instance of Buffer or an instance of Blob\",\n ];\n }),\n }),\n ],\n optionalAttributesValidator,\n [\n \"undefined\",\n literal(null),\n objectSchema(\"email attributes\", {\n subject: [nonEmptyString, \"undefined\"],\n }),\n ]\n )\n async sendMessage(\n message: null | string | FormData | SendMediaOptions,\n messageAttributes?: JSONValue,\n emailOptions?: SendEmailOptions\n ): Promise<number> {\n if (typeof message === \"string\" || message === null) {\n const response = await this.messagesEntity.send(\n message,\n messageAttributes,\n emailOptions\n );\n return parseToNumber(response.index) ?? 0;\n }\n\n const response = await this.messagesEntity.sendMedia(\n message,\n messageAttributes,\n emailOptions\n );\n return parseToNumber(response.index) ?? 0;\n }\n\n /**\n * New interface to prepare for sending a message.\n * Use instead of `sendMessage`.\n * @return A MessageBuilder to help set all message sending options.\n */\n public prepareMessage(): MessageBuilder {\n return new MessageBuilder(this.limits, this.messagesEntity);\n }\n\n /**\n * Set last read message index of the conversation to the index of the last known message.\n * @return Resulting unread messages count in the conversation.\n */\n public async setAllMessagesRead(): Promise<number> {\n await this._subscribeStreams();\n\n const messagesPage = await this.getMessages(1);\n\n if (messagesPage.items.length > 0) {\n return this.advanceLastReadMessageIndex(messagesPage.items[0].index);\n }\n\n return Promise.resolve(0);\n }\n\n /**\n * Set all messages in the conversation unread.\n * @return Resulting unread messages count in the conversation.\n */\n public async setAllMessagesUnread(): Promise<number> {\n await this._subscribeStreams();\n return await this._setLastReadMessageIndex(null);\n }\n\n /**\n * Set user notification level for this conversation.\n * @param notificationLevel New user notification level.\n */\n @validateTypesAsync(literal(\"default\", \"muted\"))\n async setUserNotificationLevel(\n notificationLevel: NotificationLevel\n ): Promise<void> {\n await this.services.commandExecutor.mutateResource<EditNotificationLevelRequest>(\n \"post\",\n `${this.configuration.links.myConversations}/${this.sid}`,\n {\n notification_level: notificationLevel,\n }\n );\n }\n\n /**\n * Send a notification to the server indicating that this client is currently typing in this conversation.\n * Typing ended notification is sent after a while automatically, but by calling this method again you ensure that typing ended is not received.\n */\n typing(): Promise<void> {\n return this.services.typingIndicator.send(this.sid);\n }\n\n /**\n * Update the attributes of the conversation.\n * @param attributes New attributes.\n */\n @validateTypesAsync(attributesValidator)\n async updateAttributes(attributes: JSONValue): Promise<Conversation> {\n await this.services.commandExecutor.mutateResource<\n EditConversationRequest,\n ConversationResponse\n >(\"post\", this.links.self, {\n attributes:\n attributes !== undefined ? JSON.stringify(attributes) : undefined,\n });\n\n return this;\n }\n\n /**\n * Update the friendly name of the conversation.\n * @param friendlyName New friendly name.\n */\n @validateTypesAsync([\"string\"])\n async updateFriendlyName(friendlyName: string): Promise<Conversation> {\n if (this.channelState.friendlyName !== friendlyName) {\n await this.services.commandExecutor.mutateResource<\n EditConversationRequest,\n ConversationResponse\n >(\"post\", this.links.self, { friendly_name: friendlyName });\n }\n\n return this;\n }\n\n /**\n * Set the last read message index to the current read horizon.\n * @param index Message index to set as last read.\n * If null is provided, then the behavior is identical to {@link Conversation.setAllMessagesUnread}.\n * @returns Resulting unread messages count in the conversation.\n */\n @validateTypesAsync([literal(null), nonNegativeInteger])\n async updateLastReadMessageIndex(index: number | null): Promise<number> {\n await this._subscribeStreams();\n return this._setLastReadMessageIndex(index);\n }\n\n /**\n * Update the unique name of the conversation.\n * @param uniqueName New unique name for the conversation. Setting unique name to null removes it.\n */\n @validateTypesAsync([\"string\", literal(null)])\n async updateUniqueName(uniqueName: string | null): Promise<Conversation> {\n if (this.channelState.uniqueName !== uniqueName) {\n if (!uniqueName) {\n uniqueName = \"\";\n }\n\n await this.services.commandExecutor.mutateResource<\n EditConversationRequest,\n ConversationResponse\n >(\"post\", this.links.self, {\n unique_name: uniqueName,\n });\n }\n\n return this;\n }\n}\n\nexport {\n ConversationDescriptor,\n Conversation,\n ConversationUpdateReason,\n ConversationStatus,\n NotificationLevel,\n ConversationState,\n ConversationUpdatedEventArgs,\n SendMediaOptions,\n SendEmailOptions,\n LastMessage,\n ConversationBindings,\n ConversationEmailBinding,\n};\n","class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve;\n private _reject;\n\n public current!: T;\n\n constructor() {\n this._promise = new Promise<T>((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n public get promise(): Promise<T> {\n return this._promise;\n }\n\n update(value: T) {\n this._resolve(value);\n }\n\n set(value: T) {\n this.current = value;\n this._resolve(value);\n }\n\n fail(e) {\n this._reject(e);\n }\n}\n\nexport { Deferred };\n","import { Logger } from \"../logger\";\nimport {\n Conversation,\n ConversationDescriptor,\n ConversationUpdatedEventArgs,\n ConversationUpdateReason,\n} from \"../conversation\";\nimport { SyncMap, SyncClient, SyncMapItem } from \"twilio-sync\";\nimport { Users } from \"./users\";\nimport { Network } from \"../services/network\";\nimport { TypingIndicator } from \"../services/typing-indicator\";\nimport { McsClient } from \"@twilio/mcs-client\";\nimport { Deferred } from \"../util/deferred\";\nimport {\n Participant,\n ParticipantUpdatedEventArgs,\n ParticipantUpdateReason,\n} from \"../participant\";\nimport {\n Message,\n MessageUpdatedEventArgs,\n MessageUpdateReason,\n} from \"../message\";\nimport { UriBuilder } from \"../util\";\nimport { Configuration } from \"../configuration\";\nimport { CommandExecutor } from \"../command-executor\";\nimport { CreateConversationRequest } from \"../interfaces/commands/create-conversation\";\nimport { ConversationResponse } from \"../interfaces/commands/conversation-response\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport isEqual from \"lodash.isequal\";\nimport { ResponseMeta } from \"../interfaces/commands/response-meta\";\n\ntype ConversationsEvents = {\n conversationAdded: (conversation: Conversation) => void;\n conversationJoined: (conversation: Conversation) => void;\n conversationLeft: (conversation: Conversation) => void;\n conversationRemoved: (conversation: Conversation) => void;\n conversationUpdated: (data: {\n conversation: Conversation;\n updateReasons: ConversationUpdateReason[];\n }) => void;\n participantJoined: (participant: Participant) => void;\n participantLeft: (participant: Participant) => void;\n participantUpdated: (data: {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n }) => void;\n messageAdded: (message: Message) => void;\n messageRemoved: (message: Message) => void;\n messageUpdated: (data: {\n message: Message;\n updateReasons: MessageUpdateReason[];\n }) => void;\n typingEnded: (participant: Participant) => void;\n typingStarted: (participant: Participant) => void;\n};\n\ntype ConversationsDataSource = \"sync\" | \"chat\" | \"rest\";\n\ninterface ConversationsServices {\n syncClient: SyncClient;\n users: Users;\n typingIndicator: TypingIndicator;\n network: Network;\n mcsClient: McsClient;\n commandExecutor: CommandExecutor;\n}\n\ntype ConversationRestData = {\n roster: string;\n notificationLevel: \"default\" | \"muted\";\n lastConsumedMessageIndex: number;\n channel: string;\n messages: string;\n descriptor: ConversationResponse;\n channel_sid: string;\n status: string;\n};\n\nconst log = Logger.scope(\"Conversations\");\n\n/**\n * Represents conversations collection\n * {@see Conversation}\n */\nclass Conversations extends ReplayEventEmitter<ConversationsEvents> {\n public readonly conversations: Map<string, Conversation> = new Map();\n public readonly myConversationsRead: Deferred<boolean> = new Deferred();\n private readonly configuration: Configuration;\n private readonly services: ConversationsServices;\n private readonly tombstones: Set<string> = new Set();\n private myConversationsFetched = false;\n\n public constructor(\n configuration: Configuration,\n services: ConversationsServices\n ) {\n super();\n\n this.configuration = configuration;\n this.services = services;\n }\n\n public async addConversation(options): Promise<Conversation> {\n const attributes =\n typeof options?.attributes !== \"undefined\" ? options.attributes : {};\n\n const response = await this.services.commandExecutor.mutateResource<\n CreateConversationRequest,\n ConversationResponse\n >(\"post\", this.configuration.links.conversations, {\n friendly_name: options.friendlyName,\n unique_name: options.uniqueName,\n attributes:\n typeof attributes !== \"undefined\"\n ? JSON.stringify(attributes)\n : undefined,\n });\n\n const conversationSid = response.sid ?? null;\n const conversationDocument = response.sync_objects?.conversation ?? null;\n const links = {\n self: response.url,\n ...response.links,\n };\n const existingConversation = this.conversations.get(conversationSid);\n\n if (existingConversation) {\n await existingConversation._subscribe();\n return existingConversation;\n }\n\n const conversation = new Conversation(\n {\n channel: conversationDocument,\n entityName: \"\",\n uniqueName: \"\",\n attributes: null,\n createdBy: \"\",\n friendlyName: \"\",\n lastConsumedMessageIndex: 0,\n dateCreated: null,\n dateUpdated: null,\n },\n conversationSid,\n links,\n this.configuration,\n this.services\n );\n\n this.conversations.set(conversation.sid, conversation);\n this._registerForEvents(conversation);\n\n await conversation._subscribe();\n this.emit(\"conversationAdded\", conversation);\n\n return conversation;\n }\n\n /**\n * Fetch conversations list and instantiate all necessary objects\n */\n public async fetchConversations(): Promise<Conversations> {\n try {\n const map = await this._getMap();\n\n map.on(\"itemAdded\", (args) => {\n log.debug(`itemAdded: ${args.item.key}`);\n\n this._upsertConversation(\"sync\", args.item.key, args.item.data);\n });\n\n map.on(\"itemRemoved\", (args) => {\n log.debug(`itemRemoved: ${args.key}`);\n\n const sid = args.key;\n\n if (!this.myConversationsFetched) {\n this.tombstones.add(sid);\n }\n\n const conversation = this.conversations.get(sid);\n\n if (!conversation) {\n return;\n }\n\n if (conversation.status === \"joined\") {\n conversation._setStatus(\"notParticipating\", \"sync\");\n this.emit(\"conversationLeft\", conversation);\n }\n\n this.conversations.delete(sid);\n this.emit(\"conversationRemoved\", conversation);\n conversation.emit(\"removed\", conversation);\n });\n\n map.on(\"itemUpdated\", (args) => {\n log.debug(`itemUpdated: ${args.item.key}`);\n\n this._upsertConversation(\"sync\", args.item.key, args.item.data);\n });\n\n const myConversations: ConversationRestData[] =\n await this._fetchMyConversations();\n const upserts: Promise<Conversation | null>[] = [];\n\n for (const conversation of myConversations) {\n upserts.push(\n this._upsertConversation(\n \"rest\",\n conversation[\"channel_sid\"],\n conversation\n )\n );\n }\n\n this.myConversationsRead.set(true);\n\n await Promise.all(upserts);\n\n this.myConversationsFetched = true;\n this.tombstones.clear();\n\n log.debug(\"The conversations list has been successfully fetched\");\n\n return this;\n } catch (error) {\n const errorMessage = \"Failed to fetch the conversations list\";\n\n if (this.services.syncClient.connectionState !== \"disconnected\") {\n log.error(errorMessage, error);\n }\n\n log.debug(`ERROR: ${errorMessage}`, error);\n\n throw error;\n }\n }\n\n public async getConversations() {\n const conversationsMap = await this._getMap();\n const page = await conversationsMap.getItems();\n\n return this._wrapPaginator(page, (items) =>\n Promise.all(\n items.map((item: SyncMapItem) =>\n this._upsertConversation(\"sync\", item.key, item.data)\n )\n )\n );\n }\n\n public async getConversation(\n sid: string\n ): Promise<Conversation | undefined | null> {\n const conversationsMap = await this._getMap();\n const page = await conversationsMap.getItems({ key: sid });\n const items = page.items.map((item: SyncMapItem) =>\n this._upsertConversation(\"sync\", item.key, item.data)\n );\n\n return items.length > 0 ? items[0] : null;\n }\n\n public async getConversationByUniqueName(\n uniqueName: string\n ): Promise<Conversation | null> {\n const url = new UriBuilder(this.configuration.links.myConversations)\n .path(uniqueName)\n .build();\n const response = await this.services.network.get<ConversationResponse>(url);\n const body = response.body;\n\n const sid = body.conversation_sid;\n const data = {\n entityName: null,\n lastConsumedMessageIndex: body.last_read_message_index,\n status: body?.status || \"unknown\",\n friendlyName: body.friendly_name,\n dateUpdated: body.date_updated,\n dateCreated: body.date_created,\n uniqueName: body.unique_name,\n createdBy: body.created_by,\n attributes: body.attributes,\n channel: body.sync_objects.conversation,\n notificationLevel: body?.notification_level,\n sid,\n };\n\n return sid ? this._upsertConversation(\"sync\", sid, data) : null;\n }\n\n public async peekConversation(sid: string): Promise<Conversation | null> {\n const url = new UriBuilder(this.configuration.links.conversations)\n .path(sid)\n .build();\n const response = await this.services.network.get<ConversationResponse>(url);\n const body = response.body;\n\n const data = {\n entityName: null,\n // lastConsumedMessageIndex: body.last_read_message_index,\n status: body?.status || \"unknown\",\n friendlyName: body.friendly_name,\n dateUpdated: body.date_updated,\n dateCreated: body.date_created,\n uniqueName: body.unique_name,\n createdBy: body.created_by,\n attributes: body.attributes,\n channel: `${sid}.channel`,\n // notificationLevel: body?.notification_level,\n sid,\n };\n\n return this._upsertConversation(\"sync\", sid, data);\n }\n\n private async _getMap(): Promise<SyncMap> {\n return await this.services.syncClient.map({\n id: this.configuration.myConversations,\n mode: \"open_existing\",\n });\n }\n\n private async _wrapPaginator(page, op) {\n const items = await op(page.items);\n\n return {\n items,\n hasNextPage: page.hasNextPage,\n hasPrevPage: page.hasPrevPage,\n nextPage: () => page.nextPage().then((x) => this._wrapPaginator(x, op)),\n prevPage: () => page.prevPage().then((x) => this._wrapPaginator(x, op)),\n };\n }\n\n private async _updateConversation(\n source: ConversationsDataSource,\n conversation: Conversation,\n data\n ): Promise<void> {\n const areSourcesDifferent =\n conversation._statusSource() !== undefined &&\n source !== conversation._statusSource();\n const isChannelSourceSync =\n source !== \"rest\" || conversation._statusSource() === \"sync\";\n\n if (areSourcesDifferent && isChannelSourceSync && source !== \"sync\") {\n log.trace(\n \"upsertConversation: conversation is known from sync and came from chat, ignoring\",\n {\n sid: conversation.sid,\n data: data.status,\n conversation: conversation.status,\n }\n );\n\n return;\n }\n\n if (data.status === \"joined\" && conversation.status !== \"joined\") {\n conversation._setStatus(\"joined\", source);\n\n const updateData: Partial<ConversationDescriptor> = {};\n\n if (typeof data.notificationLevel !== \"undefined\") {\n updateData.notificationLevel = data.notificationLevel;\n }\n\n if (typeof data.lastConsumedMessageIndex !== \"undefined\") {\n updateData.lastConsumedMessageIndex = data.lastConsumedMessageIndex;\n }\n\n if (!isEqual(updateData, {})) {\n conversation._update(updateData);\n }\n\n conversation._subscribe().then(() => {\n this.emit(\"conversationJoined\", conversation);\n });\n\n return;\n }\n\n if (\n data.status === \"notParticipating\" &&\n conversation.status === \"joined\"\n ) {\n conversation._setStatus(\"notParticipating\", source);\n conversation._update(data);\n await conversation._subscribe();\n this.emit(\"conversationLeft\", conversation);\n\n return;\n }\n\n if (data.status === \"notParticipating\") {\n await conversation._subscribe();\n\n return;\n }\n\n conversation._update(data);\n }\n\n private async _upsertConversation(\n source: ConversationsDataSource,\n sid: string,\n data\n ): Promise<Conversation | null> {\n log.trace(`upsertConversation called for ${sid}`, data);\n\n const conversation = this.conversations.get(sid);\n\n // If the channel is known, update it\n if (conversation) {\n log.trace(\n `upsertConversation: the conversation ${conversation.sid} is known;` +\n `its status is known from the source ${conversation._statusSource()} ` +\n `and the update came from the source ${source}`,\n conversation\n );\n\n await this._updateConversation(source, conversation, data);\n await conversation._subscribe();\n\n return conversation;\n }\n\n // If the conversations is deleted, ignore it\n if ([\"chat\", \"rest\"].includes(source) && this.tombstones.has(sid)) {\n log.trace(\n \"upsertChannel: the channel is deleted but reappeared again from chat, ignoring\",\n sid\n );\n return null;\n }\n\n // If the conversation is unknown, fetch it\n log.trace(\n \"upsertConversation: creating a local conversation object with sid \" +\n sid,\n data\n );\n\n const baseLink = `${this.configuration.links.conversations}/${sid}`;\n const links = {\n self: baseLink,\n messages: `${baseLink}/Messages`,\n participants: `${baseLink}/Participants`,\n };\n const newConversation = new Conversation(\n data,\n sid,\n links,\n this.configuration,\n this.services\n );\n this.conversations.set(sid, newConversation);\n\n await newConversation._subscribe();\n this._registerForEvents(newConversation);\n this.emit(\"conversationAdded\", newConversation);\n\n if (data.status === \"joined\") {\n newConversation._setStatus(\"joined\", source);\n this.emit(\"conversationJoined\", newConversation);\n }\n\n return newConversation;\n }\n private async _fetchMyConversations(): Promise<ConversationRestData[]> {\n let conversations: ConversationRestData[] = [];\n let pageToken: null | string = null;\n\n do {\n const url = new UriBuilder(this.configuration.links.myConversations);\n\n if (pageToken) {\n url.arg(\"PageToken\", pageToken);\n }\n\n const response = await this.services.network.get<\n { conversations: ConversationResponse[] } & ResponseMeta\n >(url.build());\n const receivedConversations = response.body?.conversations.map(\n (conversationDescriptor) => ({\n descriptor: conversationDescriptor,\n channel_sid: conversationDescriptor.conversation_sid,\n status: conversationDescriptor.status,\n channel: conversationDescriptor.sync_objects.conversation,\n messages: conversationDescriptor.sync_objects.messages,\n roster: `${conversationDescriptor.conversation_sid}.roster`,\n lastConsumedMessageIndex:\n conversationDescriptor.last_read_message_index,\n notificationLevel: conversationDescriptor.notification_level,\n })\n );\n\n pageToken = response.body.meta.next_token;\n conversations = [...conversations, ...receivedConversations];\n } while (pageToken);\n\n return conversations;\n }\n\n private _onConversationRemoved(sid: string) {\n const conversation = this.conversations.get(sid);\n\n if (conversation) {\n this.conversations.delete(sid);\n this.emit(\"conversationRemoved\", conversation);\n }\n }\n\n private _registerForEvents(conversation) {\n conversation.on(\"removed\", () =>\n this._onConversationRemoved(conversation.sid)\n );\n conversation.on(\"updated\", (args: ConversationUpdatedEventArgs) =>\n this.emit(\"conversationUpdated\", args)\n );\n conversation.on(\"participantJoined\", (participant) =>\n this.emit(\"participantJoined\", participant)\n );\n conversation.on(\"participantLeft\", (participant) =>\n this.emit(\"participantLeft\", participant)\n );\n conversation.on(\"participantUpdated\", (args: ParticipantUpdatedEventArgs) =>\n this.emit(\"participantUpdated\", args)\n );\n conversation.on(\"messageAdded\", (message) =>\n this.emit(\"messageAdded\", message)\n );\n conversation.on(\"messageUpdated\", (args: MessageUpdatedEventArgs) =>\n this.emit(\"messageUpdated\", args)\n );\n conversation.on(\"messageRemoved\", (message) =>\n this.emit(\"messageRemoved\", message)\n );\n conversation.on(\"typingStarted\", (participant) =>\n this.emit(\"typingStarted\", participant)\n );\n conversation.on(\"typingEnded\", (participant) =>\n this.emit(\"typingEnded\", participant)\n );\n }\n}\n\nexport {\n ConversationsServices,\n ConversationsDataSource,\n Conversation,\n Conversations,\n};\n","import { User, UserUpdatedEventArgs, UserUpdateReason } from \"../user\";\nimport { Network } from \"../services/network\";\nimport { SyncClient } from \"twilio-sync\";\nimport { UriBuilder } from \"../util\";\nimport { Configuration } from \"../configuration\";\nimport { CommandExecutor } from \"../command-executor\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport { UserResponse } from \"../interfaces/commands/user\";\n\ntype UsersEvents = {\n userUpdated: (data: {\n user: User;\n updateReasons: UserUpdateReason[];\n }) => void;\n userSubscribed: (user: User) => void;\n userUnsubscribed: (user: User) => void;\n};\n\nexport interface UsersServices {\n network: Network;\n syncClient: SyncClient;\n commandExecutor: CommandExecutor;\n}\n\n/**\n * Container for known users\n */\nclass Users extends ReplayEventEmitter<UsersEvents> {\n private readonly configuration: Configuration;\n private readonly services: UsersServices;\n\n private subscribedUsers: Map<string, User>;\n private fifoStack: string[];\n public readonly myself: User;\n\n constructor(\n myself: User,\n configuration: Configuration,\n services: UsersServices\n ) {\n super();\n\n this.configuration = configuration;\n this.services = services;\n\n this.fifoStack = [];\n this.myself = myself;\n this.myself.on(\"updated\", (args: UserUpdatedEventArgs) =>\n this.emit(\"userUpdated\", args)\n );\n this.myself.on(\"userSubscribed\", () =>\n this.emit(\"userSubscribed\", this.myself)\n );\n this.myself.on(\"userUnsubscribed\", () => {\n this.emit(\"userUnsubscribed\", this.myself);\n this.myself._ensureFetched();\n });\n\n this.subscribedUsers = new Map<string, User>();\n }\n\n private handleUnsubscribeUser(user: User): void {\n if (this.subscribedUsers.has(user.identity)) {\n this.subscribedUsers.delete(user.identity);\n }\n let foundItemIndex = 0;\n const foundItem = this.fifoStack.find((item, index) => {\n if (item == user.identity) {\n foundItemIndex = index;\n return true;\n }\n return false;\n });\n if (foundItem) {\n this.fifoStack.splice(foundItemIndex, 1);\n }\n this.emit(\"userUnsubscribed\", user);\n }\n\n private handleSubscribeUser(user: User): void {\n if (this.subscribedUsers.has(user.identity)) {\n return;\n }\n if (this.fifoStack.length >= this.configuration.userInfosToSubscribe) {\n const item = this.fifoStack.shift() as string;\n this.subscribedUsers?.get(item)?.unsubscribe();\n }\n this.fifoStack.push(user.identity);\n this.subscribedUsers.set(user.identity, user);\n this.emit(\"userSubscribed\", user);\n }\n\n /**\n * Gets user, if it's in subscribed list - then return the user object from it,\n * if not - then subscribes and adds user to the FIFO stack\n * @returns {Promise<User>} Fully initialized user\n */\n async getUser(identity = \"\", entityName = \"\"): Promise<User> {\n await this.myself._ensureFetched();\n\n if (identity == this.myself.identity) {\n return this.myself;\n }\n\n const user = this.subscribedUsers.get(identity);\n\n if (user) {\n return user;\n }\n\n entityName = entityName || (await this.getSyncUniqueName(identity));\n\n const newUser = new User(\n identity,\n entityName,\n this.configuration,\n this.services\n );\n\n newUser.on(\"updated\", (args: UserUpdatedEventArgs) =>\n this.emit(\"userUpdated\", args)\n );\n newUser.on(\"userSubscribed\", () => this.handleSubscribeUser(newUser));\n newUser.on(\"userUnsubscribed\", () => this.handleUnsubscribeUser(newUser));\n await newUser._ensureFetched();\n\n return newUser;\n }\n\n /**\n * @returns {Promise<Array<User>>} returns list of subscribed User objects {@see User}\n */\n async getSubscribedUsers(): Promise<Array<User>> {\n await this.myself._ensureFetched();\n\n const users = [this.myself];\n this.subscribedUsers.forEach((user) => users.push(user));\n\n return users;\n }\n\n /**\n * @returns {Promise<string>} User's sync unique name\n */\n private async getSyncUniqueName(identity: string): Promise<string> {\n const url = new UriBuilder(this.configuration.links.users)\n .path(identity)\n .build();\n const response = await this.services.network.get<UserResponse>(url);\n return response.body?.sync_objects.user_info_map ?? \"\";\n }\n}\n\nexport { Users };\n","import { Logger } from \"../logger\";\n\nimport { Notifications } from \"@twilio/notifications\";\n\nimport { NotificationTypes } from \"../interfaces/notification-types\";\nimport { TwilsockClient } from \"twilsock\";\nimport { Configuration } from \"../configuration\";\n\nconst log = Logger.scope(\"TypingIndicator\");\n\nexport interface TypingIndicatorServices {\n twilsockClient: TwilsockClient;\n notificationClient: Notifications;\n}\n\n/**\n * An important note in regards to typing timeout timers. There are two places that the SDK can get the \"typing_timeout\" attribute from. The first\n * place that the attribute appears in is the response received from POST -> /v1/typing REST call. In the body of that response, the value of the\n * \"typing_timeout\" attribute will be exactly the same as defined in the console. The second place that the attribute appears in is from a\n * notification of type \"twilio.ipmsg.typing_indicator\". In this case, the \"typing_timeout\" value will be +1 of that in the console. This\n * intentional. The timeout returned from the POST -> /v1/typing call should be used to disable further calls for that period of time. On contrary,\n * the timeout returned from the notification should be used as the timeout for the \"typingEnded\" event, +1 is to account for latency.\n *\n * @private\n */\n\n/**\n * @class TypingIndicator\n *\n * @constructor\n * @private\n */\nclass TypingIndicator {\n private readonly services: TypingIndicatorServices;\n private readonly configuration: Configuration;\n\n private sentUpdates: Map<string, number>;\n private getConversation;\n private serviceTypingTimeout;\n\n constructor(\n getConversation,\n config: Configuration,\n services: TypingIndicatorServices\n ) {\n this.configuration = config;\n this.services = services;\n this.getConversation = getConversation;\n\n this.serviceTypingTimeout = null;\n this.sentUpdates = new Map();\n }\n\n public get typingTimeout(): number {\n return (\n this.configuration.typingIndicatorTimeoutOverride ||\n this.serviceTypingTimeout ||\n this.configuration.typingIndicatorTimeoutDefault\n );\n }\n\n /**\n * Initialize TypingIndicator controller\n * Registers for needed message types and sets listeners\n * @private\n */\n initialize(): void {\n // this.services.notificationClient.subscribe(NotificationTypes.TYPING_INDICATOR, 'twilsock');\n this.services.notificationClient.on(\"message\", async (type, message) => {\n if (type === NotificationTypes.TYPING_INDICATOR) {\n await this._handleRemoteTyping(message);\n }\n });\n }\n\n /**\n * Remote participants typing events handler\n */\n private async _handleRemoteTyping(message) {\n log.trace(\"Got new typing indicator \", message);\n\n this.getConversation(message.channel_sid)\n .then((conversation) => {\n if (!conversation) {\n return;\n }\n\n conversation.participants.forEach((participant) => {\n if (participant.identity !== message.identity) {\n return;\n }\n\n const timeout = this.configuration.typingIndicatorTimeoutOverride\n ? this.configuration.typingIndicatorTimeoutOverride + 1000\n : message.typing_timeout * 1000;\n participant._startTyping(timeout);\n });\n })\n .catch((err) => {\n log.error(err);\n throw err;\n });\n }\n\n /**\n * Send typing event for the given conversation sid\n * @param {String} conversationSid\n */\n send(conversationSid: string) {\n const lastUpdate = this.sentUpdates.get(conversationSid);\n if (lastUpdate && lastUpdate > Date.now() - this.typingTimeout) {\n return Promise.resolve();\n }\n\n this.sentUpdates.set(conversationSid, Date.now());\n return this._send(conversationSid);\n }\n\n private _send(conversationSid: string) {\n log.trace(\"Sending typing indicator\");\n\n const url = this.configuration.links.typing;\n const headers = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n };\n const body = `ChannelSid=${conversationSid}`;\n\n return this.services.twilsockClient\n .post<{ typing_timeout: number }>(\n url,\n headers,\n body,\n this.configuration.productId\n )\n .then((response) => {\n if (response.body.hasOwnProperty(\"typing_timeout\")) {\n this.serviceTypingTimeout = response.body.typing_timeout * 1000;\n }\n })\n .catch((err) => {\n log.error(\"Failed to send typing indicator:\", err);\n throw err;\n });\n }\n}\n\nexport { TypingIndicator };\n","/**\n * Push notification type.\n */\ntype PushNotificationType =\n | \"twilio.conversations.new_message\"\n | \"twilio.conversations.added_to_conversation\"\n | \"twilio.conversations.removed_from_conversation\";\n\ninterface PushNotificationDescriptor {\n title: string | null;\n body: string | null;\n sound: string | null;\n badge: number | null;\n action: string | null;\n type: PushNotificationType;\n data: Record<string, unknown>;\n}\n\n/**\n * Additional data for a given push notification.\n */\ninterface PushNotificationData {\n /**\n * SID of the conversation.\n */\n conversationSid?: string;\n\n /**\n * Index of the message in the conversation.\n */\n messageIndex?: number;\n\n /**\n * SID of the message in the conversation.\n */\n messageSid?: string;\n}\n\n/**\n * Push notification for a Conversations client.\n */\nclass PushNotification {\n /**\n * Title of the notification.\n */\n public readonly title: string | null;\n\n /**\n * Text of the notification.\n */\n public readonly body: string | null;\n\n /**\n * Sound of the notification.\n */\n public readonly sound: string | null;\n\n /**\n * Number of the badge.\n */\n public readonly badge: number | null;\n\n /**\n * Notification action (`click_action` in FCM terms and `category` in APN terms).\n */\n public readonly action: string | null;\n\n /**\n * Type of the notification.\n */\n public readonly type: PushNotificationType;\n\n /**\n * Additional data of the conversation.\n */\n public readonly data: PushNotificationData;\n\n /**\n * @internal\n */\n constructor(data: PushNotificationDescriptor) {\n this.title = data.title || null;\n this.body = data.body || null;\n this.sound = data.sound || null;\n this.badge = data.badge || null;\n this.action = data.action || null;\n this.type = data.type || null;\n this.data = data.data || {};\n }\n}\n\nexport {\n PushNotification,\n PushNotificationType,\n PushNotificationDescriptor,\n PushNotificationData,\n};\n","import { TransportResult as Result, Transport } from \"twilsock\";\nimport { MutationConflictResponse } from \"./interfaces/commands/mutation-conflict\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { AsyncRetrier } from \"@twilio/operation-retrier\";\n\nexport interface CommandExecutorServices {\n transport: Transport;\n}\n\nconst trimSlashes = (url: string): string => url.replace(/(^\\/+|\\/+$)/g, \"\");\n\nconst isMutationConflictResponse = (\n response: Result<unknown>\n): response is Result<MutationConflictResponse> => response.status.code === 202;\n\nclass CommandExecutor {\n constructor(\n private _serviceUrl: string,\n private _services: CommandExecutorServices,\n private _productId?: string\n ) {}\n\n private _preProcessUrl(url: string): string {\n const trimmedUrl = trimSlashes(url);\n\n if (/^https?:\\/\\//.test(url)) {\n return trimmedUrl;\n }\n\n return `${trimSlashes(this._serviceUrl)}/${trimmedUrl}`;\n }\n\n private async _makeRequest<REQ = void, RESP = void>(\n method: \"get\" | \"post\" | \"delete\",\n url: string,\n requestBody?: REQ,\n headers?: Record<string, string>\n ): Promise<Result<RESP>> {\n const preProcessedUrl = this._preProcessUrl(url);\n const finalHeaders = {\n \"Content-Type\": \"application/json; charset=utf-8\",\n ...(headers || {}),\n };\n let response: Result<RESP>;\n\n switch (method) {\n case \"get\":\n let getUrl = preProcessedUrl;\n\n if (requestBody) {\n getUrl +=\n \"?\" +\n Object.entries(requestBody)\n .map((entry) => entry.map(encodeURIComponent).join(\"=\"))\n .join(\"&\");\n }\n\n response = await this._services.transport.get(\n getUrl,\n finalHeaders,\n this._productId\n );\n break;\n case \"post\":\n response = await this._services.transport.post(\n preProcessedUrl,\n finalHeaders,\n JSON.stringify(requestBody),\n this._productId\n );\n break;\n case \"delete\":\n response = await this._services.transport.delete(\n preProcessedUrl,\n finalHeaders,\n {},\n this._productId\n );\n break;\n }\n\n if (response.status.code < 200 || response.status.code >= 300) {\n throw new Error(\n `Request responded with a non-success code ${response.status.code}`\n );\n }\n\n return response;\n }\n\n public async fetchResource<REQ = void, RESP = void>(\n url: string,\n requestBody?: REQ\n ): Promise<RESP> {\n const maxAttemptsCount = 6;\n\n try {\n const result = await new AsyncRetrier({\n min: 50,\n max: 1600,\n maxAttemptsCount,\n }).run(() => this._makeRequest<REQ, RESP>(\"get\", url, requestBody));\n return result.body;\n } catch {\n throw new Error(`Fetch resource from \"${url}\" failed.`);\n }\n }\n\n public async mutateResource<REQ = void, RESP = void>(\n method: \"post\" | \"delete\",\n url: string,\n requestBody?: REQ\n ): Promise<RESP> {\n const result = await this._makeRequest<REQ, RESP>(\n method,\n url,\n requestBody,\n {\n \"X-Twilio-Mutation-Id\": uuidv4(),\n }\n );\n\n if (isMutationConflictResponse(result)) {\n return await this.fetchResource<undefined, RESP>(\n result.body.resource_url\n );\n }\n\n return result.body;\n }\n}\n\nexport { CommandExecutor };\n","import { Logger } from \"./logger\";\nimport { Configuration } from \"./configuration\";\n\nimport { User, UserUpdatedEventArgs, UserUpdateReason } from \"./user\";\nimport { Network } from \"./services/network\";\n\nimport { NotificationTypes } from \"./interfaces/notification-types\";\n\nimport {\n TwilsockClient,\n InitRegistration,\n ConnectionState as TwilsockConnectionState,\n Transport,\n} from \"twilsock\";\nimport {\n ChannelType,\n Notifications as NotificationClient,\n} from \"@twilio/notifications\";\nimport { SyncClient } from \"twilio-sync\";\nimport { McsClient } from \"@twilio/mcs-client\";\n\nimport {\n Conversation,\n Conversations,\n Conversations as ConversationsEntity,\n} from \"./data/conversations\";\n\nimport { Users } from \"./data/users\";\nimport { TypingIndicator } from \"./services/typing-indicator\";\nimport { Paginator } from \"./interfaces/paginator\";\nimport { PushNotification } from \"./push-notification\";\nimport { deepClone, parseToNumber } from \"./util\";\nimport {\n Participant,\n ParticipantUpdatedEventArgs,\n ParticipantUpdateReason,\n} from \"./participant\";\nimport {\n Message,\n MessageUpdatedEventArgs,\n MessageUpdateReason,\n} from \"./message\";\nimport { TelemetryEventDescription, TelemetryPoint } from \"twilsock\";\nimport {\n validateTypesAsync,\n validateTypes,\n literal,\n nonEmptyString,\n pureObject,\n objectSchema,\n validateConstructorTypes,\n} from \"@twilio/declarative-type-validator\";\nimport { version } from \"../package.json\";\nimport {\n ConversationUpdatedEventArgs,\n ConversationUpdateReason,\n} from \"./conversation\";\nimport { CommandExecutor } from \"./command-executor\";\nimport { ConfigurationResponse } from \"./interfaces/commands/configuration\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport { JSONValue } from \"./types\";\n\nconst log = Logger.scope(\"Client\");\n\nconst SDK_VERSION = version;\n\nclass ClientServices {\n commandExecutor!: CommandExecutor;\n twilsockClient!: TwilsockClient;\n users!: Users;\n notificationClient!: NotificationClient;\n network!: Network;\n typingIndicator!: TypingIndicator;\n syncClient!: SyncClient;\n mcsClient!: McsClient;\n transport!: Transport;\n}\n\ntype ClientEvents = {\n conversationAdded: (conversation: Conversation) => void;\n conversationJoined: (conversation: Conversation) => void;\n conversationLeft: (conversation: Conversation) => void;\n conversationRemoved: (conversation: Conversation) => void;\n conversationUpdated: (data: {\n conversation: Conversation;\n updateReasons: ConversationUpdateReason[];\n }) => void;\n participantJoined: (participant: Participant) => void;\n participantLeft: (participant: Participant) => void;\n participantUpdated: (data: {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n }) => void;\n messageAdded: (message: Message) => void;\n messageRemoved: (message: Message) => void;\n messageUpdated: (data: {\n message: Message;\n updateReasons: MessageUpdateReason[];\n }) => void;\n tokenAboutToExpire: (ttl: number) => void;\n tokenExpired: () => void;\n typingEnded: (participant: Participant) => void;\n typingStarted: (participant: Participant) => void;\n pushNotification: (pushNotification: PushNotification) => void;\n userSubscribed: (user: User) => void;\n userUnsubscribed: (user: User) => void;\n userUpdated: (data: {\n user: User;\n updateReasons: UserUpdateReason[];\n }) => void;\n stateChanged: (state: State) => void;\n connectionStateChanged: (state: TwilsockConnectionState) => void;\n connectionError: (data: {\n terminal: boolean;\n message: string;\n httpStatusCode?: number;\n errorCode?: number;\n }) => void;\n};\n\n/**\n * Connection state of the client. Possible values are as follows:\n * * `'connecting'` - client is offline and connection attempt is in process\n * * `'connected'` - client is online and ready\n * * `'disconnecting'` - client is going offline as disconnection is in process\n * * `'disconnected'` - client is offline and no connection attempt is in process\n * * `'denied'` - client connection is denied because of invalid JWT access token. User must refresh token in order to proceed\n */\ntype ConnectionState = TwilsockConnectionState;\n\n/**\n * State of the client. Possible values are as follows:\n * * `'failed'` - the client failed to initialize\n * * `'initialized'` - the client successfully initialized\n */\ntype State = \"failed\" | \"initialized\";\n\n/**\n * Notifications channel type. Possible values are as follows:\n * * `'fcm'`\n * * `'apn'`\n */\ntype NotificationsChannelType = ChannelType;\n\ntype LogLevel = \"trace\" | \"debug\" | \"info\" | \"warn\" | \"error\" | \"silent\";\n\n/**\n * Conversations client options.\n */\ninterface ClientOptions {\n /**\n * The level of logging to enable.\n */\n logLevel?: LogLevel;\n region?: string;\n productId?: string;\n twilsockClient?: TwilsockClient;\n transport?: Transport;\n notificationsClient?: NotificationClient;\n syncClient?: SyncClient;\n typingIndicatorTimeoutOverride?: number;\n consumptionReportIntervalOverride?: string;\n httpCacheIntervalOverride?: string;\n userInfosToSubscribeOverride?: number;\n retryWhenThrottledOverride?: boolean;\n backoffConfigOverride?: Record<string, unknown>;\n Chat?: ClientOptions;\n IPMessaging?: ClientOptions;\n Sync?: Record<string, unknown>;\n Notification?: Record<string, unknown>;\n Twilsock?: Record<string, unknown>;\n clientMetadata?: Record<string, unknown>;\n initRegistrations?: InitRegistration[];\n disableDeepClone?: boolean;\n typingUri?: string;\n apiUri?: string;\n}\n\n/**\n * Options for {@link Client.createConversation}.\n */\ninterface CreateConversationOptions {\n /**\n * Any custom attributes to attach to the conversation.\n */\n attributes?: JSONValue;\n\n /**\n * A non-unique display name of the conversation.\n */\n friendlyName?: string;\n\n /**\n * A unique identifier of the conversation.\n */\n uniqueName?: string;\n}\n\n/**\n * A client is the starting point to the Twilio Conversations functionality.\n */\n@validateConstructorTypes(nonEmptyString, [pureObject, \"undefined\"])\nclass Client extends ReplayEventEmitter<ClientEvents> {\n /**\n * Client connection state.\n */\n public connectionState: ConnectionState = \"unknown\";\n private conversationsPromise!: Promise<Conversations>;\n private _ensureReady!: Promise<void>;\n private _resolveEnsureReady!: () => void;\n private _rejectEnsureReady!: (err: Error) => void;\n private fpaToken: string;\n private configuration!: Configuration;\n private conversations!: Conversations;\n private readonly options: Partial<ClientOptions>;\n private services: ClientServices;\n private readonly _myself: User;\n\n /**\n * Current version of the Conversations client.\n */\n public static readonly version: string = SDK_VERSION;\n\n /**\n * Current version of the Conversations client.\n */\n public readonly version: string = SDK_VERSION;\n\n private static readonly supportedPushChannels: NotificationsChannelType[] = [\n \"fcm\",\n \"apn\",\n ];\n private static readonly supportedPushDataFields = {\n conversation_sid: \"conversationSid\",\n message_sid: \"messageSid\",\n message_index: \"messageIndex\",\n };\n\n /**\n * Returned Conversations instance is not yet fully initialized. Calling any operations will block until it is.\n * Use connection events to monitor when client becomes fully available (connectionStateChanged with state\n * 'connected') or not available (connectionStateChange with state 'denied', event tokenExpired, event connectionError).\n *\n * @param fpaToken Access token\n * @param options Options to customize the Client\n * @returns A not yet fully-initialized client.\n */\n public constructor(fpaToken: string, options: ClientOptions | null = {}) {\n super();\n\n this.fpaToken = fpaToken ?? \"\";\n this.options = options ?? {};\n\n if (!this.options.disableDeepClone) {\n let options: Partial<ClientOptions> = {\n ...this.options,\n transport: undefined,\n twilsockClient: undefined,\n };\n\n options = deepClone(options);\n options.transport = this.options.transport;\n options.twilsockClient = this.options.twilsockClient;\n\n this.options = options;\n }\n\n this.options.logLevel = this.options.logLevel ?? \"silent\";\n log.setLevel(this.options.logLevel);\n\n const productId = (this.options.productId = \"ip_messaging\");\n\n // Filling ClientMetadata\n this.options.clientMetadata = this.options.clientMetadata || {};\n\n if (!this.options.clientMetadata.hasOwnProperty(\"type\")) {\n this.options.clientMetadata.type = \"conversations\";\n }\n\n if (!this.options.clientMetadata.hasOwnProperty(\"sdk\")) {\n this.options.clientMetadata.sdk = \"JS\";\n this.options.clientMetadata.sdkv = SDK_VERSION;\n }\n\n // Enable session local storage for Sync\n this.options.Sync = this.options.Sync || {};\n\n if (typeof this.options.Sync.enableSessionStorage === \"undefined\") {\n this.options.Sync.enableSessionStorage = true;\n }\n\n if (this.options.region) {\n this.options.Sync.region = this.options.region;\n }\n\n if (!fpaToken) {\n throw new Error(\"A valid Twilio token should be provided\");\n }\n\n this.services = new ClientServices();\n\n this._myself = new User(\"\", \"\", null, this.services);\n\n const startTwilsock = !this.options.twilsockClient;\n\n // Create default init registrations if none were provided.\n // Otherwise, the outside party have to list all the init registrations they\n // need.\n // Init registrations passed to the Conversations client will be passed down\n // to the Sync client as well.\n if (!this.options.initRegistrations) {\n const initRegistration = new InitRegistration(productId);\n Client.populateInitRegistrations(initRegistration);\n this.options.initRegistrations = [initRegistration];\n }\n\n this.services.twilsockClient = this.options.twilsockClient =\n this.options.twilsockClient ??\n new TwilsockClient(fpaToken, productId, this.options);\n\n this.services.twilsockClient.on(\"tokenAboutToExpire\", (ttl) =>\n this.emit(\"tokenAboutToExpire\", ttl)\n );\n this.services.twilsockClient.on(\"tokenExpired\", () =>\n this.emit(\"tokenExpired\")\n );\n this.services.twilsockClient.on(\"connectionError\", (error) =>\n this.emit(\"connectionError\", error)\n );\n this.services.twilsockClient.on(\n \"stateChanged\",\n (state: ConnectionState) => {\n log.debug(\n `Handling stateChanged for ConversationsClient: new state ${state}`\n );\n if (state !== this.connectionState) {\n this.connectionState = state;\n this.emit(\"connectionStateChanged\", this.connectionState);\n }\n }\n );\n\n this.services.transport = this.options.transport = (this.options\n .transport ?? this.options.twilsockClient) as Transport;\n this.services.notificationClient = this.options.notificationsClient =\n this.options.notificationsClient ??\n new NotificationClient(fpaToken, this.options);\n this.services.syncClient = this.options.syncClient =\n this.options.syncClient ?? new SyncClient(fpaToken, this.options);\n\n const configurationOptions =\n options?.Chat || options?.IPMessaging || options || {};\n const region = configurationOptions.region || options?.region;\n const baseUrl: string =\n configurationOptions.apiUri ||\n configurationOptions.typingUri ||\n `https://aim.${region || \"us1\"}.twilio.com`;\n\n this.services.commandExecutor = new CommandExecutor(\n baseUrl,\n { transport: this.options.transport },\n productId\n );\n\n const emitFailed = (err): void => {\n this._rejectEnsureReady(err);\n this.emit(\"stateChanged\", \"failed\");\n };\n\n this.services.twilsockClient.once(\"connectionError\", emitFailed);\n this.services.twilsockClient.once(\"disconnected\", emitFailed);\n\n // ConversationsClient will be able to initialize only after twilsock is connected\n this.services.twilsockClient.once(\"connected\", async () => {\n log.debug(`ConversationsClient started INITIALIZING`);\n this.services.twilsockClient.off(\"connectionError\", emitFailed);\n this.services.twilsockClient.off(\"disconnected\", emitFailed);\n try {\n const startupEvent = \"conversations.client.startup\";\n\n this.services.twilsockClient.addPartialTelemetryEvent(\n new TelemetryEventDescription(\n startupEvent,\n \"Conversations client startup\",\n new Date()\n ),\n startupEvent,\n TelemetryPoint.Start\n );\n\n await this._initialize();\n\n this.services.twilsockClient.addPartialTelemetryEvent(\n new TelemetryEventDescription(\"\", \"\", new Date()),\n startupEvent,\n TelemetryPoint.End\n );\n } catch (err) {\n // Fail ChatClient if initialization is incomplete\n this._rejectEnsureReady(err);\n this.emit(\"stateChanged\", \"failed\");\n }\n });\n\n this._ensureReady = new Promise<void>((resolve, reject) => {\n this._resolveEnsureReady = resolve;\n this._rejectEnsureReady = reject;\n }).catch(() => void 0); // @todo How to process unhandled rejection here?\n\n if (startTwilsock) {\n this.services.twilsockClient.connect();\n }\n }\n\n public static populateInitRegistrations(reg: InitRegistration) {\n reg.populateInitRegistrations([NotificationTypes.TYPING_INDICATOR]);\n SyncClient.populateInitRegistrations(reg);\n }\n\n /**\n * Fired when a conversation becomes visible to the client. The event is also triggered when the client creates a new conversation.\n * Fired for all conversations client has joined.\n *\n * Parameters:\n * 1. {@link Conversation} `conversation` - the conversation in question\n * @event\n */\n static readonly conversationAdded = \"conversationAdded\";\n\n /**\n * Fired when the client joins a conversation.\n *\n * Parameters:\n * 1. {@link Conversation} `conversation` - the conversation in question\n * @event\n */\n static readonly conversationJoined = \"conversationJoined\";\n\n /**\n * Fired when the client leaves a conversation.\n *\n * Parameters:\n * 1. {@link Conversation} `conversation` - the conversation in question\n * @event\n */\n static readonly conversationLeft = \"conversationLeft\";\n\n /**\n * Fired when a conversation is no longer visible to the client.\n *\n * Parameters:\n * 1. {@link Conversation} `conversation` - the conversation in question\n * @event\n */\n static readonly conversationRemoved = \"conversationRemoved\";\n\n /**\n * Fired when the attributes or the metadata of a conversation have been updated.\n * During conversation's creation and initialization, this event might be fired multiple times\n * for same joined or created conversation as new data is arriving from different sources.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the following properties:\n * * {@link Conversation} `conversation` - the conversation in question\n * * {@link ConversationUpdateReason}[] `updateReasons` - array of reasons for the update\n * @event\n */\n static readonly conversationUpdated = \"conversationUpdated\";\n\n /**\n * Fired when a participant has joined a conversation.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant in question\n * @event\n */\n static readonly participantJoined = \"participantJoined\";\n\n /**\n * Fired when a participant has left a conversation.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant in question\n * @event\n */\n static readonly participantLeft = \"participantLeft\";\n\n /**\n * Fired when a participant's fields have been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the following properties:\n * * {@link Participant} `participant` - the participant in question\n * * {@link ParticipantUpdateReason}[] `updateReasons` - array of reasons for the update\n * @event\n */\n static readonly participantUpdated = \"participantUpdated\";\n\n /**\n * Fired when a new message has been added to the conversation on the server.\n *\n * Parameters:\n * 1. {@link Message} `message` - the message in question\n * @event\n */\n static readonly messageAdded = \"messageAdded\";\n\n /**\n * Fired when a message is removed from the message list of a conversation.\n *\n * Parameters:\n * 1. {@link Message} `message` - the message in question\n * @event\n */\n static readonly messageRemoved = \"messageRemoved\";\n\n /**\n * Fired when the fields of an existing message are updated with new values.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the following properties:\n * * {@link Message} `message` - the message in question\n * * {@link MessageUpdateReason}[] `updateReasons` - array of reasons for the update\n * @event\n */\n static readonly messageUpdated = \"messageUpdated\";\n\n /**\n * Fired when the token is about to expire and needs to be updated.\n * * Parameters:\n * 1. number `message` - token's time to live\n * @event\n */\n static readonly tokenAboutToExpire = \"tokenAboutToExpire\";\n\n /**\n * Fired when the token has expired.\n * @event\n */\n static readonly tokenExpired = \"tokenExpired\";\n\n /**\n * Fired when a participant has stopped typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant in question\n * @event\n */\n static readonly typingEnded = \"typingEnded\";\n\n /**\n * Fired when a participant has started typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant in question\n * @event\n */\n static readonly typingStarted = \"typingStarted\";\n\n /**\n * Fired when the client has received (and parsed) a push notification via one of the push channels (apn or fcm).\n *\n * Parameters:\n * 1. {@link PushNotification} `pushNotification` - the push notification in question\n * @event\n */\n static readonly pushNotification = \"pushNotification\";\n\n /**\n * Fired when the client has subscribed to a user.\n *\n * Parameters:\n * 1. {@link User} `user` - the user in question\n * @event\n */\n static readonly userSubscribed = \"userSubscribed\";\n\n /**\n * Fired when the client has unsubscribed from a user.\n *\n * Parameters:\n * 1. {@link User} `user` - the user in question\n * @event\n */\n static readonly userUnsubscribed = \"userUnsubscribed\";\n\n /**\n * Fired when the properties or the reachability status of a user have been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the following properties:\n * * {@link User} `user` - the user in question\n * * {@link UserUpdateReason}[] `updateReasons` - array of reasons for the update\n * @event\n */\n static readonly userUpdated = \"userUpdated\";\n\n /**\n * Fired when the state of the client has been changed.\n *\n * Parameters:\n * 1. {@link State} `state` - the new client state\n * @event\n */\n static readonly stateChanged = \"stateChanged\";\n\n /**\n * Fired when the connection state of the client has been changed.\n *\n * Paremeters:\n * 1. {@link ConnectionState} `state` - the new connection state\n * @event\n */\n static readonly connectionStateChanged = \"connectionStateChanged\";\n\n /**\n * Fired when the connection is interrupted for an unexpected reason.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the following properties:\n * * boolean `terminal` - Twilsock will stop connection attempts if true\n * * string `message` - the error message of the root cause\n * * number? `httpStatusCode` - http status code if available\n * * number? `errorCode` - Twilio public error code if available\n * @event\n */\n static readonly connectionError = \"connectionError\";\n\n /**\n * @deprecated Call constructor directly.\n *\n * Factory method to create a Conversations client instance.\n *\n * The factory method will automatically trigger connection.\n * Do not use it if you need finer-grained control.\n *\n * Since this method returns an already-initialized client, some of the events\n * will be lost because they happen *before* the initialization. It is\n * recommended that `client.onWithReplay` is used as opposed to `client.on`\n * for subscribing to client events. The `client.onWithReplay` will re-emit\n * the most recent value for a given event if it emitted before the\n * subscription.\n *\n * @param token Access token.\n * @param options Options to customize the client.\n * @returns Returns a fully initialized client.\n */\n @validateTypesAsync(\"string\", [\"undefined\", pureObject])\n static async create(\n token: string,\n options?: ClientOptions | null\n ): Promise<Client> {\n // The logic is as follows:\n // - If twilsock is not passed in, then the ConversationsClient constructor will call twilsock.connect() by itself\n // and we do not need to do it here.\n // - If twilsock was passed in from the outside, but customer called ConversationsClient.create() then they are\n // using an obsolete workflow and the startup sequence will never complete.\n if (options?.twilsockClient) {\n throw new Error(\n \"Obsolete usage of ConversationsClient.create() \" +\n \"factory method: if you pass twilsock from the outside then you must \" +\n \"use ConversationsClient constructor and be prepared to work with \" +\n \"uninitialized client.\"\n );\n }\n\n const client = new Client(token, options);\n await client._ensureReady;\n\n return client;\n }\n\n /**\n * Information of the logged-in user. Before client initialization, returns an\n * uninitialized user. Will trigger a {@link Client.userUpdated} event after\n * initialization.\n */\n public get user(): User {\n return this._myself;\n }\n\n /**\n * Client reachability state. Throws if accessed before the client\n * initialization was completed.\n */\n public get reachabilityEnabled(): boolean {\n if (!this.configuration) {\n throw new Error(\n \"Reachability information could not yet be accessed as the client \" +\n \"has not yet been initialized. Subscribe to the 'stateChanged' event \" +\n \"to properly react to the client initialization.\"\n );\n }\n\n return this.configuration.reachabilityEnabled;\n }\n\n public get token(): string {\n return this.fpaToken;\n }\n\n private _subscribeToPushNotifications(channelType: NotificationsChannelType) {\n [\n NotificationTypes.NEW_MESSAGE,\n NotificationTypes.ADDED_TO_CONVERSATION,\n NotificationTypes.REMOVED_FROM_CONVERSATION,\n NotificationTypes.TYPING_INDICATOR,\n NotificationTypes.CONSUMPTION_UPDATE,\n ].forEach((messageType) => {\n this.services.notificationClient.subscribe(channelType, messageType);\n });\n }\n\n private _unsubscribeFromPushNotifications(\n channelType: NotificationsChannelType\n ) {\n [\n NotificationTypes.NEW_MESSAGE,\n NotificationTypes.ADDED_TO_CONVERSATION,\n NotificationTypes.REMOVED_FROM_CONVERSATION,\n NotificationTypes.TYPING_INDICATOR,\n NotificationTypes.CONSUMPTION_UPDATE,\n ].forEach((messageType) => {\n this.services.notificationClient.unsubscribe(channelType, messageType);\n });\n }\n\n private async _initialize() {\n const configurationResponse =\n await this.services.commandExecutor.fetchResource<\n void,\n ConfigurationResponse\n >(\"Client/v2/Configuration\");\n\n this.configuration = new Configuration(\n this.options as ClientOptions,\n configurationResponse,\n log\n );\n\n this._myself._resolveInitialization(\n this.configuration,\n this.configuration.userIdentity,\n this.configuration.userInfo,\n true\n );\n\n this.services.typingIndicator = new TypingIndicator(\n this.getConversationBySid.bind(this),\n this.configuration,\n this.services\n );\n this.services.network = new Network(this.configuration, this.services);\n\n this.services.users = new Users(\n this._myself,\n this.configuration,\n this.services\n );\n this.services.users.on(\"userSubscribed\", (user) => {\n this.emit(\"userSubscribed\", user);\n });\n this.services.users.on(\"userUpdated\", (args: UserUpdatedEventArgs) =>\n this.emit(\"userUpdated\", args)\n );\n this.services.users.on(\"userUnsubscribed\", (user) => {\n this.emit(\"userUnsubscribed\", user);\n });\n\n this.conversations = new ConversationsEntity(\n this.configuration,\n this.services\n );\n\n this.conversations.on(\"conversationAdded\", (conversation) => {\n this.emit(\"conversationAdded\", conversation);\n });\n this.conversations.on(\"conversationRemoved\", (conversation) => {\n this.emit(\"conversationRemoved\", conversation);\n });\n this.conversations.on(\"conversationJoined\", (conversation) => {\n this.emit(\"conversationJoined\", conversation);\n });\n this.conversations.on(\"conversationLeft\", (conversation) => {\n this.emit(\"conversationLeft\", conversation);\n });\n this.conversations.on(\n \"conversationUpdated\",\n (args: ConversationUpdatedEventArgs) =>\n this.emit(\"conversationUpdated\", args)\n );\n\n this.conversations.on(\"participantJoined\", (participant) => {\n this.emit(\"participantJoined\", participant);\n });\n this.conversations.on(\"participantLeft\", (participant) => {\n this.emit(\"participantLeft\", participant);\n });\n this.conversations.on(\n \"participantUpdated\",\n (args: ParticipantUpdatedEventArgs) =>\n this.emit(\"participantUpdated\", args)\n );\n\n this.conversations.on(\"messageAdded\", (message) =>\n this.emit(\"messageAdded\", message)\n );\n this.conversations.on(\"messageUpdated\", (args: MessageUpdatedEventArgs) =>\n this.emit(\"messageUpdated\", args)\n );\n this.conversations.on(\"messageRemoved\", (message) =>\n this.emit(\"messageRemoved\", message)\n );\n\n this.conversations.on(\"typingStarted\", (participant) =>\n this.emit(\"typingStarted\", participant)\n );\n this.conversations.on(\"typingEnded\", (participant) =>\n this.emit(\"typingEnded\", participant)\n );\n\n this.conversationsPromise = this.conversations\n .fetchConversations()\n .then(() => this.conversations)\n .catch((error) => {\n throw error;\n });\n\n await this.services.users.myself._ensureFetched();\n\n Client.supportedPushChannels.forEach((channelType) =>\n this._subscribeToPushNotifications(channelType)\n );\n this.services.typingIndicator.initialize();\n\n this.services.mcsClient = new McsClient(\n this.fpaToken,\n this.configuration.links.mediaService,\n this.configuration.links.mediaSetService,\n {\n ...this.options,\n transport: undefined,\n }\n );\n\n this._resolveEnsureReady();\n this.emit(\"stateChanged\", \"initialized\");\n }\n\n /**\n * Gracefully shut down the client.\n */\n async shutdown(): Promise<void> {\n await this._ensureReady;\n await this.services.twilsockClient.disconnect();\n }\n\n /**\n * Update the token used by the client and re-register with the Conversations services.\n * @param token New access token.\n */\n @validateTypesAsync(nonEmptyString)\n async updateToken(token: string): Promise<Client> {\n await this._ensureReady;\n log.info(\"updateToken\");\n\n if (this.fpaToken === token) {\n return this;\n }\n\n await this.services.twilsockClient.updateToken(token);\n await this.services.notificationClient.updateToken(token);\n await this.services.mcsClient.updateToken(token);\n this.fpaToken = token;\n\n return this;\n }\n\n /**\n * Get a known conversation by its SID.\n * @param conversationSid Conversation sid\n */\n @validateTypesAsync(nonEmptyString)\n async getConversationBySid(conversationSid: string): Promise<Conversation> {\n await this._ensureReady;\n await this.conversations.myConversationsRead.promise;\n let conversation = await this.conversations.getConversation(\n conversationSid\n );\n\n if (!conversation) {\n conversation = await this.conversations.peekConversation(conversationSid);\n }\n\n if (!conversation) {\n throw new Error(`Conversation with SID ${conversationSid} is not found.`);\n }\n\n return conversation;\n }\n\n /**\n * Get a known conversation by its unique identifier name.\n * @param uniqueName The unique identifier name of the conversation.\n */\n @validateTypesAsync(nonEmptyString)\n async getConversationByUniqueName(uniqueName: string): Promise<Conversation> {\n await this._ensureReady;\n await this.conversations.myConversationsRead.promise;\n const conversation = await this.conversations.getConversationByUniqueName(\n uniqueName\n );\n\n if (!conversation) {\n throw new Error(\n `Conversation with unique name ${uniqueName} is not found.`\n );\n }\n\n return conversation;\n }\n\n /**\n * Get the current list of all the subscribed conversations.\n */\n public async getSubscribedConversations(): Promise<Paginator<Conversation>> {\n await this._ensureReady;\n return this.conversationsPromise.then((conversations) =>\n conversations.getConversations()\n );\n }\n\n /**\n * Create a conversation on the server and subscribe to its events.\n * The default is a conversation with an empty friendly name.\n * @param options Options for the conversation.\n */\n @validateTypesAsync([\n \"undefined\",\n objectSchema(\"conversation options\", {\n friendlyName: [\"string\", \"undefined\"],\n isPrivate: [\"boolean\", \"undefined\"],\n uniqueName: [\"string\", \"undefined\"],\n }),\n ])\n public async createConversation(\n options?: CreateConversationOptions\n ): Promise<Conversation> {\n await this._ensureReady;\n options = options || {};\n return this.conversationsPromise.then((conversationsEntity) =>\n conversationsEntity.addConversation(options)\n );\n }\n\n /**\n * Register for push notifications.\n * @param channelType Channel type.\n * @param registrationId Push notification ID provided by the FCM/APNS service on the platform.\n */\n @validateTypesAsync(literal(\"fcm\", \"apn\"), \"string\")\n public async setPushRegistrationId(\n channelType: NotificationsChannelType,\n registrationId: string\n ): Promise<void> {\n await this._ensureReady;\n this._subscribeToPushNotifications(channelType);\n this.services.notificationClient.setPushRegistrationId(\n channelType,\n registrationId\n );\n await this.services.notificationClient.commitChanges(); // Committing before this point is useless because we have no push id\n }\n\n /**\n * Unregister from push notifications.\n * @param channelType Channel type.\n * @deprecated Use removePushRegistrations() instead.\n */\n @validateTypesAsync(literal(\"fcm\", \"apn\"))\n public async unsetPushRegistrationId(\n channelType: NotificationsChannelType\n ): Promise<void> {\n await this._ensureReady;\n this._unsubscribeFromPushNotifications(channelType);\n await this.services.notificationClient.commitChanges();\n }\n\n /**\n * Clear existing registrations directly using provided device token.\n * This is useful to ensure stopped subscriptions without resubscribing.\n *\n * This function goes completely beside the state machine and removes all registrations.\n * Use with caution: if it races with current state machine operations, madness will ensue.\n *\n * @param channelType Channel type.\n * @param registrationId Push notification ID provided by the FCM/APNS service on the platform.\n */\n @validateTypesAsync(literal(\"fcm\", \"apn\"), nonEmptyString)\n public async removePushRegistrations(\n channelType: ChannelType,\n registrationId: string\n ): Promise<void> {\n // do not await this._ensureReady() here - it could be called at any moment\n await this.services.notificationClient.removeRegistrations(\n channelType,\n registrationId\n );\n }\n\n private static parsePushNotificationChatData(\n data: Record<string, unknown>\n ): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const key in Client.supportedPushDataFields) {\n if (typeof data[key] === \"undefined\" || data[key] === null) {\n continue;\n }\n\n if (key !== \"message_index\") {\n result[Client.supportedPushDataFields[key]] = data[key];\n continue;\n }\n\n if (parseToNumber(data[key]) !== null) {\n result[Client.supportedPushDataFields[key]] = Number(data[key]);\n }\n }\n\n return result;\n }\n\n /**\n * Static method for push notification payload parsing. Returns parsed push as a {@link PushNotification} object.\n * @param notificationPayload Push notification payload.\n */\n @validateTypes(pureObject)\n static parsePushNotification(notificationPayload): PushNotification {\n log.debug(\n \"parsePushNotification, notificationPayload=\",\n notificationPayload\n );\n\n // APNS specifics\n if (typeof notificationPayload.aps !== \"undefined\") {\n if (!notificationPayload.twi_message_type) {\n throw new Error(\n \"Provided push notification payload does not contain Programmable Chat push notification type\"\n );\n }\n\n const data = Client.parsePushNotificationChatData(notificationPayload);\n\n const apsPayload = notificationPayload.aps;\n let body: string | null;\n let title: string | null = null;\n if (typeof apsPayload.alert === \"string\") {\n body = apsPayload.alert || null;\n } else {\n body = apsPayload.alert.body || null;\n title = apsPayload.alert.title || null;\n }\n\n return new PushNotification({\n title,\n body,\n sound: apsPayload.sound || null,\n badge: apsPayload.badge || null,\n action: apsPayload.category || null,\n type: notificationPayload.twi_message_type,\n data: data,\n });\n }\n\n // FCM specifics\n if (typeof notificationPayload.data !== \"undefined\") {\n const dataPayload = notificationPayload.data;\n if (!dataPayload.twi_message_type) {\n throw new Error(\n \"Provided push notification payload does not contain Programmable Chat push notification type\"\n );\n }\n\n const data = Client.parsePushNotificationChatData(\n notificationPayload.data\n );\n return new PushNotification({\n title: dataPayload.twi_title || null,\n body: dataPayload.twi_body || null,\n sound: dataPayload.twi_sound || null,\n badge: null,\n action: dataPayload.twi_action || null,\n type: dataPayload.twi_message_type,\n data: data,\n });\n }\n\n throw new Error(\n \"Provided push notification payload is not Programmable Chat notification\"\n );\n }\n\n public parsePushNotification = Client.parsePushNotification;\n\n /**\n * Handle push notification payload parsing and emit the {@link Client.pushNotification} event on this {@link Client} instance.\n * @param notificationPayload Push notification payload\n */\n @validateTypesAsync(pureObject)\n async handlePushNotification(notificationPayload): Promise<void> {\n await this._ensureReady;\n log.debug(\n \"handlePushNotification, notificationPayload=\",\n notificationPayload\n );\n this.emit(\n \"pushNotification\",\n Client.parsePushNotification(notificationPayload)\n );\n }\n\n /**\n * Gets a user with the given identity. If it's in the subscribed list, then return the user object from it;\n * if not, then subscribe and add user to the subscribed list.\n * @param identity Identity of the user.\n * @returns A fully initialized user.\n */\n @validateTypesAsync(nonEmptyString)\n public async getUser(identity: string): Promise<User> {\n await this._ensureReady;\n return this.services.users.getUser(identity);\n }\n\n /**\n * Get a list of subscribed user objects.\n */\n public async getSubscribedUsers(): Promise<Array<User>> {\n await this._ensureReady;\n return this.services.users.getSubscribedUsers();\n }\n}\n\nexport {\n Client,\n State,\n ConnectionState,\n NotificationsChannelType,\n LogLevel,\n ClientOptions,\n CreateConversationOptions,\n};\n"],"names":["__decorate","decorators","target","key","desc","c","arguments","length","r","Object","getOwnPropertyDescriptor","d","Reflect","decorate","i","defineProperty","__metadata","metadataKey","metadataValue","metadata","log","loglevelLog","toSeconds","parseDuration","parseTime","custom","isEqual","ReplayEventEmitter","validateTypesAsync","Retrier","McsMedia","validateTypes","nonEmptyString","nonNegativeInteger","literal","objectSchema","AsyncRetrier","uuidv4","Client","InitRegistration","TwilsockClient","NotificationClient","SyncClient","TelemetryEventDescription","TelemetryPoint","ConversationsEntity","McsClient","pureObject","validateConstructorTypes"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDO,SAASA,UAAT,CAAoBC,UAApB,EAAgCC,MAAhC,EAAwCC,GAAxC,EAA6CC,IAA7C,EAAmD;AACtD,MAAIC,CAAC,GAAGC,SAAS,CAACC,MAAlB;AAAA,MAA0BC,CAAC,GAAGH,CAAC,GAAG,CAAJ,GAAQH,MAAR,GAAiBE,IAAI,KAAK,IAAT,GAAgBA,IAAI,GAAGK,MAAM,CAACC,wBAAP,CAAgCR,MAAhC,EAAwCC,GAAxC,CAAvB,GAAsEC,IAArH;AAAA,MAA2HO,CAA3H;AACA,MAAI,QAAOC,OAAP,6DAAOA,OAAP,OAAmB,QAAnB,IAA+B,OAA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CAAA,0BAAA,0BAAA,EAUC,IAVD,CAAA;;AAmBA,UAAA,CAAA,CADCnB,2CAAkB,CAACI,uCAAD,CACnB,qCAAA,2CAAA,0CAAA,CAAA,0BAAA,WAAA,EAGC,IAHD,CAAA;;AAjeA,UAAA,CAAA,CADCJ,2CAAkB,CAAC,QAAD,EAAW,CAAC,WAAD,EAAcmB,mCAAd,CAAX,CACnB,qCAAA,mDAAA,0CAAA,CAAA,gBAAA,UAAA,EAsBC,IAtBD,CAAA;;AAsYA,UAAA,CAAA,CADChB,sCAAa,CAACgB,mCAAD,CACd,qCAAA,2CAAA,kCAAmD,iBAAnD,CAAA,gBAAA,yBAAA,EA+DC,IA/DD,CAAA;;AAp0BIT,cAAM,GAAA,QAAA,GAAA,UAAA,CAAA,CADXU,iDAAwB,CAAChB,uCAAD,EAAiB,CAACe,mCAAD,EAAa,WAAb,CAAjB,CACb,mDAAA,CAAA,EAANT,cAAM,CAAN;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"lib.js","sources":["../../../node_modules/tslib/tslib.es6.js","../src/logger.ts","../src/configuration.ts","../src/util/index.ts","../src/interfaces/attributes.ts","../src/user.ts","../src/services/network.ts","../src/interfaces/notification-types.ts","../src/participant.ts","../src/data/participants.ts","../src/media.ts","../src/aggregated-delivery-receipt.ts","../src/rest-paginator.ts","../src/detailed-delivery-receipt.ts","../src/message.ts","../src/data/messages.ts","../src/unsent-message.ts","../src/message-builder.ts","../src/conversation.ts","../src/util/deferred.ts","../src/data/conversations.ts","../src/data/users.ts","../src/services/typing-indicator.ts","../src/push-notification.ts","../src/command-executor.ts","../src/client.ts"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","import * as loglevelLog from \"loglevel\";\nimport { LogLevelDesc } from \"loglevel\";\n\nfunction prepareLine(prefix, args) {\n return [`${new Date().toISOString()} Conversations ${prefix}:`].concat(\n Array.from(args)\n );\n}\n\nconst log: loglevelLog.Logger = loglevelLog.getLogger(\"twilio-conversations\"); // twilio-conversations is used by Flex SDK. Please DO NOT change\n\nclass Logger {\n private prefix = \"\";\n\n private constructor(prefix: string) {\n this.prefix =\n prefix !== null && prefix !== undefined && prefix.length > 0\n ? prefix + \" \"\n : \"\";\n }\n\n static scope(prefix: string): Logger {\n return new Logger(prefix);\n }\n\n setLevel(level: LogLevelDesc) {\n log.setLevel(level);\n }\n\n static setLevel(level: LogLevelDesc) {\n log.setLevel(level);\n }\n\n trace(...args) {\n log.trace.apply(null, prepareLine(this.prefix + \"T\", args));\n }\n\n debug(...args) {\n log.debug.apply(null, prepareLine(this.prefix + \"D\", args));\n }\n\n info(...args) {\n log.info.apply(null, prepareLine(this.prefix + \"I\", args));\n }\n\n warn(...args) {\n log.warn.apply(null, prepareLine(this.prefix + \"W\", args));\n }\n\n error(...args) {\n log.error.apply(null, prepareLine(this.prefix + \"E\", args));\n }\n\n static trace(...args) {\n log.trace.apply(null, prepareLine(\"T\", args));\n }\n\n static debug(...args) {\n log.debug.apply(null, prepareLine(\"D\", args));\n }\n\n static info(...args) {\n log.info.apply(null, prepareLine(\"I\", args));\n }\n\n static warn(...args) {\n log.warn.apply(null, prepareLine(\"W\", args));\n }\n\n static error(...args) {\n log.error.apply(null, prepareLine(\"E\", args));\n }\n}\n\nexport { Logger };\n","import { ConfigurationResponse } from \"./interfaces/commands/configuration\";\nimport { parse as parseDuration, toSeconds } from \"iso8601-duration\";\nimport { Logger } from \"./logger\";\nimport { ConversationLimits } from \"./interfaces/conversation-limits\";\nimport { ClientOptions } from \"./client\";\n\nconst TYPING_TIMEOUT = 5;\nconst HTTP_CACHE_LIFETIME = \"PT5S\";\nconst CONSUMPTION_HORIZON_SENDING_INTERVAL = \"PT5S\";\nconst USER_INFOS_TO_SUBSCRIBE = 100;\n\nconst MINIMUM_RETRY_DELAY = 1000;\nconst MAXIMUM_RETRY_DELAY = 4000;\nconst MAXIMUM_ATTEMPTS_COUNT = 3;\nconst RETRY_WHEN_THROTTLED = true;\n\ninterface BackoffConfiguration {\n min: number;\n max: number;\n maxAttemptsCount: number;\n}\n\nclass Configuration {\n public readonly links: {\n myConversations: string;\n conversations: string;\n users: string;\n currentUser: string;\n typing: string;\n mediaService: string;\n mediaSetService: string;\n messagesReceipts: string;\n };\n\n public readonly limits: ConversationLimits;\n\n public readonly productId?: string;\n\n public readonly typingIndicatorTimeoutOverride?: number;\n public readonly typingIndicatorTimeoutDefault: number = TYPING_TIMEOUT * 1000;\n public readonly backoffConfiguration: BackoffConfiguration;\n public readonly retryWhenThrottled: boolean;\n\n public readonly consumptionReportInterval: number;\n public readonly userInfosToSubscribe: number;\n public readonly httpCacheInterval: number;\n public readonly reachabilityEnabled: boolean;\n\n public readonly userIdentity: string;\n public readonly userInfo: string;\n public readonly myConversations: string;\n\n constructor(\n options: ClientOptions = {},\n configurationResponse: ConfigurationResponse,\n logger: Logger\n ) {\n const constructorOptions =\n options.Chat || options.IPMessaging || options || {};\n\n this.productId = constructorOptions.productId;\n\n this.links = {\n myConversations: configurationResponse.links.my_conversations,\n conversations: configurationResponse.links.conversations,\n users: configurationResponse.links.users,\n currentUser: configurationResponse.links.current_user,\n typing: configurationResponse.links.typing,\n mediaService: configurationResponse.links.media_service,\n mediaSetService: configurationResponse.links.media_set_service,\n messagesReceipts: configurationResponse.links.messages_receipts,\n };\n\n this.limits = {\n mediaAttachmentsCountLimit:\n configurationResponse.options.media_attachments_count_limit,\n mediaAttachmentSizeLimitInMb:\n configurationResponse.options.media_attachment_size_limit_in_mb,\n mediaAttachmentsTotalSizeLimitInMb:\n configurationResponse.options.media_attachments_total_size_limit_in_mb,\n emailHistoriesAllowedContentTypes:\n configurationResponse.options.email_histories_allowed_mime_types,\n emailBodiesAllowedContentTypes:\n configurationResponse.options.email_bodies_allowed_mime_types,\n };\n\n this.typingIndicatorTimeoutOverride =\n constructorOptions.typingIndicatorTimeoutOverride;\n this.backoffConfiguration = {\n min: MINIMUM_RETRY_DELAY,\n max: MAXIMUM_RETRY_DELAY,\n maxAttemptsCount: MAXIMUM_ATTEMPTS_COUNT,\n ...constructorOptions.backoffConfigOverride,\n };\n this.retryWhenThrottled =\n constructorOptions.retryWhenThrottledOverride !== undefined\n ? constructorOptions.retryWhenThrottledOverride\n : RETRY_WHEN_THROTTLED;\n this.userInfosToSubscribe =\n constructorOptions.userInfosToSubscribeOverride ??\n configurationResponse.options.user_infos_to_subscribe ??\n USER_INFOS_TO_SUBSCRIBE;\n this.reachabilityEnabled =\n configurationResponse.options.reachability_enabled;\n this.userIdentity = configurationResponse.identity;\n this.userInfo = configurationResponse.sync_objects.my_user_info;\n this.myConversations = configurationResponse.sync_objects.my_conversations;\n\n const httpCacheInterval =\n constructorOptions.httpCacheIntervalOverride ??\n configurationResponse.options.http_cache_interval ??\n HTTP_CACHE_LIFETIME;\n\n try {\n this.httpCacheInterval = toSeconds(parseDuration(httpCacheInterval));\n } catch {\n logger.error(\n `Failed to parse http cache interval ${httpCacheInterval}, using default value ${HTTP_CACHE_LIFETIME}`\n );\n this.httpCacheInterval = toSeconds(parseDuration(HTTP_CACHE_LIFETIME));\n }\n\n const consumptionReportInterval =\n constructorOptions.consumptionReportIntervalOverride ??\n configurationResponse.options.consumption_report_interval ??\n CONSUMPTION_HORIZON_SENDING_INTERVAL;\n\n try {\n this.consumptionReportInterval = toSeconds(\n parseDuration(consumptionReportInterval)\n );\n } catch {\n logger.error(\n `Failed to parse consumption report interval ${consumptionReportInterval}, using default value ${CONSUMPTION_HORIZON_SENDING_INTERVAL}`\n );\n this.consumptionReportInterval = toSeconds(\n parseDuration(CONSUMPTION_HORIZON_SENDING_INTERVAL)\n );\n }\n }\n}\n\nexport { Configuration };\n","import { Logger } from \"../logger\";\nimport { JSONValue } from \"../types\";\n\n/**\n * Deep-clone an object. Note that this does not work on object containing\n * functions.\n * @param {object} obj - the object to deep-clone\n * @returns {object}\n */\nfunction deepClone<T>(obj: T): T {\n return JSON.parse(JSON.stringify(obj)) as T;\n}\n\nfunction parseToNumber(value) {\n if (typeof value !== \"undefined\" && !isNaN(Number(value))) {\n return Number(value);\n }\n return null;\n}\n\n// timeString cannot be typed `string` because in member.ts\n// call to parseTime(data.lastReadTimestamp) uses number not a string for timestamp.\nfunction parseTime(timeString): Date | null {\n try {\n return new Date(timeString);\n } catch (e) {\n return null;\n }\n}\n\nfunction parseAttributes(\n rawAttributes,\n warningMessage: string,\n log: Logger\n): JSONValue {\n let attributes = {};\n if (rawAttributes) {\n try {\n attributes = JSON.parse(rawAttributes);\n } catch (e) {\n log.warn(warningMessage, e);\n }\n }\n\n return attributes;\n}\n\n/**\n * Construct URI with query parameters\n */\nclass UriBuilder {\n private base: string;\n private args: string[];\n private paths: string[];\n\n constructor(base: string) {\n this.base = base.replace(/\\/$/, \"\");\n this.args = [];\n this.paths = [];\n }\n\n public arg(name: string, value: string | number | boolean): UriBuilder {\n if (typeof value !== \"undefined\") {\n this.args.push(\n encodeURIComponent(name) + \"=\" + encodeURIComponent(value)\n );\n }\n return this;\n }\n\n public path(name: string): UriBuilder {\n this.paths.push(encodeURIComponent(name));\n return this;\n }\n\n public build(): string {\n let result = this.base;\n if (this.paths.length) {\n result += \"/\" + this.paths.join(\"/\");\n }\n\n if (this.args.length) {\n result += \"?\" + this.args.join(\"&\");\n }\n return result;\n }\n}\n\nexport { deepClone, UriBuilder, parseToNumber, parseTime, parseAttributes };\n","import { custom } from \"@twilio/declarative-type-validator\";\n\n// Any JSON value\nexport const attributesValidator = custom((value) => [\n [\"string\", \"number\", \"boolean\", \"object\"].includes(typeof value),\n \"a JSON type\",\n]);\n\nexport const optionalAttributesValidator = custom((value) => [\n [\"undefined\", \"string\", \"number\", \"boolean\", \"object\"].includes(typeof value),\n \"an optional JSON type\",\n]);\n","import { Logger } from \"./logger\";\nimport { SyncClient } from \"twilio-sync\";\nimport { parseAttributes } from \"./util\";\nimport { validateTypesAsync } from \"@twilio/declarative-type-validator\";\nimport { attributesValidator } from \"./interfaces/attributes\";\nimport { Configuration } from \"./configuration\";\nimport { CommandExecutor } from \"./command-executor\";\nimport {\n EditUserRequest,\n EditUserResponse,\n} from \"./interfaces/commands/edit-user\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport isEqual from \"lodash.isequal\";\nimport { JSONValue } from \"./types\";\n\ntype UserEvents = {\n updated: (data: { user: User; updateReasons: UserUpdateReason[] }) => void;\n userSubscribed: (user: User) => void;\n userUnsubscribed: (user: User) => void;\n};\n\nconst log = Logger.scope(\"User\");\n\ninterface UserState {\n identity: string;\n entityName: string;\n friendlyName: string | null;\n attributes: JSONValue;\n online: boolean | null;\n notifiable: boolean | null;\n}\n\ninterface UpdateValue {\n value: string;\n notifiable: boolean | null;\n online: boolean | null;\n}\n\ninterface UserServices {\n syncClient: SyncClient;\n commandExecutor: CommandExecutor;\n}\n\ninterface UserLinks {\n self: string;\n}\n\ntype SubscriptionState = \"initializing\" | \"subscribed\" | \"unsubscribed\";\n\n/**\n * The reason for the `updated` event being emitted by a user.\n */\ntype UserUpdateReason =\n | \"friendlyName\"\n | \"attributes\"\n | \"reachabilityOnline\"\n | \"reachabilityNotifiable\";\n\ninterface UserUpdatedEventArgs {\n user: User;\n updateReasons: UserUpdateReason[];\n}\n\n/**\n * Extended user information.\n * Note that `isOnline` and `isNotifiable` properties are eligible\n * for use only if the reachability function is enabled.\n * You may check if it is enabled by reading the value of {@link Client.reachabilityEnabled}.\n */\nclass User extends ReplayEventEmitter<UserEvents> {\n private links!: UserLinks;\n private configuration!: Configuration;\n private readonly services: UserServices;\n\n private entity;\n private state: UserState;\n private promiseToFetch: Promise<User> | null = null;\n private subscribed: SubscriptionState;\n\n private _initializationPromise: Promise<void>;\n private _resolveInitializationPromise;\n\n /**\n * @internal\n */\n constructor(\n identity: string,\n entityName: string,\n configuration: Configuration | null,\n services: UserServices\n ) {\n super();\n\n this.services = services;\n\n this.subscribed = \"initializing\";\n this.setMaxListeners(0);\n\n this.state = {\n identity,\n entityName,\n friendlyName: null,\n attributes: {},\n online: null,\n notifiable: null,\n };\n\n this._initializationPromise = new Promise((resolve) => {\n this._resolveInitializationPromise = resolve;\n });\n\n if (configuration !== null) {\n this._resolveInitialization(configuration, identity, entityName, false);\n }\n }\n\n /**\n * Fired when the properties or the reachability status of the message has been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the following properties:\n * * {@link User} `user` - the user in question\n * * {@link UserUpdateReason}[] `updateReasons` - array of reasons for the update\n * @event\n */\n public readonly updated = \"updated\";\n\n /**\n * Fired when the client has subscribed to the user.\n *\n * Parameters:\n * 1. {@link User} `user` - the user in question\n * @event\n */\n public readonly userSubscribed = \"userSubscribed\";\n\n /**\n * Fired when the client has unsubscribed from the user.\n *\n * Parameters:\n * 1. {@link User} `user` - the user in question\n * @event\n */\n public readonly userUnsubscribed = \"userUnsubscribed\";\n\n /**\n * User identity.\n */\n public get identity(): string {\n return this.state.identity;\n }\n\n public set identity(identity: string) {\n this.state.identity = identity;\n }\n\n public set entityName(name: string) {\n this.state.entityName = name;\n }\n\n /**\n * Custom attributes of the user.\n */\n public get attributes() {\n return this.state.attributes;\n }\n\n /**\n * Friendly name of the user, null if not set.\n */\n public get friendlyName(): string | null {\n return this.state.friendlyName;\n }\n\n /**\n * Status of the real-time conversation connection of the user.\n */\n public get isOnline(): boolean | null {\n return this.state.online;\n }\n\n /**\n * User push notification registration status.\n */\n public get isNotifiable(): boolean | null {\n return this.state.notifiable;\n }\n\n /**\n * True if this user is receiving real-time status updates.\n */\n public get isSubscribed(): boolean {\n return this.subscribed == \"subscribed\";\n }\n\n // Handles service updates\n async _update(\n key: string,\n value: { value: string; notifiable: boolean | null; online: boolean | null }\n ) {\n await this._initializationPromise;\n\n const updateReasons: UserUpdateReason[] = [];\n log.debug(\"User for\", this.state.identity, \"updated:\", key, value);\n switch (key) {\n case \"friendlyName\":\n if (this.state.friendlyName !== value.value) {\n updateReasons.push(\"friendlyName\");\n this.state.friendlyName = value.value;\n }\n break;\n case \"attributes\":\n const updateAttributes = parseAttributes(\n value.value,\n `Retrieved malformed attributes from the server for user: ${this.state.identity}`,\n log\n );\n if (!isEqual(this.state.attributes, updateAttributes)) {\n this.state.attributes = updateAttributes;\n updateReasons.push(\"attributes\");\n }\n break;\n case \"reachability\":\n if (this.state.online !== value.online) {\n this.state.online = value.online;\n updateReasons.push(\"reachabilityOnline\");\n }\n if (this.state.notifiable !== value.notifiable) {\n this.state.notifiable = value.notifiable;\n updateReasons.push(\"reachabilityNotifiable\");\n }\n break;\n default:\n return;\n }\n if (updateReasons.length > 0) {\n this.emit(\"updated\", { user: this, updateReasons: updateReasons });\n }\n }\n\n // Fetch reachability info\n private async _updateReachabilityInfo(map, update) {\n await this._initializationPromise;\n\n if (!this.configuration.reachabilityEnabled) {\n return Promise.resolve();\n }\n\n return map\n .get(\"reachability\")\n .then(update)\n .catch((err) => {\n log.warn(\n \"Failed to get reachability info for \",\n this.state.identity,\n err\n );\n });\n }\n\n // Fetch user\n async _fetch(): Promise<User> {\n await this._initializationPromise;\n\n if (!this.state.entityName) {\n return this;\n }\n\n this.promiseToFetch = this.services.syncClient\n .map({\n id: this.state.entityName,\n mode: \"open_existing\",\n includeItems: true,\n })\n .then((map) => {\n this.entity = map;\n map.on(\"itemUpdated\", (args) => {\n log.debug(\n this.state.entityName +\n \" (\" +\n this.state.identity +\n \") itemUpdated: \" +\n args.item.key\n );\n return this._update(args.item.key, args.item.data);\n });\n return Promise.all([\n map\n .get(\"friendlyName\")\n .then((item) => this._update(item.key, item.data as UpdateValue)),\n map\n .get(\"attributes\")\n .then((item) => this._update(item.key, item.data as UpdateValue)),\n this._updateReachabilityInfo(map, (item) =>\n this._update(item.key, item.data)\n ),\n ]);\n })\n .then(() => {\n log.debug(\"Fetched for\", this.identity);\n this.subscribed = \"subscribed\";\n this.emit(\"userSubscribed\", this);\n return this;\n })\n .catch((err) => {\n this.promiseToFetch = null;\n throw err;\n });\n return this.promiseToFetch;\n }\n\n async _ensureFetched() {\n await this._initializationPromise;\n return this.promiseToFetch || this._fetch();\n }\n\n /**\n * Edit user attributes.\n * @param attributes New attributes.\n */\n @validateTypesAsync(attributesValidator)\n public async updateAttributes(attributes: JSONValue): Promise<User> {\n await this._initializationPromise;\n\n if (this.subscribed == \"unsubscribed\") {\n throw new Error(\"Can't modify unsubscribed object\");\n }\n\n await this.services.commandExecutor.mutateResource<\n EditUserRequest,\n EditUserResponse\n >(\"post\", this.links.self, {\n attributes: JSON.stringify(attributes),\n });\n\n return this;\n }\n\n /**\n * Update the friendly name of the user.\n * @param friendlyName New friendly name.\n */\n @validateTypesAsync([\"string\"])\n public async updateFriendlyName(friendlyName: string): Promise<User> {\n await this._initializationPromise;\n\n if (this.subscribed == \"unsubscribed\") {\n throw new Error(\"Can't modify unsubscribed object\");\n }\n\n await this.services.commandExecutor.mutateResource<\n EditUserRequest,\n EditUserResponse\n >(\"post\", this.links.self, {\n friendly_name: friendlyName,\n });\n\n return this;\n }\n\n /**\n * Remove the user from the subscription list.\n * @return A promise of completion.\n */\n async unsubscribe(): Promise<void> {\n await this._initializationPromise;\n\n if (this.promiseToFetch) {\n await this.promiseToFetch;\n this.entity.close();\n this.promiseToFetch = null;\n this.subscribed = \"unsubscribed\";\n this.emit(\"userUnsubscribed\", this);\n }\n }\n\n public _resolveInitialization(\n configuration: Configuration,\n identity: string,\n entityName: string,\n emitUpdated: boolean\n ): void {\n this.configuration = configuration;\n this.identity = identity;\n this.entityName = entityName;\n this.links = {\n self: `${this.configuration.links.users}/${this.identity}`,\n };\n this._resolveInitializationPromise();\n\n if (emitUpdated) {\n this.emit(\"updated\", {\n user: this,\n updateReasons: [\n \"friendlyName\",\n \"attributes\",\n \"reachabilityOnline\",\n \"reachabilityNotifiable\",\n ],\n });\n }\n }\n}\n\nexport {\n User,\n UserServices,\n SubscriptionState,\n UserUpdateReason,\n UserUpdatedEventArgs,\n};\n","import { Retrier } from \"@twilio/operation-retrier\";\nimport { Transport, TransportResult } from \"twilsock\";\nimport { Configuration } from \"../configuration\";\n\nimport Timeout = NodeJS.Timeout;\n\ninterface CacheEntry {\n response: TransportResult<unknown>;\n timestamp: number;\n}\n\nexport interface NetworkServices {\n transport: Transport;\n}\n\nclass Network {\n private readonly configuration: Configuration;\n private readonly services: NetworkServices;\n private cacheLifetime: number;\n\n private readonly cache: Map<string, CacheEntry>;\n private timer!: number | NodeJS.Timeout;\n\n constructor(configuration, services) {\n this.configuration = configuration;\n this.services = services;\n this.cache = new Map<string, CacheEntry>();\n this.cacheLifetime = this.configuration.httpCacheInterval * 100;\n this.cleanupCache();\n }\n\n private isExpired(timestamp: number): boolean {\n return !this.cacheLifetime || Date.now() - timestamp > this.cacheLifetime;\n }\n\n private cleanupCache() {\n for (const [k, v] of this.cache) {\n if (this.isExpired(v.timestamp)) {\n this.cache.delete(k);\n }\n }\n\n if (this.cache.size === 0) {\n clearInterval(this.timer as Timeout);\n }\n }\n\n pokeTimer() {\n this.timer =\n this.timer ||\n setInterval(() => this.cleanupCache(), this.cacheLifetime * 2);\n }\n\n private executeWithRetry<T>(\n request,\n retryWhenThrottled = false\n ): Promise<TransportResult<T>> {\n return new Promise((resolve, reject) => {\n const codesToRetryOn = [502, 503, 504];\n if (retryWhenThrottled) {\n codesToRetryOn.push(429);\n }\n\n const retrier = new Retrier(this.configuration.backoffConfiguration);\n retrier.on(\"attempt\", () => {\n request()\n .then((result) => retrier.succeeded(result))\n .catch((err) => {\n if (codesToRetryOn.indexOf(err.status) > -1) {\n retrier.failed(err);\n } else if (err.message === \"Twilsock disconnected\") {\n // Ugly hack. We must make a proper exceptions for twilsock\n retrier.failed(err);\n } else {\n // Fatal error\n retrier.removeAllListeners();\n retrier.cancel();\n reject(err);\n }\n });\n });\n\n retrier.on(\"succeeded\", (result) => {\n resolve(result);\n });\n retrier.on(\"cancelled\", (err) => reject(err));\n retrier.on(\"failed\", (err) => reject(err));\n\n retrier.start();\n });\n }\n\n async get<T>(url: string): Promise<TransportResult<T>> {\n const cacheEntry = this.cache.get(url);\n if (cacheEntry && !this.isExpired(cacheEntry.timestamp)) {\n return cacheEntry.response as TransportResult<T>;\n }\n\n const headers = {};\n const response = await this.executeWithRetry<T>(\n () =>\n this.services.transport.get<T>(\n url,\n headers,\n this.configuration.productId\n ),\n this.configuration.retryWhenThrottled\n );\n this.cache.set(url, { response, timestamp: Date.now() });\n this.pokeTimer();\n return response;\n }\n}\n\nexport { Network };\n","class NotificationTypes {\n static readonly TYPING_INDICATOR = \"twilio.ipmsg.typing_indicator\";\n static readonly NEW_MESSAGE = \"twilio.conversations.new_message\";\n static readonly ADDED_TO_CONVERSATION =\n \"twilio.conversations.added_to_conversation\";\n // static readonly INVITED_TO_CHANNEL = 'twilio.channel.invited_to_channel';\n static readonly REMOVED_FROM_CONVERSATION =\n \"twilio.conversations.removed_from_conversation\";\n static readonly CONSUMPTION_UPDATE = \"twilio.channel.consumption_update\";\n}\n\nexport { NotificationTypes };\n","import { Users } from \"./data/users\";\nimport { User } from \"./user\";\nimport { parseTime, parseAttributes } from \"./util\";\nimport { Logger } from \"./logger\";\nimport { Conversation } from \"./conversation\";\nimport { attributesValidator } from \"./interfaces/attributes\";\nimport { validateTypesAsync } from \"@twilio/declarative-type-validator\";\nimport { CommandExecutor } from \"./command-executor\";\nimport { EditParticipantRequest } from \"./interfaces/commands/edit-participant\";\nimport { ParticipantResponse } from \"./interfaces/commands/participant-response\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport isEqual from \"lodash.isequal\";\nimport { JSONValue } from \"./types\";\n\ntype ParticipantEvents = {\n typingEnded: (participant: Participant) => void;\n typingStarted: (participant: Participant) => void;\n updated: (data: {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n }) => void;\n};\n\nconst log = Logger.scope(\"Participant\");\n\ninterface ParticipantDescriptor {\n attributes?: JSONValue;\n dateCreated: Date | null;\n dateUpdated: Date | null;\n identity: string;\n roleSid?: string;\n lastConsumedMessageIndex: number | null;\n lastConsumptionTimestamp: number;\n type: ParticipantType;\n userInfo: string;\n bindings?: ParticipantBindings;\n}\n\ninterface ParticipantState {\n attributes: JSONValue;\n dateCreated: Date | null;\n dateUpdated: Date | null;\n identity: string;\n isTyping: boolean;\n lastReadMessageIndex: number | null;\n lastReadTimestamp: Date | null;\n roleSid: string;\n sid: string;\n type: ParticipantType;\n typingTimeout: number | null;\n userInfo: string;\n bindings?: ParticipantBindings;\n}\n\ninterface ParticipantServices {\n users: Users;\n commandExecutor: CommandExecutor;\n}\n\ninterface ParticipantLinks {\n self: string;\n}\n\n/**\n * The reason for the `updated` event being emitted by a participant.\n */\ntype ParticipantUpdateReason =\n | \"attributes\"\n | \"dateCreated\"\n | \"dateUpdated\"\n | \"roleSid\"\n | \"lastReadMessageIndex\"\n | \"lastReadTimestamp\"\n | \"bindings\";\n\n/**\n * Type of a participant.\n */\ntype ParticipantType = \"chat\" | \"sms\" | \"whatsapp\" | \"email\";\n\ninterface ParticipantUpdatedEventArgs {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n}\n\n/**\n * Bindings for conversation participant.\n */\ninterface ParticipantBindings {\n email?: ParticipantEmailBinding;\n}\n\n/**\n * Email participation level.\n * to = to/from\n * cc = cc\n */\ntype ParticipantEmailLevel = \"to\" | \"cc\";\n\n/**\n * Bindings for email participant.\n */\ninterface ParticipantEmailBinding {\n name: string;\n address: string;\n level: ParticipantEmailLevel;\n}\n\n/**\n * A participant represents a remote client in a conversation.\n */\nclass Participant extends ReplayEventEmitter<ParticipantEvents> {\n private state: ParticipantState;\n private readonly links: ParticipantLinks;\n private readonly services: ParticipantServices;\n\n /**\n * Conversation that the remote client is a participant of.\n */\n public readonly conversation: Conversation;\n\n /**\n * The server-assigned unique identifier for the participant.\n */\n public get sid(): string {\n return this.state.sid;\n }\n\n /**\n * Custom attributes of the participant.\n */\n public get attributes(): JSONValue {\n return this.state.attributes;\n }\n\n /**\n * Date this participant was created on.\n */\n public get dateCreated(): Date | null {\n return this.state.dateCreated;\n }\n\n /**\n * Date this participant was last updated on.\n */\n public get dateUpdated(): Date | null {\n return this.state.dateUpdated;\n }\n\n /**\n * Identity of the participant.\n */\n public get identity(): string | null {\n return this.state.identity;\n }\n\n /**\n * Indicates whether the participant is currently typing.\n */\n public get isTyping(): boolean {\n return this.state.isTyping;\n }\n\n /**\n * The index of the last read message by the participant.\n * Note that retrieving messages on a client endpoint does not mean that messages are read,\n * please consider reading about the [Read Horizon feature](https://www.twilio.com/docs/api/chat/guides/consumption-horizon)\n * to find out about the proper way to mark messages as read.\n */\n public get lastReadMessageIndex(): number | null {\n return this.state.lastReadMessageIndex;\n }\n\n /**\n * Date of the most recent read horizon update.\n */\n public get lastReadTimestamp(): Date | null {\n return this.state.lastReadTimestamp;\n }\n\n public get roleSid(): string {\n return this.state.roleSid;\n }\n\n /**\n * Type of the participant.\n */\n public get type(): ParticipantType {\n return this.state.type;\n }\n\n /**\n * Get the bindings mapping for the current participant.\n * Available binding depends on the participant type.\n * You could access it as `participant.bindings.sms?.address` or\n * using the type dynamically `participant.bindings[participant.type]`\n * just be aware that the binding information has different structure for\n * each participant type.\n * See also {ParticipantEmailBinding}, the only available currently binding descriptor.\n */\n public get bindings(): ParticipantBindings {\n return this.state.bindings ?? {};\n }\n\n /**\n * @internal\n */\n constructor(\n data: ParticipantDescriptor,\n sid: string,\n conversation: Conversation,\n links: ParticipantLinks,\n services: ParticipantServices\n ) {\n super();\n\n this.conversation = conversation;\n this.links = links;\n this.services = services;\n this.state = {\n attributes: parseAttributes(\n data.attributes,\n \"Retrieved malformed attributes from the server for participant: \" +\n sid,\n log\n ),\n dateCreated: data.dateCreated ? parseTime(data.dateCreated) : null,\n dateUpdated: data.dateCreated ? parseTime(data.dateUpdated) : null,\n sid: sid,\n typingTimeout: null,\n isTyping: false,\n identity: data.identity,\n roleSid: data.roleSid ?? \"\",\n lastReadMessageIndex: Number.isInteger(data.lastConsumedMessageIndex)\n ? data.lastConsumedMessageIndex\n : null,\n lastReadTimestamp: data.lastConsumptionTimestamp\n ? parseTime(data.lastConsumptionTimestamp)\n : null,\n type: data.type || \"chat\",\n userInfo: data.userInfo,\n bindings: data.bindings ?? {},\n };\n\n if (!data.identity && !data.type) {\n throw new Error(\n \"Received invalid Participant object from server: Missing identity or type of Participant.\"\n );\n }\n }\n\n /**\n * Fired when the participant has started typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant in question\n * @event\n */\n static readonly typingStarted = \"typingStarted\";\n\n /**\n * Fired when the participant has stopped typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant in question\n * @event\n */\n static readonly typingEnded = \"typingEnded\";\n\n /**\n * Fired when the fields of the participant have been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the following properties:\n * * {@link Participant} participant - the participant in question\n * * {@link ParticipantUpdateReason}[] updateReasons - array of reasons for the update\n * @event\n */\n static readonly updated = \"updated\";\n\n /**\n * Internal method used to start or reset the typing indicator timeout (with event emitting).\n * @internal\n */\n _startTyping(timeout) {\n if (this.state.typingTimeout) {\n clearTimeout(this.state.typingTimeout);\n }\n\n this.state.isTyping = true;\n this.emit(\"typingStarted\", this);\n\n this.conversation.emit(\"typingStarted\", this);\n\n this.state.typingTimeout = Number(\n setTimeout(() => this._endTyping(), timeout)\n );\n return this;\n }\n\n /**\n * Internal method function used to stop the typing indicator timeout (with event emitting).\n * @internal\n */\n _endTyping() {\n if (!this.state.typingTimeout) {\n return;\n }\n\n this.state.isTyping = false;\n this.emit(\"typingEnded\", this);\n\n this.conversation.emit(\"typingEnded\", this);\n\n clearInterval(this.state.typingTimeout);\n this.state.typingTimeout = null;\n }\n\n /**\n * Internal method function used update local object's property roleSid with a new value.\n * @internal\n */\n _update(data) {\n const updateReasons: ParticipantUpdateReason[] = [];\n\n const updateAttributes = parseAttributes(\n data.attributes,\n \"Retrieved malformed attributes from the server for participant: \" +\n this.state.sid,\n log\n );\n\n if (data.attributes && !isEqual(this.state.attributes, updateAttributes)) {\n this.state.attributes = updateAttributes;\n updateReasons.push(\"attributes\");\n }\n\n const updatedDateUpdated = parseTime(data.dateUpdated);\n if (\n data.dateUpdated &&\n updatedDateUpdated?.getTime() !==\n (this.state.dateUpdated && this.state.dateUpdated.getTime())\n ) {\n this.state.dateUpdated = updatedDateUpdated;\n updateReasons.push(\"dateUpdated\");\n }\n\n const updatedDateCreated = parseTime(data.dateCreated);\n if (\n data.dateCreated &&\n updatedDateCreated?.getTime() !==\n (this.state.dateCreated && this.state.dateCreated.getTime())\n ) {\n this.state.dateCreated = updatedDateCreated;\n updateReasons.push(\"dateCreated\");\n }\n\n if (data.roleSid && this.state.roleSid !== data.roleSid) {\n this.state.roleSid = data.roleSid;\n updateReasons.push(\"roleSid\");\n }\n\n if (\n (Number.isInteger(data.lastConsumedMessageIndex) ||\n data.lastConsumedMessageIndex === null) &&\n this.state.lastReadMessageIndex !== data.lastConsumedMessageIndex\n ) {\n this.state.lastReadMessageIndex = data.lastConsumedMessageIndex;\n updateReasons.push(\"lastReadMessageIndex\");\n }\n\n if (data.lastConsumptionTimestamp) {\n const lastReadTimestamp = new Date(data.lastConsumptionTimestamp);\n if (\n !this.state.lastReadTimestamp ||\n this.state.lastReadTimestamp.getTime() !== lastReadTimestamp.getTime()\n ) {\n this.state.lastReadTimestamp = lastReadTimestamp;\n updateReasons.push(\"lastReadTimestamp\");\n }\n }\n\n if (data.bindings && !isEqual(this.state.bindings, data.bindings)) {\n this.state.bindings = data.bindings;\n updateReasons.push(\"bindings\");\n }\n\n if (updateReasons.length > 0) {\n this.emit(\"updated\", { participant: this, updateReasons: updateReasons });\n }\n\n return this;\n }\n\n /**\n * Get the user for this participant and subscribes to it. Supported only for participants of type `chat`.\n */\n async getUser(): Promise<User> {\n if (this.type != \"chat\") {\n throw new Error(\n \"Getting User is not supported for this Participant type: \" + this.type\n );\n }\n\n return this.services.users.getUser(\n this.state.identity,\n this.state.userInfo\n );\n }\n\n /**\n * Remove the participant from the conversation.\n */\n async remove() {\n return this.conversation.removeParticipant(this);\n }\n\n /**\n * Update the attributes of the participant.\n * @param attributes New attributes.\n */\n @validateTypesAsync(attributesValidator)\n async updateAttributes(attributes: JSONValue): Promise<Participant> {\n await this.services.commandExecutor.mutateResource<\n EditParticipantRequest,\n ParticipantResponse\n >(\"post\", this.links.self, {\n attributes: JSON.stringify(attributes),\n });\n\n return this;\n }\n}\n\nexport {\n ParticipantDescriptor,\n ParticipantServices,\n Participant,\n ParticipantUpdateReason,\n ParticipantType,\n ParticipantUpdatedEventArgs,\n ParticipantBindings,\n ParticipantEmailBinding,\n ParticipantEmailLevel,\n};\n","import {\n ParticipantDescriptor,\n Participant,\n ParticipantUpdatedEventArgs,\n ParticipantUpdateReason,\n ParticipantEmailBinding,\n} from \"../participant\";\nimport { Logger } from \"../logger\";\n\nimport { Conversation } from \"../conversation\";\n\nimport { SyncMap, SyncClient } from \"twilio-sync\";\nimport { Users } from \"./users\";\nimport { CommandExecutor } from \"../command-executor\";\nimport { AddParticipantRequest } from \"../interfaces/commands/add-participant\";\nimport { Configuration } from \"../configuration\";\nimport { ParticipantResponse } from \"../interfaces/commands/participant-response\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport { JSONValue } from \"../types\";\n\ntype ParticipantsEvents = {\n participantJoined: (participant: Participant) => void;\n participantLeft: (participant: Participant) => void;\n participantUpdated: (data: {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n }) => void;\n};\n\nconst log = Logger.scope(\"Participants\");\n\nexport interface ParticipantsServices {\n syncClient: SyncClient;\n users: Users;\n commandExecutor: CommandExecutor;\n}\n\ninterface ParticipantsLinks {\n participants: string;\n}\n\nexport interface ParticipantBindingOptions {\n email?: ParticipantEmailBinding;\n}\n\n/**\n * @classdesc Represents the collection of participants for the conversation\n * @fires Participants#participantJoined\n * @fires Participants#participantLeft\n * @fires Participants#participantUpdated\n */\nclass Participants extends ReplayEventEmitter<ParticipantsEvents> {\n private readonly configuration: Configuration;\n private readonly services: ParticipantsServices;\n private readonly links: ParticipantsLinks;\n\n rosterEntityPromise: Promise<SyncMap> | null = null;\n\n public readonly conversation: Conversation;\n public readonly participants: Map<string, Participant>;\n\n constructor(\n conversation: Conversation,\n participants: Map<string, Participant>,\n links: ParticipantsLinks,\n configuration: Configuration,\n services: ParticipantsServices\n ) {\n super();\n this.conversation = conversation;\n this.participants = participants;\n this.links = links;\n this.configuration = configuration;\n this.services = services;\n }\n\n async unsubscribe(): Promise<void> {\n if (this.rosterEntityPromise) {\n const entity = await this.rosterEntityPromise;\n entity.close();\n this.rosterEntityPromise = null;\n }\n }\n\n subscribe(rosterObjectName: string) {\n return (this.rosterEntityPromise =\n this.rosterEntityPromise ||\n this.services.syncClient\n .map({ id: rosterObjectName, mode: \"open_existing\" })\n .then((rosterMap) => {\n rosterMap.on(\"itemAdded\", (args) => {\n log.debug(this.conversation.sid + \" itemAdded: \" + args.item.key);\n this.upsertParticipant(args.item.key, args.item.data).then(\n (participant) => {\n this.emit(\"participantJoined\", participant);\n }\n );\n });\n\n rosterMap.on(\"itemRemoved\", (args) => {\n log.debug(this.conversation.sid + \" itemRemoved: \" + args.key);\n const participantSid = args.key;\n if (!this.participants.has(participantSid)) {\n return;\n }\n const leftParticipant = this.participants.get(participantSid);\n this.participants.delete(participantSid);\n if (!leftParticipant) {\n return;\n }\n this.emit(\"participantLeft\", leftParticipant);\n });\n\n rosterMap.on(\"itemUpdated\", (args) => {\n log.debug(this.conversation.sid + \" itemUpdated: \" + args.item.key);\n this.upsertParticipant(args.item.key, args.item.data);\n });\n\n const participantsPromises: Promise<Participant>[] = [];\n const rosterMapHandler = (paginator) => {\n paginator.items.forEach((item) => {\n participantsPromises.push(\n this.upsertParticipant(item.key, item.data)\n );\n });\n return paginator.hasNextPage\n ? paginator.nextPage().then(rosterMapHandler)\n : null;\n };\n\n return rosterMap\n .getItems()\n .then(rosterMapHandler)\n .then(() => Promise.all(participantsPromises))\n .then(() => rosterMap);\n })\n .catch((err) => {\n this.rosterEntityPromise = null;\n if (this.services.syncClient.connectionState != \"disconnected\") {\n log.error(\n \"Failed to get roster object for conversation\",\n this.conversation.sid,\n err\n );\n }\n log.debug(\n \"ERROR: Failed to get roster object for conversation\",\n this.conversation.sid,\n err\n );\n throw err;\n }));\n }\n\n async upsertParticipant(\n participantSid: string,\n data: ParticipantDescriptor\n ): Promise<Participant> {\n let participant = this.participants.get(participantSid);\n if (participant) {\n return participant._update(data);\n }\n\n const links = {\n self: `${this.links.participants}/${participantSid}`,\n };\n\n participant = new Participant(\n data,\n participantSid,\n this.conversation,\n links,\n this.services\n );\n this.participants.set(participantSid, participant);\n participant.on(\"updated\", (args: ParticipantUpdatedEventArgs) =>\n this.emit(\"participantUpdated\", args)\n );\n return participant;\n }\n\n /**\n * @returns {Promise<Array<Participant>>} returns list of participants {@see Participant}\n */\n async getParticipants(): Promise<Participant[]> {\n return this.rosterEntityPromise\n ? this.rosterEntityPromise.then(() => {\n const participants: Participant[] = [];\n this.participants.forEach((participant) =>\n participants.push(participant)\n );\n return participants;\n })\n : [];\n }\n\n /**\n * Get participant by SID from conversation\n * @returns {Promise<Participant>}\n */\n async getParticipantBySid(\n participantSid: string\n ): Promise<Participant | null> {\n return this.rosterEntityPromise\n ? this.rosterEntityPromise.then(() => {\n const participant = this.participants.get(participantSid);\n if (!participant) {\n throw new Error(\n \"Participant with SID \" + participantSid + \" was not found\"\n );\n }\n return participant;\n })\n : null;\n }\n\n /**\n * Get participant by identity from conversation\n * @returns {Promise<Participant>}\n */\n async getParticipantByIdentity(\n identity: string\n ): Promise<Participant | null> {\n let foundParticipant: Participant | null = null;\n return this.rosterEntityPromise\n ? this.rosterEntityPromise.then(() => {\n this.participants.forEach((participant) => {\n if (participant.identity === identity) {\n foundParticipant = participant;\n }\n });\n if (!foundParticipant) {\n throw new Error(\n \"Participant with identity \" + identity + \" was not found\"\n );\n }\n return foundParticipant;\n })\n : null;\n }\n\n /**\n * Add a chat participant to the conversation\n * @returns {Promise<ParticipantResponse>}\n */\n async add(\n identity: string,\n attributes: JSONValue\n ): Promise<ParticipantResponse> {\n return await this.services.commandExecutor.mutateResource<\n AddParticipantRequest,\n ParticipantResponse\n >(\"post\", this.links.participants, {\n identity,\n attributes:\n typeof attributes !== \"undefined\"\n ? JSON.stringify(attributes)\n : undefined,\n });\n }\n\n /**\n * Add a non-chat participant to the conversation.\n *\n * @param proxyAddress\n * @param address\n * @param attributes\n * @param bindingOptions\n * @returns {Promise<any>}\n */\n addNonChatParticipant(\n proxyAddress: string,\n address: string,\n attributes: JSONValue = {},\n bindingOptions: ParticipantBindingOptions = {}\n ): Promise<ParticipantResponse> {\n return this.services.commandExecutor.mutateResource<\n AddParticipantRequest,\n ParticipantResponse\n >(\"post\", this.links.participants, {\n attributes:\n typeof attributes !== \"undefined\"\n ? JSON.stringify(attributes)\n : undefined,\n messaging_binding: {\n address,\n proxy_address: proxyAddress,\n name: bindingOptions?.email?.name,\n level: bindingOptions?.email?.level,\n },\n });\n }\n\n /**\n * Remove the participant with a given identity from a conversation.\n */\n remove(identity: string): Promise<void> {\n return this.services.commandExecutor.mutateResource(\n \"delete\",\n `${this.links.participants}/${identity}`\n );\n }\n}\n\nexport { Participants };\n\n/**\n * Fired when participant joined conversation\n * @event Participants#participantJoined\n * @type {Participant}\n */\n\n/**\n * Fired when participant left conversation\n * @event Participants#participantLeft\n * @type {Participant}\n */\n\n/**\n * Fired when participant updated\n * @event Participants#participantUpdated\n * @type {Object}\n * @property {Participant} participant - Updated Participant\n * @property {Participant#UpdateReason[]} updateReasons - Array of Participant's updated event reasons\n */\n","import {\n McsClient,\n McsMedia,\n MediaCategory as McsMediaCategory,\n CancellablePromise,\n} from \"@twilio/mcs-client\";\n\n/**\n * Category of media. Possible values are as follows:\n * * `'media'`\n * * `'body'`\n * * `'history'`\n */\ntype MediaCategory = McsMediaCategory;\n\ninterface MediaState {\n sid: string;\n category: MediaCategory;\n filename: string | null;\n contentType: string;\n size: number;\n}\n\ninterface MediaServices {\n mcsClient: McsClient;\n}\n\n/**\n * Represents a media information for a message in a conversation.\n */\nclass Media {\n private state: MediaState;\n private services: MediaServices;\n private mcsMedia: McsMedia | null = null;\n\n /**\n * @internal\n */\n constructor(data: MediaState | McsMedia, services: MediaServices) {\n this.services = services;\n\n if (data instanceof McsMedia) {\n this.mcsMedia = data as McsMedia;\n }\n\n this.state = {\n sid: data.sid,\n category: data.category,\n filename: data.filename,\n contentType: data.contentType,\n size: data.size,\n };\n }\n\n /**\n * Server-assigned unique identifier for the media.\n */\n public get sid(): string {\n return this.state.sid;\n }\n\n /**\n * File name. Null if absent.\n */\n public get filename(): string | null {\n return this.state.filename;\n }\n\n /**\n * Content type of the media.\n */\n public get contentType(): string {\n return this.state.contentType;\n }\n\n /**\n * Size of the media in bytes.\n */\n public get size(): number {\n return this.state.size;\n }\n\n /**\n * Media category, can be one of the {@link MediaCategory} values.\n */\n public get category(): MediaCategory {\n return this.state.category;\n }\n\n /**\n * Returns the direct content URL for the media.\n *\n * This URL is impermanent, it will expire in several minutes and cannot be cached.\n * If the URL becomes expired, you need to request a new one.\n * Each call to this function produces a new temporary URL.\n */\n public getContentTemporaryUrl(): CancellablePromise<string | null> {\n return new CancellablePromise(async (resolve, reject, onCancel) => {\n const fetchMediaRequest = this._fetchMcsMedia();\n let contentUrlRequest = this.mcsMedia?.getContentUrl();\n\n onCancel(() => {\n fetchMediaRequest.cancel();\n if (contentUrlRequest) {\n contentUrlRequest.cancel();\n }\n });\n\n try {\n if (!this.mcsMedia) {\n const mcsMedia = await fetchMediaRequest;\n contentUrlRequest = mcsMedia.getContentUrl();\n }\n resolve(contentUrlRequest ? await contentUrlRequest : null);\n } catch (e) {\n reject(e);\n }\n });\n }\n\n private _fetchMcsMedia(): CancellablePromise<McsMedia> {\n return new CancellablePromise(async (resolve, reject, onCancel) => {\n const request = this.services.mcsClient.get(this.state.sid);\n if (this.services.mcsClient) {\n onCancel(() => request.cancel());\n\n try {\n this.mcsMedia = await request;\n resolve(this.mcsMedia);\n } catch (e) {\n reject(e);\n }\n return;\n }\n\n reject(new Error(\"Media Content Service is unavailable\"));\n });\n }\n}\n\nexport { Media, MediaState, MediaServices, MediaCategory };\n","/**\n * Signifies the amount of participants which have the status for the message.\n */\ntype DeliveryAmount = \"none\" | \"some\" | \"all\";\n\ninterface AggregatedDeliveryDescriptor {\n total: number;\n delivered: DeliveryAmount;\n failed: DeliveryAmount;\n read: DeliveryAmount;\n sent: DeliveryAmount;\n undelivered: DeliveryAmount;\n}\n\n/**\n * Contains aggregated information about delivery statuses of a message across all participants\n * of a conversation.\n *\n * At any moment during the message delivery to a participant, the message can have zero or more of following\n * delivery statuses:\n * * Message is considered as **sent** to a participant if the nearest upstream carrier accepted the message.\n * * Message is considered as **delivered** to a participant if Twilio has received confirmation of message\n * delivery from the upstream carrier, and, where available, the destination handset.\n * * Message considered as **undelivered** to a participant if Twilio has received a delivery receipt\n * indicating that the message was not delivered. This can happen for many reasons including carrier content\n * filtering and the availability of the destination handset.\n * * Message considered as **read** by a participant if the message has been delivered and opened by the\n * recipient in a conversation. The recipient must have enabled the read receipts.\n * * Message considered as **failed** to be delivered to a participant if the message could not be sent.\n * This can happen for various reasons including queue overflows, account suspensions and media\n * errors (in the case of MMS for instance).\n *\n * {@link AggregatedDeliveryReceipt} class contains an aggregated value {@link DeliveryAmount} for each delivery status.\n */\nclass AggregatedDeliveryReceipt {\n private state: AggregatedDeliveryDescriptor;\n\n /**\n * @internal\n */\n constructor(data: AggregatedDeliveryDescriptor) {\n this.state = data;\n }\n\n /**\n * Maximum number of delivery events expected for the message.\n */\n public get total(): number {\n return this.state.total;\n }\n\n /**\n * Message is considered as **sent** to a participant if the nearest upstream carrier accepted the message.\n *\n * @return Amount of participants that have the **sent** delivery status for the message.\n */\n public get sent(): DeliveryAmount {\n return this.state.sent;\n }\n\n /**\n * Message is considered as **delivered** to a participant if Twilio has received confirmation of message\n * delivery from the upstream carrier, and, where available, the destination handset.\n *\n * @return Amount of participants that have the **delivered** delivery status for the message.\n */\n public get delivered(): DeliveryAmount {\n return this.state.delivered;\n }\n\n /**\n * Message is considered as **read** by a participant, if the message has been delivered and opened by the\n * recipient in a conversation. The recipient must have enabled the read receipts.\n *\n * @return Amount of participants that have the **read** delivery status for the message.\n */\n public get read(): DeliveryAmount {\n return this.state.read;\n }\n\n /**\n * Message is considered as **undelivered** to a participant if Twilio has received a delivery receipt\n * indicating that the message was not delivered. This can happen for many reasons including carrier content\n * filtering and the availability of the destination handset.\n *\n * @return Ammount of participants that have the **undelivered** delivery status for the message.\n */\n public get undelivered(): DeliveryAmount {\n return this.state.undelivered;\n }\n\n /**\n * Message is considered as **failed** to be delivered to a participant if the message could not be sent.\n * This can happen for various reasons including queue overflows, account suspensions and media\n * errors (in the case of MMS for instance). Twilio does not charge you for failed messages.\n *\n * @return Amount of participants that have the **failed** delivery status for the message.\n */\n public get failed(): DeliveryAmount {\n return this.state.failed;\n }\n\n _update(data: AggregatedDeliveryDescriptor): void {\n this.state = data;\n }\n\n _isEquals(data: AggregatedDeliveryDescriptor): boolean {\n const isTotalSame = this.total === data.total;\n const isSentSame = this.sent === data.sent;\n const isDeliveredSame = this.delivered === data.delivered;\n const isReadSame = this.read === data.read;\n const isUndeliveredSame = this.undelivered === data.undelivered;\n const isFailedSame = this.failed === data.failed;\n\n return (\n isTotalSame &&\n isSentSame &&\n isDeliveredSame &&\n isReadSame &&\n isUndeliveredSame &&\n isFailedSame\n );\n }\n}\n\nexport {\n AggregatedDeliveryReceipt,\n AggregatedDeliveryDescriptor,\n DeliveryAmount,\n};\n","import { Paginator } from \"./interfaces/paginator\";\n\ninterface PaginatorState<T> {\n source: (token: string) => Promise<RestPaginator<T>>;\n nextToken: string;\n prevToken: string;\n items: T[];\n}\n\n/**\n * Pagination helper class.\n */\nclass RestPaginator<T> implements Paginator<T> {\n private state: PaginatorState<T>;\n\n /**\n * Indicates the existence of the next page.\n */\n public get hasNextPage(): boolean {\n return !!this.state.nextToken;\n }\n\n /**\n * Indicates the existence of the previous page\n */\n public get hasPrevPage(): boolean {\n return !!this.state.prevToken;\n }\n\n /**\n * Array of elements on the current page.\n */\n public get items(): T[] {\n return this.state.items;\n }\n\n /**\n * @internal\n */\n constructor(items, source, prevToken, nextToken) {\n this.state = {\n prevToken,\n nextToken,\n source,\n items,\n };\n }\n\n /**\n * Request the next page. Does not modify the existing object.\n */\n nextPage(): Promise<RestPaginator<T>> {\n return this.hasNextPage\n ? this.state.source(this.state.nextToken)\n : Promise.reject(new Error(\"No next page\"));\n }\n\n /**\n * Request the previous page. Does not modify the existing object.\n */\n prevPage(): Promise<RestPaginator<T>> {\n return this.hasPrevPage\n ? this.state.source(this.state.prevToken)\n : Promise.reject(new Error(\"No previous page\"));\n }\n}\n\nexport { RestPaginator };\n","/**\n * Message delivery status.\n */\ntype DeliveryStatus =\n | \"sent\"\n | \"delivered\"\n | \"failed\"\n | \"read\"\n | \"undelivered\"\n | \"queued\";\n\ninterface DetailedDeliveryReceiptDescriptor {\n sid: string;\n message_sid: string;\n conversation_sid: string;\n channel_message_sid: string;\n participant_sid: string;\n status: DeliveryStatus;\n error_code: string | null;\n date_created: string;\n date_updated: string;\n}\n\n/**\n * Represents a delivery receipt of a message.\n */\nclass DetailedDeliveryReceipt {\n /**\n * Unique identifier for the delivery receipt.\n */\n sid: string;\n\n /**\n * Unique identifier for the message in the conversation.\n */\n messageSid: string;\n\n /**\n * Unique identifier for the conversation.\n */\n conversationSid: string;\n\n /**\n * Unique identifier for the `‘channel’` message (e.g., `WAxx` for WhatsApp, `SMxx` for SMS).\n */\n channelMessageSid: string;\n\n /**\n * Unique identifier for the participant.\n */\n participantSid: string;\n\n /**\n * Status of the message delivery.\n */\n status: DeliveryStatus;\n\n /**\n * Numeric error code mapped from Status callback code. Information about the error codes can be found\n * [here](https://www.twilio.com/docs/sms/api/message-resource#delivery-related-errors).\n */\n errorCode: string | 0;\n\n /**\n * Date this delivery receipt was created on.\n */\n dateCreated: string;\n\n /**\n * Date this delivery receipt was last updated on.\n */\n dateUpdated: string;\n\n /**\n * @internal\n */\n constructor(descriptor: DetailedDeliveryReceiptDescriptor) {\n this.sid = descriptor.sid;\n this.messageSid = descriptor.message_sid;\n this.conversationSid = descriptor.conversation_sid;\n this.channelMessageSid = descriptor.channel_message_sid;\n this.participantSid = descriptor.participant_sid;\n this.status = descriptor.status || \"queued\";\n this.errorCode = descriptor.error_code || 0;\n this.dateCreated = descriptor.date_created;\n this.dateUpdated = descriptor.date_updated;\n }\n}\n\nexport {\n DetailedDeliveryReceipt,\n DetailedDeliveryReceiptDescriptor,\n DeliveryStatus,\n};\n","import { parseAttributes, UriBuilder } from \"./util\";\nimport { Logger } from \"./logger\";\nimport { Conversation } from \"./conversation\";\nimport {\n CancellablePromise,\n McsClient,\n MediaCategory,\n} from \"@twilio/mcs-client\";\nimport { Media } from \"./media\";\nimport { Participant } from \"./participant\";\nimport {\n AggregatedDeliveryDescriptor,\n AggregatedDeliveryReceipt,\n} from \"./aggregated-delivery-receipt\";\nimport {\n validateTypes,\n validateTypesAsync,\n nonEmptyString,\n custom,\n} from \"@twilio/declarative-type-validator\";\nimport { attributesValidator } from \"./interfaces/attributes\";\nimport { Network } from \"./services/network\";\nimport { RestPaginator } from \"./rest-paginator\";\nimport { DetailedDeliveryReceipt } from \"./detailed-delivery-receipt\";\nimport { Paginator } from \"./interfaces/paginator\";\nimport { Configuration } from \"./configuration\";\nimport { CommandExecutor } from \"./command-executor\";\nimport { EditMessageRequest } from \"./interfaces/commands/edit-message\";\nimport { MessageResponse } from \"./interfaces/commands/message-response\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport isEqual from \"lodash.isequal\";\nimport { JSONValue } from \"./types\";\nimport { ResponseMeta } from \"./interfaces/commands/response-meta\";\nimport { DeliveryReceiptResponse } from \"./interfaces/commands/delivery-receipt-response\";\n\ntype MessageEvents = {\n updated: (data: {\n message: Message;\n updateReasons: MessageUpdateReason[];\n }) => void;\n};\n\nconst log = Logger.scope(\"Message\");\n\ninterface MessageState {\n sid: string;\n index: number;\n author: string | null;\n subject: string | null;\n body: string | null;\n dateUpdated: Date | null;\n lastUpdatedBy: string | null;\n attributes: JSONValue;\n timestamp: Date | null;\n type: MessageType;\n media: Media | null;\n medias: Media[] | null;\n participantSid: string | null;\n aggregatedDeliveryReceipt: AggregatedDeliveryReceipt | null;\n}\n\ninterface MessageServices {\n mcsClient: McsClient;\n network: Network;\n commandExecutor: CommandExecutor;\n}\n\ninterface MessageLinks {\n self: string;\n conversation: string;\n messages_receipts: string;\n}\n\n/**\n * The reason for the `updated` event being emitted by a message.\n */\ntype MessageUpdateReason =\n | \"body\"\n | \"lastUpdatedBy\"\n | \"dateCreated\"\n | \"dateUpdated\"\n | \"attributes\"\n | \"author\"\n | \"deliveryReceipt\"\n | \"subject\";\n\n/**\n * Type of a message.\n */\ntype MessageType = \"text\" | \"media\";\n\ninterface MessageUpdatedEventArgs {\n message: Message;\n updateReasons: MessageUpdateReason[];\n}\n\nexport interface MessageData {\n sid: string;\n text?: string;\n type?: MessageType;\n author: string | null;\n subject: string | null;\n lastUpdatedBy?: string | null;\n attributes?: JSONValue;\n dateUpdated: string;\n timestamp?: string;\n medias?: Media[];\n media?: Media;\n memberSid?: string;\n delivery?: AggregatedDeliveryDescriptor;\n}\n\n/**\n * A message in a conversation.\n */\nclass Message extends ReplayEventEmitter<MessageEvents> {\n /**\n * Conversation that the message is in.\n */\n public readonly conversation: Conversation;\n\n private readonly links: MessageLinks;\n private readonly configuration: Configuration;\n private readonly services: MessageServices;\n\n private state: MessageState;\n\n /**\n * @internal\n */\n constructor(\n index: number,\n data: MessageData,\n conversation: Conversation,\n links: MessageLinks,\n configuration: Configuration,\n services: MessageServices\n ) {\n super();\n\n this.conversation = conversation;\n\n this.links = links;\n this.configuration = configuration;\n this.services = services;\n\n this.state = {\n sid: data.sid,\n index: index,\n author: data.author,\n subject: data.subject,\n body: data.text ?? null,\n timestamp: data.timestamp ? new Date(data.timestamp) : null,\n dateUpdated: data.dateUpdated ? new Date(data.dateUpdated) : null,\n lastUpdatedBy: data.lastUpdatedBy ?? null,\n attributes: parseAttributes(\n data.attributes,\n `Got malformed attributes for the message ${data.sid}`,\n log\n ),\n type: data.type ?? \"text\",\n media:\n data.type && data.type === \"media\" && data.media\n ? new Media(data.media, this.services)\n : null,\n medias:\n data.type && data.type === \"media\" && data.medias\n ? data.medias.map((m) => new Media(m, this.services))\n : null,\n participantSid: data.memberSid ?? null,\n aggregatedDeliveryReceipt: data.delivery\n ? new AggregatedDeliveryReceipt(data.delivery)\n : null,\n };\n }\n\n /**\n * Fired when the properties or the body of the message has been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the following properties:\n * * {@link Message} message - the message in question\n * * {@link MessageUpdateReason}[] updateReasons - array of reasons for the update\n */\n static readonly updated = \"updated\";\n\n /**\n * The server-assigned unique identifier for the message.\n */\n public get sid(): string {\n return this.state.sid;\n }\n\n /**\n * Name of the user that sent the message.\n */\n public get author(): string | null {\n return this.state.author;\n }\n\n /**\n * Message subject. Used only in email conversations.\n */\n public get subject(): string | null {\n return this.state.subject;\n }\n\n /**\n * Body of the message.\n */\n public get body(): string | null {\n return this.state.body;\n }\n\n /**\n * Date this message was last updated on.\n */\n public get dateUpdated(): Date | null {\n return this.state.dateUpdated;\n }\n\n /**\n * Index of the message in the conversation's messages list.\n * By design of the Conversations system, the message indices may have arbitrary gaps between them,\n * that does not necessarily mean they were deleted or otherwise modified - just that\n * messages may have some non-contiguous indices even if they are being sent immediately one after another.\n *\n * Trying to use indices for some calculations is going to be unreliable.\n *\n * To calculate the number of unread messages it is better to use the read horizon API.\n * See {@link Conversation.getUnreadMessagesCount} for details.\n */\n public get index(): number {\n return this.state.index;\n }\n\n /**\n * Identity of the last user that updated the message.\n */\n public get lastUpdatedBy(): string | null {\n return this.state.lastUpdatedBy;\n }\n\n /**\n * Date this message was created on.\n */\n public get dateCreated(): Date | null {\n return this.state.timestamp;\n }\n\n /**\n * Custom attributes of the message.\n */\n public get attributes(): JSONValue {\n return this.state.attributes;\n }\n\n /**\n * Type of the message.\n */\n public get type(): MessageType {\n return this.state.type;\n }\n\n /**\n * One of the attached media (if present).\n * @deprecated Use attachedMedia instead. Note that the latter is now an array.\n */\n public get media(): Media | null {\n return this.state.media;\n }\n\n /**\n * Return all media attachments, except email body/history attachments, without temporary urls.\n */\n public get attachedMedia(): Array<Media> | null {\n return this.getMediaByCategories([\"media\"]);\n }\n\n /**\n * The server-assigned unique identifier of the authoring participant.\n */\n public get participantSid(): string | null {\n return this.state.participantSid;\n }\n\n /**\n * Aggregated information about the message delivery statuses across all participants of a conversation..\n */\n public get aggregatedDeliveryReceipt(): AggregatedDeliveryReceipt | null {\n return this.state.aggregatedDeliveryReceipt;\n }\n\n /**\n * Return a (possibly empty) array of media matching a specific set of categories.\n * Allowed category is so far only 'media'.\n * @param categories Array of categories to match.\n * @returns Array of media descriptors matching given categories.\n */\n public getMediaByCategories(categories: MediaCategory[]): Media[] | null {\n return (this.state.medias ?? []).filter((m) =>\n categories.includes(m.category)\n );\n }\n\n /**\n * Get a media descriptor for an email body attachment of a provided type.\n * Allowed body types are returned in the Conversation.limits().emailBodiesAllowedContentTypes array.\n * @param type Type of email body to request, defaults to `text/plain`.\n */\n @validateTypes([nonEmptyString, \"undefined\"])\n public getEmailBody(type = \"text/plain\"): Media | null {\n return (\n this.getMediaByCategories([\"body\"])\n ?.filter((m) => m.contentType == type)\n .shift() ?? null\n );\n }\n\n /**\n * Get a media descriptor for an email history attachment of a provided type.\n * Allowed body types are returned in the Conversation.limits().emailHistoriesAllowedContentTypes array.\n * @param type Type of email history to request, defaults to `text/plain`.\n */\n @validateTypes([nonEmptyString, \"undefined\"])\n public getEmailHistory(type = \"text/plain\"): Media | null {\n return (\n this.getMediaByCategories([\"history\"])\n ?.filter((m) => m.contentType == type)\n .shift() ?? null\n );\n }\n\n _update(data) {\n const updateReasons: MessageUpdateReason[] = [];\n\n if (\n (data.text || typeof data.text === \"string\") &&\n data.text !== this.state.body\n ) {\n this.state.body = data.text;\n updateReasons.push(\"body\");\n }\n\n if (data.subject && data.subject !== this.state.subject) {\n this.state.subject = data.subject;\n updateReasons.push(\"subject\");\n }\n\n if (data.lastUpdatedBy && data.lastUpdatedBy !== this.state.lastUpdatedBy) {\n this.state.lastUpdatedBy = data.lastUpdatedBy;\n updateReasons.push(\"lastUpdatedBy\");\n }\n\n if (data.author && data.author !== this.state.author) {\n this.state.author = data.author;\n updateReasons.push(\"author\");\n }\n\n if (\n data.dateUpdated &&\n new Date(data.dateUpdated).getTime() !==\n (this.state.dateUpdated && this.state.dateUpdated.getTime())\n ) {\n this.state.dateUpdated = new Date(data.dateUpdated);\n updateReasons.push(\"dateUpdated\");\n }\n\n if (\n data.timestamp &&\n new Date(data.timestamp).getTime() !==\n (this.state.timestamp && this.state.timestamp.getTime())\n ) {\n this.state.timestamp = new Date(data.timestamp);\n updateReasons.push(\"dateCreated\");\n }\n\n const updatedAttributes = parseAttributes(\n data.attributes,\n `Got malformed attributes for the message ${this.sid}`,\n log\n );\n if (!isEqual(this.state.attributes, updatedAttributes)) {\n this.state.attributes = updatedAttributes;\n updateReasons.push(\"attributes\");\n }\n\n const updatedAggregatedDelivery = data.delivery;\n const currentAggregatedDelivery = this.state.aggregatedDeliveryReceipt;\n const isUpdatedAggregateDeliveryValid =\n !!updatedAggregatedDelivery &&\n !!updatedAggregatedDelivery.total &&\n !!updatedAggregatedDelivery.delivered &&\n !!updatedAggregatedDelivery.failed &&\n !!updatedAggregatedDelivery.read &&\n !!updatedAggregatedDelivery.sent &&\n !!updatedAggregatedDelivery.undelivered;\n if (isUpdatedAggregateDeliveryValid) {\n if (!currentAggregatedDelivery) {\n this.state.aggregatedDeliveryReceipt = new AggregatedDeliveryReceipt(\n updatedAggregatedDelivery\n );\n updateReasons.push(\"deliveryReceipt\");\n } else if (\n !currentAggregatedDelivery._isEquals(updatedAggregatedDelivery)\n ) {\n currentAggregatedDelivery._update(updatedAggregatedDelivery);\n updateReasons.push(\"deliveryReceipt\");\n }\n }\n\n if (updateReasons.length > 0) {\n this.emit(\"updated\", { message: this, updateReasons: updateReasons });\n }\n }\n\n /**\n * Get the participant who is the author of the message.\n */\n public async getParticipant(): Promise<Participant> {\n let participant: Participant | null = null;\n if (this.state.participantSid) {\n participant = await this.conversation\n .getParticipantBySid(this.state.participantSid)\n .catch(() => {\n log.debug(\n `Participant with sid \"${this.participantSid}\" not found for message ${this.sid}`\n );\n return null;\n });\n }\n if (!participant && this.state.author) {\n participant = await this.conversation\n .getParticipantByIdentity(this.state.author)\n .catch(() => {\n log.debug(\n `Participant with identity \"${this.author}\" not found for message ${this.sid}`\n );\n return null;\n });\n }\n if (participant) {\n return participant;\n }\n let errorMesage = \"Participant with \";\n if (this.state.participantSid) {\n errorMesage += \"SID '\" + this.state.participantSid + \"' \";\n }\n if (this.state.author) {\n if (this.state.participantSid) {\n errorMesage += \"or \";\n }\n errorMesage += \"identity '\" + this.state.author + \"' \";\n }\n if (errorMesage === \"Participant with \") {\n errorMesage = \"Participant \";\n }\n errorMesage += \"was not found\";\n throw new Error(errorMesage);\n }\n\n /**\n * Get the delivery receipts of the message.\n */\n public async getDetailedDeliveryReceipts(): Promise<\n DetailedDeliveryReceipt[]\n > {\n let paginator: Paginator<DetailedDeliveryReceipt> =\n await this._getDetailedDeliveryReceiptsPaginator();\n let detailedDeliveryReceipts: DetailedDeliveryReceipt[] = [];\n\n while (true) {\n detailedDeliveryReceipts = [\n ...detailedDeliveryReceipts,\n ...paginator.items,\n ];\n\n if (!paginator.hasNextPage) {\n break;\n }\n\n paginator = await paginator.nextPage();\n }\n\n return detailedDeliveryReceipts;\n }\n\n /**\n * Remove the message.\n */\n public async remove(): Promise<Message> {\n await this.services.commandExecutor.mutateResource(\n \"delete\",\n this.links.self\n );\n\n return this;\n }\n\n /**\n * Edit the message body.\n * @param body New body of the message.\n */\n @validateTypesAsync(\"string\")\n public async updateBody(body: string): Promise<Message> {\n await this.services.commandExecutor.mutateResource<\n EditMessageRequest,\n MessageResponse\n >(\"post\", this.links.self, {\n body,\n });\n\n return this;\n }\n\n /**\n * Edit the message attributes.\n * @param attributes New attributes.\n */\n @validateTypesAsync(attributesValidator)\n public async updateAttributes(attributes: JSONValue): Promise<Message> {\n await this.services.commandExecutor.mutateResource<\n EditMessageRequest,\n MessageResponse\n >(\"post\", this.links.self, {\n attributes:\n typeof attributes !== \"undefined\"\n ? JSON.stringify(attributes)\n : undefined,\n });\n\n return this;\n }\n\n /**\n * Get content URLs for all media attachments in the given set using a single operation.\n * @param contentSet Set of media attachments to query content URLs.\n */\n @validateTypesAsync(\n custom((value) => [\n value instanceof Array &&\n value.length > 0 &&\n value.reduce((a, c) => a && c instanceof Media, true),\n \"a non-empty array of Media\",\n ])\n )\n public getTemporaryContentUrlsForMedia(\n contentSet: Media[] | null\n ): CancellablePromise<Map<string, string>> {\n // We ignore existing mcsMedia members of each of the media entries.\n // Instead we just collect their sids and pull new descriptors from a mediaSet GET endpoint.\n const sids = contentSet?.map((m) => m.sid) ?? [];\n return this.getTemporaryContentUrlsForMediaSids(sids);\n }\n\n /**\n * Get content URLs for all media attachments in the given set of media sids using a single operation.\n * @param mediaSids Set of media sids to query for the content URL.\n */\n public getTemporaryContentUrlsForMediaSids(\n mediaSids: string[]\n ): CancellablePromise<Map<string, string>> {\n return new CancellablePromise(async (resolve, reject, onCancel) => {\n const mediaGetRequest = this.services.mcsClient.mediaSetGetContentUrls(\n mediaSids ?? []\n );\n\n if (!this.services.mcsClient || !mediaSids) {\n reject(new Error(\"Media Content Service is unavailable\"));\n return;\n }\n\n onCancel(() => {\n mediaGetRequest.cancel();\n });\n\n try {\n const urls = await mediaGetRequest;\n resolve(urls);\n } catch (e) {\n reject(e);\n }\n });\n }\n\n /**\n * Get content URLs for all media attached to the message.\n */\n public getTemporaryContentUrlsForAttachedMedia(): CancellablePromise<\n Map<string, string>\n > {\n const media = this.attachedMedia;\n const sids = media?.map((m) => m.sid) ?? [];\n return this.getTemporaryContentUrlsForMediaSids(sids);\n }\n\n private async _getDetailedDeliveryReceiptsPaginator(options?: {\n pageToken?: string;\n pageSize?: number;\n }): Promise<Paginator<DetailedDeliveryReceipt>> {\n const messagesReceiptsUrl = this.configuration.links.messagesReceipts\n .replace(\"%s\", this.conversation.sid)\n .replace(\"%s\", this.sid);\n const url = new UriBuilder(messagesReceiptsUrl)\n .arg(\"PageToken\", options?.pageToken as string)\n .arg(\"PageSize\", options?.pageSize as number)\n .build();\n const response = await this.services.network.get<\n { delivery_receipts: DeliveryReceiptResponse[] } & ResponseMeta\n >(url);\n\n return new RestPaginator<DetailedDeliveryReceipt>(\n response.body.delivery_receipts.map(\n (x) => new DetailedDeliveryReceipt(x)\n ),\n (pageToken, pageSize) =>\n this._getDetailedDeliveryReceiptsPaginator({ pageToken, pageSize }),\n response.body.meta.previous_token,\n response.body.meta.next_token\n );\n }\n}\n\nexport {\n Message,\n MessageServices,\n MessageType,\n MessageUpdateReason,\n MessageUpdatedEventArgs,\n};\n","import { Logger } from \"../logger\";\n\nimport {\n Message,\n MessageData,\n MessageUpdatedEventArgs,\n MessageUpdateReason,\n} from \"../message\";\nimport {\n Conversation,\n SendEmailOptions,\n SendMediaOptions,\n} from \"../conversation\";\nimport { UnsentMessage } from \"../unsent-message\";\n\nimport { SyncList, SyncClient } from \"twilio-sync\";\nimport { SyncPaginator } from \"../sync-paginator\";\n\nimport { McsClient, McsMedia, CancellablePromise } from \"@twilio/mcs-client\";\nimport { Network } from \"../services/network\";\nimport { Configuration } from \"../configuration\";\nimport { CommandExecutor } from \"../command-executor\";\nimport { SendMessageRequest } from \"../interfaces/commands/send-message\";\nimport { MessageResponse } from \"../interfaces/commands/message-response\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport { JSONValue } from \"../types\";\n\ntype MessagesEvents = {\n messageAdded: (message: Message) => void;\n messageRemoved: (message: Message) => void;\n messageUpdated: (data: {\n message: Message;\n updateReasons: MessageUpdateReason[];\n }) => void;\n};\n\nconst log = Logger.scope(\"Messages\");\n\nexport interface MessagesServices {\n mcsClient: McsClient;\n network: Network;\n syncClient: SyncClient;\n commandExecutor: CommandExecutor;\n}\n\n/**\n * Represents the collection of messages in a conversation\n */\nclass Messages extends ReplayEventEmitter<MessagesEvents> {\n public readonly conversation: Conversation;\n private readonly configuration: Configuration;\n private readonly services: MessagesServices;\n private readonly messagesByIndex: Map<number, Message>;\n private messagesListPromise: Promise<SyncList> | null;\n\n public constructor(\n conversation: Conversation,\n configuration: Configuration,\n services: MessagesServices\n ) {\n super();\n\n this.conversation = conversation;\n this.configuration = configuration;\n this.services = services;\n\n this.messagesByIndex = new Map();\n this.messagesListPromise = null;\n }\n\n /**\n * Subscribe to the Messages Event Stream\n * @param name - The name of Sync object for the Messages resource.\n */\n public async subscribe(name: string) {\n if (this.messagesListPromise) {\n return this.messagesListPromise;\n }\n\n this.messagesListPromise = this.services.syncClient.list({\n id: name,\n mode: \"open_existing\",\n });\n\n try {\n const list = await this.messagesListPromise;\n\n list.on(\"itemAdded\", (args) => {\n log.debug(`${this.conversation.sid} itemAdded: ${args.item.index}`);\n\n const links = {\n self: `${this.conversation.links.messages}/${args.item.data.sid}`,\n conversation: this.conversation.links.self,\n messages_receipts: `${this.conversation.links.messages}/${args.item.data.sid}/Receipts`,\n };\n const message = new Message(\n args.item.index,\n args.item.data,\n this.conversation,\n links,\n this.configuration,\n this.services\n );\n\n if (this.messagesByIndex.has(message.index)) {\n log.debug(\n \"Message arrived, but is already known and ignored\",\n this.conversation.sid,\n message.index\n );\n return;\n }\n\n this.messagesByIndex.set(message.index, message);\n\n message.on(\"updated\", (args: MessageUpdatedEventArgs) =>\n this.emit(\"messageUpdated\", args)\n );\n\n this.emit(\"messageAdded\", message);\n });\n\n list.on(\"itemRemoved\", (args) => {\n log.debug(`#{this.conversation.sid} itemRemoved: ${args.index}`);\n\n const index = args.index;\n\n if (this.messagesByIndex.has(index)) {\n const message = this.messagesByIndex.get(index);\n if (!message) {\n return;\n }\n\n this.messagesByIndex.delete(message.index);\n message.removeAllListeners(\"updated\");\n this.emit(\"messageRemoved\", message);\n }\n });\n\n list.on(\"itemUpdated\", (args) => {\n log.debug(`${this.conversation.sid} itemUpdated: ${args.item.index}`);\n\n const message = this.messagesByIndex.get(args.item.index);\n\n if (message) {\n message._update(args.item.data);\n }\n });\n\n return list;\n } catch (err) {\n this.messagesListPromise = null;\n\n if (this.services.syncClient.connectionState !== \"disconnected\") {\n log.error(\n \"Failed to get messages object for conversation\",\n this.conversation.sid,\n err\n );\n }\n\n log.debug(\n \"ERROR: Failed to get messages object for conversation\",\n this.conversation.sid,\n err\n );\n\n throw err;\n }\n }\n\n public async unsubscribe() {\n if (!this.messagesListPromise) {\n return;\n }\n\n const entity = await this.messagesListPromise;\n entity.close();\n this.messagesListPromise = null;\n }\n\n /**\n * Send a message to the conversation. The message could include text and multiple media attachments.\n * @param message Message to post\n */\n public sendV2(message: UnsentMessage): CancellablePromise<MessageResponse> {\n log.debug(\n \"Sending message V2\",\n message.mediaContent,\n message.attributes,\n message.emailOptions\n );\n\n return new CancellablePromise(async (resolve, reject, onCancel) => {\n const media: McsMedia[] = [];\n const requests: CancellablePromise<McsMedia>[] = [];\n\n onCancel(() => {\n requests.forEach((request) => request.cancel());\n });\n\n for (const [category, mediaContent] of message.mediaContent) {\n try {\n log.debug(\n `Adding media to a message as ${\n mediaContent instanceof FormData ? \"FormData\" : \"SendMediaOptions\"\n }`,\n mediaContent\n );\n\n const request =\n mediaContent instanceof FormData\n ? this.services.mcsClient.postFormData(mediaContent, category)\n : this.services.mcsClient.post(\n mediaContent.contentType ?? \"\",\n mediaContent.media ?? \"\",\n category,\n mediaContent.filename\n );\n\n requests.push(request);\n\n media.push(await request);\n } catch (e) {\n reject(e);\n return;\n }\n }\n\n const messagesPostRequest = this.services.commandExecutor.mutateResource<\n SendMessageRequest,\n MessageResponse\n >(\"post\", this.conversation.links.messages, {\n body: message.text,\n subject: message.emailOptions?.subject,\n media_sids: media.map((m) => m.sid),\n attributes:\n typeof message.attributes !== \"undefined\"\n ? JSON.stringify(message.attributes)\n : undefined,\n });\n\n try {\n resolve(await messagesPostRequest);\n } catch (e) {\n reject(e);\n }\n });\n }\n\n /**\n * Send Message to the conversation\n * @param message Message to post\n * @param attributes Message attributes\n * @param emailOptions Options that modify E-mail integration behaviors.\n * @returns Returns promise which can fail\n */\n public async send(\n message: null | string | FormData | SendMediaOptions,\n attributes: JSONValue = {},\n emailOptions?: SendEmailOptions\n ): Promise<MessageResponse> {\n log.debug(\"Sending text message\", message, attributes, emailOptions);\n\n return this.services.commandExecutor.mutateResource<\n SendMessageRequest,\n MessageResponse\n >(\"post\", this.conversation.links.messages, {\n body: message ?? \"\",\n attributes:\n typeof attributes !== \"undefined\"\n ? JSON.stringify(attributes)\n : undefined,\n subject: emailOptions?.subject,\n });\n }\n\n /**\n * Send Media Message to the conversation\n * @param mediaContent Media content to post\n * @param attributes Message attributes\n * @param emailOptions Email options\n * @returns Returns promise which can fail\n */\n public async sendMedia(\n mediaContent: FormData | SendMediaOptions,\n attributes: JSONValue = {},\n emailOptions?: SendEmailOptions\n ) {\n log.debug(\"Sending media message\", mediaContent, attributes, emailOptions);\n log.debug(\n `Sending media message as ${\n mediaContent instanceof FormData ? \"FormData\" : \"SendMediaOptions\"\n }`,\n mediaContent,\n attributes\n );\n\n const media: McsMedia =\n mediaContent instanceof FormData\n ? await this.services.mcsClient.postFormData(mediaContent)\n : await this.services.mcsClient.post(\n mediaContent.contentType ?? \"\",\n mediaContent.media ?? \"\",\n \"media\",\n mediaContent.filename\n );\n\n // emailOptions are currently ignored for media messages.\n return await this.services.commandExecutor.mutateResource<\n SendMessageRequest,\n MessageResponse\n >(\"post\", this.conversation.links.messages, {\n media_sids: [media.sid],\n attributes:\n typeof attributes !== \"undefined\"\n ? JSON.stringify(attributes)\n : undefined,\n });\n }\n\n /**\n * Returns messages from conversation using paginator interface\n * @param pageSize Number of messages to return in single chunk. By default it's 30.\n * @param anchor Most early message id which is already known, or 'end' by default\n * @param direction Pagination order 'backwards' or 'forward', 'forward' by default\n * @returns Last page of messages by default\n */\n public async getMessages(\n pageSize: number | undefined,\n anchor: number | \"end\" | undefined,\n direction: \"forward\" | \"backwards\" = \"backwards\"\n ): Promise<SyncPaginator<Message>> {\n return this._getMessages(pageSize, anchor, direction);\n }\n\n private _wrapPaginator(order, page, op) {\n // Due to an inconsistency between Sync and Chat conventions, next and\n // previous pages should be swapped.\n const shouldReverse = order === \"desc\";\n\n const nextPage = () =>\n page.nextPage().then((page) => this._wrapPaginator(order, page, op));\n const previousPage = () =>\n page.prevPage().then((page) => this._wrapPaginator(order, page, op));\n\n return op(page.items).then((items) => ({\n items: items.sort((x, y) => {\n return x.index - y.index;\n }),\n hasPrevPage: shouldReverse ? page.hasNextPage : page.hasPrevPage,\n hasNextPage: shouldReverse ? page.hasPrevPage : page.hasNextPage,\n prevPage: shouldReverse ? nextPage : previousPage,\n nextPage: shouldReverse ? previousPage : nextPage,\n }));\n }\n\n private _upsertMessage(index: number, value: MessageData) {\n const cachedMessage = this.messagesByIndex.get(index);\n\n if (cachedMessage) {\n return cachedMessage;\n }\n\n const links = {\n self: `${this.conversation.links.messages}/${value.sid}`,\n conversation: this.conversation.links.self,\n messages_receipts: `${this.conversation.links.messages}/${value.sid}/Receipts`,\n };\n const message = new Message(\n index,\n value,\n this.conversation,\n links,\n this.configuration,\n this.services\n );\n\n this.messagesByIndex.set(message.index, message);\n\n message.on(\"updated\", (args: MessageUpdatedEventArgs) =>\n this.emit(\"messageUpdated\", args)\n );\n\n return message;\n }\n\n /**\n * Returns last messages from conversation\n * @param {Number} [pageSize] Number of messages to return in single chunk. By default it's 30.\n * @param {String} [anchor] Most early message id which is already known, or 'end' by default\n * @param {String} [direction] Pagination order 'backwards' or 'forward', or 'forward' by default\n * @returns {Promise<SyncPaginator<Message>>} last page of messages by default\n * @private\n */\n private async _getMessages(\n pageSize = 30,\n anchor: number | \"end\" = \"end\",\n direction: \"forward\" | \"backwards\" = \"forward\"\n ): Promise<SyncPaginator<Message>> {\n const order = direction === \"backwards\" ? \"desc\" : \"asc\";\n const list = await this.messagesListPromise;\n const page = await list?.getItems({\n from: anchor !== \"end\" ? anchor : void 0,\n pageSize,\n order,\n limit: pageSize, // @todo Limit equals pageSize by default in Sync. This is probably not ideal.\n });\n\n return await this._wrapPaginator(order, page, (items) =>\n Promise.all(\n items.map((item) => this._upsertMessage(item.index, item.data))\n )\n );\n }\n}\n\nexport { Messages };\n","import { MediaCategory, CancellablePromise } from \"@twilio/mcs-client\";\nimport { parseToNumber } from \"./util\";\nimport { SendEmailOptions, SendMediaOptions } from \"./conversation\";\nimport { JSONValue } from \"./types\";\nimport { Messages } from \"./data/messages\";\n\n/**\n * An unsent message. Returned from {@link MessageBuilder.build}.\n */\nclass UnsentMessage {\n public text?: string;\n public attributes: JSONValue = {};\n public mediaContent: [MediaCategory, FormData | SendMediaOptions][] = [];\n public emailOptions: SendEmailOptions = {};\n\n /**\n * @internal\n */\n constructor(private messagesEntity: Messages) {}\n\n /**\n * Send the prepared message to the conversation.\n * @returns Index of the new message in the conversation.\n */\n send(): CancellablePromise<number | null> {\n return new CancellablePromise(async (resolve, reject, onCancel) => {\n const request = this.messagesEntity.sendV2(this);\n onCancel(() => request.cancel());\n try {\n const response = await request;\n resolve(parseToNumber(response.index));\n } catch (e) {\n reject(e);\n }\n });\n }\n}\n\nexport { UnsentMessage };\n","import { CancellablePromise } from \"@twilio/mcs-client\";\nimport { ConversationLimits } from \"./interfaces/conversation-limits\";\nimport { SendMediaOptions } from \"./conversation\";\nimport { UnsentMessage } from \"./unsent-message\";\nimport { JSONValue } from \"./types\";\nimport { Messages } from \"./data/messages\";\n\n/**\n * Message builder. Allows the message to be built and sent via method chaining.\n *\n * Example:\n *\n * ```ts\n * await testConversation.prepareMessage()\n * .setBody('Hello!')\n * .setAttributes({foo: 'bar'})\n * .addMedia(media1)\n * .addMedia(media2)\n * .build()\n * .send();\n * ```\n */\nclass MessageBuilder {\n private readonly message: UnsentMessage;\n private emailBodies: Map<string, FormData | SendMediaOptions>;\n private emailHistories: Map<string, FormData | SendMediaOptions>;\n\n /**\n * @internal\n */\n constructor(\n private readonly limits: ConversationLimits,\n messagesEntity: Messages\n ) {\n this.message = new UnsentMessage(messagesEntity);\n this.emailBodies = new Map<string, FormData | SendMediaOptions>();\n this.emailHistories = new Map<string, FormData | SendMediaOptions>();\n }\n\n /**\n * Sets the message body.\n * @param text Contents of the body.\n */\n setBody(text: string): MessageBuilder {\n this.message.text = text;\n return this;\n }\n\n /**\n * Sets the message subject.\n * @param subject Contents of the subject.\n */\n setSubject(subject: string): MessageBuilder {\n this.message.emailOptions.subject = subject;\n return this;\n }\n\n /**\n * Sets the message attributes.\n * @param attributes Message attributes.\n */\n setAttributes(attributes: JSONValue): MessageBuilder {\n this.message.attributes = attributes;\n return this;\n }\n\n /**\n * Set the email body with a given content type.\n * @param contentType Format of the body to set (text/plain or text/html).\n * @param body Body payload in the selected format.\n */\n setEmailBody(\n contentType: string,\n body: FormData | SendMediaOptions\n ): MessageBuilder {\n this.emailBodies.set(contentType, body);\n return this;\n }\n\n /**\n * Set the email history with a given content type.\n * @param contentType Format of the history to set (text/plain or text/html).\n * @param history History payload in the selected format.\n */\n setEmailHistory(\n contentType: string,\n history: FormData | SendMediaOptions\n ): MessageBuilder {\n this.emailHistories.set(contentType, history);\n return this;\n }\n\n /**\n * Adds media to the message.\n * @param payload Media to add.\n */\n addMedia(payload: FormData | SendMediaOptions): MessageBuilder {\n if (typeof FormData === \"undefined\" && payload instanceof FormData) {\n throw new Error(\"Could not add FormData content whilst not in a browser\");\n }\n if (!(payload instanceof FormData)) {\n const mediaOptions = payload as SendMediaOptions;\n if (!mediaOptions.contentType || !mediaOptions.media) {\n throw new Error(\n \"Media content in SendMediaOptions must contain non-empty contentType and media\"\n );\n }\n }\n this.message.mediaContent.push([\"media\", payload]);\n return this;\n }\n\n /**\n * Builds the message, making it ready to be sent.\n */\n build(): UnsentMessage {\n this.emailBodies.forEach((_, key) => {\n if (!this.limits.emailBodiesAllowedContentTypes.includes(key)) {\n throw new Error(`Unsupported email body content type ${key}`);\n }\n });\n this.emailHistories.forEach((_, key) => {\n if (!this.limits.emailHistoriesAllowedContentTypes.includes(key)) {\n throw new Error(`Unsupported email history content type ${key}`);\n }\n });\n if (\n this.emailBodies.size > this.limits.emailBodiesAllowedContentTypes.length\n ) {\n throw new Error(\n `Too many email bodies attached to the message (${this.emailBodies.size} > ${this.limits.emailBodiesAllowedContentTypes.length})`\n );\n }\n if (\n this.emailHistories.size >\n this.limits.emailHistoriesAllowedContentTypes.length\n ) {\n throw new Error(\n `Too many email histories attached to the message (${this.emailHistories.size} > ${this.limits.emailHistoriesAllowedContentTypes.length})`\n );\n }\n\n if (\n this.message.mediaContent.length > this.limits.mediaAttachmentsCountLimit\n ) {\n throw new Error(\n `Too many media attachments in the message (${this.message.mediaContent.length} > ${this.limits.mediaAttachmentsCountLimit})`\n );\n }\n\n // @todo we don't know the sizes of the attachments in FormData\n // @todo insertion below makes build() method non-repeatable - probably move to UnsentMessage.send() or even sendV2()?\n\n this.emailBodies.forEach((body) => {\n this.message.mediaContent.push([\"body\", body]);\n });\n\n this.emailHistories.forEach((history) => {\n this.message.mediaContent.push([\"history\", history]);\n });\n\n return this.message;\n }\n\n /**\n * Prepares a message and sends it to the conversation.\n */\n buildAndSend(): CancellablePromise<number | null> {\n return this.build().send();\n }\n\n private getPayloadContentType(\n payload: FormData | SendMediaOptions\n ): string | null {\n if (typeof FormData !== \"undefined\" && payload instanceof FormData) {\n return payload.get(\"Content-Type\") as string;\n }\n return (payload as SendMediaOptions).contentType;\n }\n}\n\nexport { MessageBuilder };\n","import { Logger } from \"./logger\";\n\nimport { ParticipantBindingOptions, Participants } from \"./data/participants\";\nimport {\n Participant,\n ParticipantUpdatedEventArgs,\n ParticipantUpdateReason,\n} from \"./participant\";\nimport { Messages } from \"./data/messages\";\nimport {\n Message,\n MessageUpdatedEventArgs,\n MessageUpdateReason,\n} from \"./message\";\n\nimport { UriBuilder, parseToNumber } from \"./util\";\nimport { Users } from \"./data/users\";\nimport { Paginator } from \"./interfaces/paginator\";\nimport { ConversationsDataSource } from \"./data/conversations\";\nimport { McsClient } from \"@twilio/mcs-client\";\n\nimport { SyncClient, SyncDocument } from \"twilio-sync\";\nimport { TypingIndicator } from \"./services/typing-indicator\";\nimport { Network } from \"./services/network\";\nimport {\n validateTypesAsync,\n custom,\n literal,\n nonEmptyString,\n nonNegativeInteger,\n objectSchema,\n} from \"@twilio/declarative-type-validator\";\nimport {\n attributesValidator,\n optionalAttributesValidator,\n} from \"./interfaces/attributes\";\nimport { Configuration } from \"./configuration\";\nimport { CommandExecutor } from \"./command-executor\";\nimport { AddParticipantRequest } from \"./interfaces/commands/add-participant\";\nimport { EditConversationRequest } from \"./interfaces/commands/edit-conversation\";\nimport { ConversationResponse } from \"./interfaces/commands/conversation-response\";\nimport { ParticipantResponse } from \"./interfaces/commands/participant-response\";\nimport { EditNotificationLevelRequest } from \"./interfaces/commands/edit-notification-level\";\nimport {\n EditLastReadMessageIndexRequest,\n EditLastReadMessageIndexResponse,\n} from \"./interfaces/commands/edit-last-read-message-index\";\nimport { ConversationLimits } from \"./interfaces/conversation-limits\";\nimport { MessageBuilder } from \"./message-builder\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport isEqual from \"lodash.isequal\";\nimport { JSONValue } from \"./types\";\n\ntype ConversationEvents = {\n participantJoined: (participant: Participant) => void;\n participantLeft: (participant: Participant) => void;\n participantUpdated: (data: {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n }) => void;\n messageAdded: (message: Message) => void;\n messageRemoved: (message: Message) => void;\n messageUpdated: (data: {\n message: Message;\n updateReasons: MessageUpdateReason[];\n }) => void;\n typingEnded: (participant: Participant) => void;\n typingStarted: (participant: Participant) => void;\n updated: (data: {\n conversation: Conversation;\n updateReasons: ConversationUpdateReason[];\n }) => void;\n removed: (conversation: Conversation) => void;\n};\n\nconst log = Logger.scope(\"Conversation\");\n\nconst fieldMappings = {\n lastMessage: \"lastMessage\",\n attributes: \"attributes\",\n createdBy: \"createdBy\",\n dateCreated: \"dateCreated\",\n dateUpdated: \"dateUpdated\",\n friendlyName: \"friendlyName\",\n lastConsumedMessageIndex: \"lastConsumedMessageIndex\",\n notificationLevel: \"notificationLevel\",\n sid: \"sid\",\n status: \"status\",\n uniqueName: \"uniqueName\",\n state: \"state\",\n bindings: \"bindings\",\n};\n\nfunction parseTime(timeString) {\n try {\n return new Date(timeString);\n } catch (e) {\n return null;\n }\n}\n\nexport interface ConversationServices {\n users: Users;\n typingIndicator: TypingIndicator;\n network: Network;\n mcsClient: McsClient;\n syncClient: SyncClient;\n commandExecutor: CommandExecutor;\n}\n\ninterface ConversationInternalState {\n uniqueName: string | null;\n status: ConversationStatus;\n attributes: JSONValue;\n createdBy?: string;\n dateCreated: Date | null;\n dateUpdated: Date | null;\n friendlyName: string | null;\n lastReadMessageIndex: number | null;\n lastMessage?: LastMessage;\n notificationLevel?: NotificationLevel;\n state?: ConversationState;\n bindings: ConversationBindings;\n}\n\ninterface ConversationDescriptor {\n channel: string;\n entityName: string;\n uniqueName: string;\n attributes: JSONValue;\n createdBy?: string;\n friendlyName?: string;\n lastConsumedMessageIndex: number;\n dateCreated: Date | null;\n dateUpdated: Date | null;\n notificationLevel?: NotificationLevel;\n bindings?: ConversationBindings;\n}\n\ninterface ConversationLinks {\n self: string;\n messages: string;\n participants: string;\n}\n\n/**\n * The reason for the `updated` event being emitted by a conversation.\n */\ntype ConversationUpdateReason =\n | \"attributes\"\n | \"createdBy\"\n | \"dateCreated\"\n | \"dateUpdated\"\n | \"friendlyName\"\n | \"lastReadMessageIndex\"\n | \"state\"\n | \"status\"\n | \"uniqueName\"\n | \"lastMessage\"\n | \"notificationLevel\"\n | \"bindings\";\n\n/**\n * The status of the conversation, relative to the client: whether\n * the conversation has been `joined` or the client is\n * `notParticipating` in the conversation.\n */\ntype ConversationStatus = \"notParticipating\" | \"joined\";\n\n/**\n * The user's notification level for the conversation. Determines\n * whether the currently logged-in user will receive pushes for events\n * in this conversation. Can be either `muted` or `default`, where\n * `default` defers to the global service push configuration.\n */\ntype NotificationLevel = \"default\" | \"muted\";\n\n/**\n * The state of the conversation.\n */\ninterface ConversationState {\n /**\n * The current state.\n */\n current: \"active\" | \"inactive\" | \"closed\";\n\n /**\n * Date at which the latest conversation state update happened.\n */\n dateUpdated: Date;\n}\n\ninterface ConversationUpdatedEventArgs {\n conversation: Conversation;\n updateReasons: ConversationUpdateReason[];\n}\n\n/**\n * Binding for email conversation.\n */\ninterface ConversationBindings {\n email?: ConversationEmailBinding;\n sms?: ConversationSmsBinding;\n}\n\n/**\n * Binding for email conversation.\n */\ninterface ConversationEmailBinding {\n name?: string;\n projected_address: string;\n}\n\ninterface ConversationSmsBinding {\n address?: string;\n}\n\n/**\n * Configuration for attaching a media file to a message.\n * These options can be passed to {@link Conversation.sendMessage} and\n * {@link MessageBuilder.addMedia}.\n */\ninterface SendMediaOptions {\n /**\n * Content type of media.\n */\n contentType: null | string;\n\n /**\n * Optional filename.\n */\n filename?: string;\n\n /**\n * Content to post.\n */\n media: null | string | Buffer | Blob;\n}\n\n/**\n * These options can be passed to {@link Conversation.sendMessage}.\n */\ninterface SendEmailOptions {\n /**\n * Message subject. Ignored for media messages.\n */\n subject?: string;\n}\n\n/**\n * Information about the last message of a conversation.\n */\ninterface LastMessage {\n /**\n * Message's index.\n */\n index?: number;\n\n /**\n * Message's creation date.\n */\n dateCreated?: Date;\n}\n\n/**\n * A conversation represents communication between multiple Conversations clients\n */\nclass Conversation extends ReplayEventEmitter<ConversationEvents> {\n /**\n * Unique system identifier of the conversation.\n */\n public readonly sid: string;\n public readonly links: ConversationLinks;\n\n private readonly configuration: Configuration;\n private readonly services: ConversationServices;\n private channelState: ConversationInternalState;\n private statusSource!: ConversationsDataSource;\n\n private entityPromise!: Promise<void | SyncDocument> | null;\n private entityName: string;\n private entity!: SyncDocument | null;\n private messagesEntity: Messages;\n private participantsEntity: Participants;\n private readonly participants: Map<string, Participant>;\n\n /**\n * @internal\n */\n constructor(\n descriptor: ConversationDescriptor,\n sid: string,\n links: ConversationLinks,\n configuration: Configuration,\n services: ConversationServices\n ) {\n super();\n\n this.sid = sid;\n this.links = links;\n this.configuration = configuration;\n this.services = services;\n\n const attributes = descriptor.attributes || {};\n const createdBy = descriptor.createdBy;\n const dateCreated = parseTime(descriptor.dateCreated);\n const dateUpdated = parseTime(descriptor.dateUpdated);\n const friendlyName = descriptor.friendlyName || null;\n const lastReadMessageIndex = Number.isInteger(\n descriptor.lastConsumedMessageIndex\n )\n ? descriptor.lastConsumedMessageIndex\n : null;\n const uniqueName = descriptor.uniqueName || null;\n\n try {\n JSON.stringify(attributes);\n } catch (e) {\n throw new Error(\"Attributes must be a valid JSON object.\");\n }\n\n this.entityName = descriptor.channel;\n this.channelState = {\n uniqueName,\n status: \"notParticipating\",\n attributes,\n createdBy,\n dateCreated,\n dateUpdated,\n friendlyName,\n lastReadMessageIndex,\n bindings: descriptor.bindings ?? {},\n };\n\n if (descriptor.notificationLevel) {\n this.channelState.notificationLevel = descriptor.notificationLevel;\n }\n\n const participantsLinks = {\n participants: this.links.participants,\n };\n\n this.participants = new Map();\n this.participantsEntity = new Participants(\n this,\n this.participants,\n participantsLinks,\n this.configuration,\n this.services\n );\n this.participantsEntity.on(\"participantJoined\", (participant) =>\n this.emit(\"participantJoined\", participant)\n );\n this.participantsEntity.on(\"participantLeft\", (participant) =>\n this.emit(\"participantLeft\", participant)\n );\n this.participantsEntity.on(\n \"participantUpdated\",\n (args: ParticipantUpdatedEventArgs) =>\n this.emit(\"participantUpdated\", args)\n );\n\n this.messagesEntity = new Messages(this, configuration, services);\n this.messagesEntity.on(\"messageAdded\", (message) =>\n this._onMessageAdded(message)\n );\n this.messagesEntity.on(\"messageUpdated\", (args: MessageUpdatedEventArgs) =>\n this.emit(\"messageUpdated\", args)\n );\n this.messagesEntity.on(\"messageRemoved\", (message) =>\n this.emit(\"messageRemoved\", message)\n );\n }\n\n /**\n * Fired when a participant has joined the conversation.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - participant that joined the conversation\n * @event\n */\n static readonly participantJoined = \"participantJoined\";\n\n /**\n * Fired when a participant has left the conversation.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - participant that left the conversation\n * @event\n */\n static readonly participantLeft = \"participantLeft\";\n\n /**\n * Fired when data of a participant has been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the following properties:\n * * {@link Participant} `participant` - participant that has received the update\n * * {@link ParticipantUpdateReason}[] `updateReasons` - array of reasons for update\n * @event\n */\n static readonly participantUpdated = \"participantUpdated\";\n\n /**\n * Fired when a new message has been added to the conversation.\n *\n * Parameters:\n * 1. {@link Message} `message` - message that has been added\n * @event\n */\n static readonly messageAdded = \"messageAdded\";\n\n /**\n * Fired when message is removed from the conversation's message list.\n *\n * Parameters:\n * 1. {@link Message} `message` - message that has been removed\n * @event\n */\n static readonly messageRemoved = \"messageRemoved\";\n\n /**\n * Fired when data of a message has been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the following properties:\n * * {@link Message} `message` - message that has received the update\n * * {@link MessageUpdateReason}[] `updateReasons` - array of reasons for update\n * @event\n */\n static readonly messageUpdated = \"messageUpdated\";\n\n /**\n * Fired when a participant has stopped typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant that has stopped typing\n * @event\n */\n static readonly typingEnded = \"typingEnded\";\n\n /**\n * Fired when a participant has started typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant that has started typing\n * @event\n */\n static readonly typingStarted = \"typingStarted\";\n\n /**\n * Fired when the data of the conversation has been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the following properties:\n * * {@link Conversation} `conversation` - conversation that has received the update\n * * {@link ConversationUpdateReason}[] `updateReasons` - array of reasons for update\n * @event\n */\n static readonly updated = \"updated\";\n\n /**\n * Fired when the conversation was destroyed or the currently-logged-in user has left private conversation.\n *\n * Parameters:\n * 1. {@link Conversation} `conversation` - conversation that has been removed\n * @event\n */\n static readonly removed = \"removed\";\n\n /**\n * Unique name of the conversation.\n */\n public get uniqueName(): string | null {\n return this.channelState.uniqueName;\n }\n\n /**\n * Status of the conversation.\n */\n public get status(): ConversationStatus {\n return this.channelState.status;\n }\n\n /**\n * Name of the conversation.\n */\n public get friendlyName(): string | null {\n return this.channelState.friendlyName;\n }\n\n /**\n * Date this conversation was last updated on.\n */\n public get dateUpdated(): Date | null {\n return this.channelState.dateUpdated;\n }\n\n /**\n * Date this conversation was created on.\n */\n public get dateCreated(): Date | null {\n return this.channelState.dateCreated;\n }\n\n /**\n * Identity of the user that created this conversation.\n */\n public get createdBy(): string {\n return this.channelState.createdBy ?? \"\";\n }\n\n /**\n * Custom attributes of the conversation.\n */\n public get attributes(): JSONValue {\n return this.channelState.attributes;\n }\n\n /**\n * Index of the last message the user has read in this conversation.\n */\n public get lastReadMessageIndex(): number | null {\n return this.channelState.lastReadMessageIndex;\n }\n\n /**\n * Last message sent to this conversation.\n */\n public get lastMessage(): LastMessage | undefined {\n return this.channelState.lastMessage ?? undefined;\n }\n\n /**\n * User notification level for this conversation.\n */\n public get notificationLevel(): NotificationLevel {\n return this.channelState.notificationLevel ?? \"default\";\n }\n\n public get bindings(): ConversationBindings {\n return this.channelState.bindings;\n }\n\n /**\n * Current conversation limits.\n */\n public get limits(): ConversationLimits {\n return this.configuration.limits;\n }\n\n /**\n * State of the conversation.\n */\n public get state(): ConversationState | undefined {\n return this.channelState.state;\n }\n\n /**\n * Load and subscribe to this conversation and do not subscribe to its participants and messages.\n * This or _subscribeStreams will need to be called before any events on conversation will fire.\n * @internal\n */\n _subscribe() {\n return (this.entityPromise =\n this.entityPromise ??\n this.services.syncClient\n .document({ id: this.entityName, mode: \"open_existing\" })\n .then((entity) => {\n this.entity = entity;\n this.entity.on(\"updated\", (args) => {\n this._update(args.data);\n });\n this.entity.on(\"removed\", () => this.emit(\"removed\", this));\n this._update(this.entity.data);\n return entity;\n })\n .catch((err) => {\n this.entity = null;\n this.entityPromise = null;\n if (this.services.syncClient.connectionState != \"disconnected\") {\n log.error(\"Failed to get conversation object\", err);\n }\n log.debug(\"ERROR: Failed to get conversation object\", err);\n throw err;\n }));\n }\n\n /**\n * Load the attributes of this conversation and instantiate its participants and messages.\n * This or _subscribe will need to be called before any events on the conversation will fire.\n * This will need to be called before any events on participants or messages will fire\n * @internal\n */\n async _subscribeStreams() {\n try {\n await this._subscribe();\n log.trace(\"_subscribeStreams, this.entity.data=\", this.entity?.data);\n const messagesObjectName = (this.entity?.data as Record<string, string>)\n .messages;\n const rosterObjectName = (this.entity?.data as Record<string, string>)\n .roster;\n await Promise.all([\n this.messagesEntity.subscribe(messagesObjectName),\n this.participantsEntity.subscribe(rosterObjectName),\n ]);\n } catch (err) {\n if (this.services.syncClient.connectionState !== \"disconnected\") {\n log.error(\"Failed to subscribe on conversation objects\", this.sid, err);\n }\n log.debug(\n \"ERROR: Failed to subscribe on conversation objects\",\n this.sid,\n err\n );\n throw err;\n }\n }\n\n /**\n * Stop listening for and firing events on this conversation.\n * @internal\n */\n async _unsubscribe() {\n if (this.entity) {\n await this.entity.close();\n this.entity = null;\n this.entityPromise = null;\n }\n\n return Promise.all([\n this.participantsEntity.unsubscribe(),\n this.messagesEntity.unsubscribe(),\n ]);\n }\n\n /**\n * Set conversation status.\n * @internal\n */\n _setStatus(status: ConversationStatus, source: ConversationsDataSource) {\n this.statusSource = source;\n\n if (this.channelState.status === status) {\n return;\n }\n\n this.channelState.status = status;\n\n if (status === \"joined\") {\n this._subscribeStreams().catch((err) => {\n log.debug(\"ERROR while setting conversation status \" + status, err);\n if (this.services.syncClient.connectionState !== \"disconnected\") {\n throw err;\n }\n });\n } else if (this.entityPromise) {\n this._unsubscribe().catch((err) => {\n log.debug(\"ERROR while setting conversation status \" + status, err);\n if (this.services.syncClient.connectionState !== \"disconnected\") {\n throw err;\n }\n });\n }\n }\n\n /**\n * Get the source of the conversation update.\n * @internal\n */\n _statusSource(): ConversationsDataSource {\n return this.statusSource;\n }\n\n private static preprocessUpdate(update, conversationSid) {\n try {\n if (typeof update.attributes === \"string\") {\n update.attributes = JSON.parse(update.attributes);\n } else if (update.attributes) {\n JSON.stringify(update.attributes);\n }\n } catch (e) {\n log.warn(\n \"Retrieved malformed attributes from the server for conversation: \" +\n conversationSid\n );\n update.attributes = {};\n }\n\n try {\n if (update.dateCreated) {\n update.dateCreated = new Date(update.dateCreated);\n }\n } catch (e) {\n log.warn(\n \"Retrieved malformed dateCreated from the server for conversation: \" +\n conversationSid\n );\n delete update.dateCreated;\n }\n\n try {\n if (update.dateUpdated) {\n update.dateUpdated = new Date(update.dateUpdated);\n }\n } catch (e) {\n log.warn(\n \"Retrieved malformed dateUpdated from the server for conversation: \" +\n conversationSid\n );\n delete update.dateUpdated;\n }\n\n try {\n if (update.lastMessage && update.lastMessage.timestamp) {\n update.lastMessage.timestamp = new Date(update.lastMessage.timestamp);\n }\n } catch (e) {\n log.warn(\n \"Retrieved malformed lastMessage.timestamp from the server for conversation: \" +\n conversationSid\n );\n delete update.lastMessage.timestamp;\n }\n }\n\n /**\n * Update the local conversation object with new values.\n * @internal\n */\n _update(update) {\n log.trace(\"_update\", update);\n\n Conversation.preprocessUpdate(update, this.sid);\n const updateReasons = new Set<ConversationUpdateReason>();\n\n for (const key of Object.keys(update)) {\n const localKey = fieldMappings[key];\n\n if (!localKey) {\n continue;\n }\n\n switch (localKey) {\n case fieldMappings.status:\n if (\n !update.status ||\n update.status === \"unknown\" ||\n this.channelState.status === update.status\n ) {\n break;\n }\n\n this.channelState.status = update.status;\n updateReasons.add(localKey);\n\n break;\n case fieldMappings.attributes:\n if (isEqual(this.channelState.attributes, update.attributes)) {\n break;\n }\n\n this.channelState.attributes = update.attributes;\n updateReasons.add(localKey);\n\n break;\n case fieldMappings.lastConsumedMessageIndex:\n if (\n update.lastConsumedMessageIndex === undefined ||\n update.lastConsumedMessageIndex ===\n this.channelState.lastReadMessageIndex\n ) {\n break;\n }\n\n this.channelState.lastReadMessageIndex =\n update.lastConsumedMessageIndex;\n updateReasons.add(\"lastReadMessageIndex\");\n\n break;\n case fieldMappings.lastMessage:\n if (this.channelState.lastMessage && !update.lastMessage) {\n delete this.channelState.lastMessage;\n updateReasons.add(localKey);\n\n break;\n }\n\n this.channelState.lastMessage = this.channelState.lastMessage || {};\n\n if (\n update.lastMessage?.index !== undefined &&\n update.lastMessage.index !== this.channelState.lastMessage.index\n ) {\n this.channelState.lastMessage.index = update.lastMessage.index;\n updateReasons.add(localKey);\n }\n\n if (\n update.lastMessage?.timestamp !== undefined &&\n this.channelState.lastMessage?.dateCreated?.getTime() !==\n update.lastMessage.timestamp.getTime()\n ) {\n this.channelState.lastMessage.dateCreated =\n update.lastMessage.timestamp;\n updateReasons.add(localKey);\n }\n\n if (isEqual(this.channelState.lastMessage, {})) {\n delete this.channelState.lastMessage;\n }\n\n break;\n case fieldMappings.state:\n const state = update.state || undefined;\n\n if (state !== undefined) {\n state.dateUpdated = new Date(state.dateUpdated);\n }\n\n if (isEqual(this.channelState.state, state)) {\n break;\n }\n\n this.channelState.state = state;\n updateReasons.add(localKey);\n\n break;\n case fieldMappings.bindings:\n if (isEqual(this.channelState.bindings, update.bindings)) {\n break;\n }\n\n this.channelState.bindings = update.bindings;\n updateReasons.add(localKey);\n\n break;\n default:\n const isDate = update[key] instanceof Date;\n const keysMatchAsDates =\n isDate &&\n this.channelState[localKey]?.getTime() === update[key].getTime();\n const keysMatchAsNonDates = !isDate && this[localKey] === update[key];\n\n if (keysMatchAsDates || keysMatchAsNonDates) {\n break;\n }\n\n this.channelState[localKey] = update[key];\n updateReasons.add(localKey);\n }\n }\n\n if (updateReasons.size > 0) {\n this.emit(\"updated\", {\n conversation: this,\n updateReasons: [...updateReasons],\n });\n }\n }\n\n /**\n * @internal\n */\n private _onMessageAdded(message) {\n for (const participant of this.participants.values()) {\n if (participant.identity === message.author) {\n participant._endTyping();\n break;\n }\n }\n this.emit(\"messageAdded\", message);\n }\n\n private async _setLastReadMessageIndex(\n index: number | null\n ): Promise<number> {\n const result = await this.services.commandExecutor.mutateResource<\n EditLastReadMessageIndexRequest,\n EditLastReadMessageIndexResponse\n >(\"post\", `${this.configuration.links.myConversations}/${this.sid}`, {\n last_read_message_index: index,\n });\n\n return result.unread_messages_count;\n }\n\n /**\n * Add a participant to the conversation by its identity.\n * @param identity Identity of the Client to add.\n * @param attributes Attributes to be attached to the participant.\n */\n @validateTypesAsync(nonEmptyString, optionalAttributesValidator)\n async add(\n identity: string,\n attributes?: JSONValue\n ): Promise<ParticipantResponse> {\n return this.participantsEntity.add(identity, attributes ?? {});\n }\n\n /**\n * Add a non-chat participant to the conversation.\n * @param proxyAddress Proxy (Twilio) address of the participant.\n * @param address User address of the participant.\n * @param attributes Attributes to be attached to the participant.\n * @param bindingOptions Options for adding email participants - name and CC/To level.\n */\n @validateTypesAsync(\n nonEmptyString,\n nonEmptyString,\n optionalAttributesValidator\n )\n async addNonChatParticipant(\n proxyAddress: string,\n address: string,\n attributes: JSONValue = {},\n bindingOptions: ParticipantBindingOptions = {}\n ): Promise<ParticipantResponse> {\n return this.participantsEntity.addNonChatParticipant(\n proxyAddress,\n address,\n attributes ?? {},\n bindingOptions ?? {}\n );\n }\n\n /**\n * Advance the conversation's last read message index to the current read horizon.\n * Rejects if the user is not a participant of the conversation.\n * Last read message index is updated only if the new index value is higher than the previous.\n * @param index Message index to advance to.\n * @return Resulting unread messages count in the conversation.\n */\n @validateTypesAsync(nonNegativeInteger)\n async advanceLastReadMessageIndex(index: number): Promise<number> {\n await this._subscribeStreams();\n\n if (index < (this.lastReadMessageIndex || 0)) {\n return await this._setLastReadMessageIndex(this.lastReadMessageIndex);\n }\n\n return await this._setLastReadMessageIndex(index);\n }\n\n /**\n * Delete the conversation and unsubscribe from its events.\n */\n async delete(): Promise<Conversation> {\n await this.services.commandExecutor.mutateResource(\n \"delete\",\n this.links.self\n );\n\n return this;\n }\n\n /**\n * Get the custom attributes of this Conversation.\n */\n async getAttributes(): Promise<JSONValue> {\n await this._subscribe();\n return this.attributes;\n }\n\n /**\n * Returns messages from the conversation using the paginator interface.\n * @param pageSize Number of messages to return in a single chunk. Default is 30.\n * @param anchor Index of the newest message to fetch. Default is from the end.\n * @param direction Query direction. By default it queries backwards\n * from newer to older. The `\"forward\"` value will query in the opposite direction.\n * @return A page of messages.\n */\n @validateTypesAsync(\n [\"undefined\", nonNegativeInteger],\n [\"undefined\", nonNegativeInteger],\n [\"undefined\", literal(\"backwards\", \"forward\")]\n )\n async getMessages(\n pageSize?: number,\n anchor?: number,\n direction?: \"backwards\" | \"forward\"\n ): Promise<Paginator<Message>> {\n await this._subscribeStreams();\n return this.messagesEntity.getMessages(pageSize, anchor, direction);\n }\n\n /**\n * Get a list of all the participants who are joined to this conversation.\n */\n async getParticipants(): Promise<Participant[]> {\n await this._subscribeStreams();\n return this.participantsEntity.getParticipants();\n }\n\n /**\n * Get conversation participants count.\n *\n * This method is semi-realtime. This means that this data will be eventually correct,\n * but will also be possibly incorrect for a few seconds. The Conversations system does not\n * provide real time events for counter values changes.\n *\n * This is useful for any UI badges, but it is not recommended to build any core application\n * logic based on these counters being accurate in real time.\n */\n async getParticipantsCount(): Promise<number> {\n const url = new UriBuilder(this.configuration.links.conversations)\n .path(this.sid)\n .build();\n const response = await this.services.network.get<ConversationResponse>(url);\n\n return response.body.participants_count ?? 0;\n }\n\n /**\n * Get a participant by its SID.\n * @param participantSid Participant SID.\n */\n @validateTypesAsync(nonEmptyString)\n async getParticipantBySid(\n participantSid: string\n ): Promise<Participant | null> {\n return this.participantsEntity.getParticipantBySid(participantSid);\n }\n\n /**\n * Get a participant by its identity.\n * @param identity Participant identity.\n */\n @validateTypesAsync(nonEmptyString)\n async getParticipantByIdentity(\n identity: string | null = \"\"\n ): Promise<Participant | null> {\n return this.participantsEntity.getParticipantByIdentity(identity ?? \"\");\n }\n\n /**\n * Get the total message count in the conversation.\n *\n * This method is semi-realtime. This means that this data will be eventually correct,\n * but will also be possibly incorrect for a few seconds. The Conversations system does not\n * provide real time events for counter values changes.\n *\n * This is useful for any UI badges, but it is not recommended to build any core application\n * logic based on these counters being accurate in real time.\n */\n async getMessagesCount(): Promise<number> {\n const url = new UriBuilder(this.configuration.links.conversations)\n .path(this.sid)\n .build();\n const response = await this.services.network.get<ConversationResponse>(url);\n\n return response.body.messages_count ?? 0;\n }\n\n /**\n * Get unread messages count for the user if they are a participant of this conversation.\n * Rejects if the user is not a participant of the conversation.\n *\n * Use this method to obtain the number of unread messages together with\n * {@link Conversation.updateLastReadMessageIndex} instead of relying on the\n * message indices which may have gaps. See {@link Message.index} for details.\n *\n * This method is semi-realtime. This means that this data will be eventually correct,\n * but will also be possibly incorrect for a few seconds. The Conversations system does not\n * provide real time events for counter values changes.\n *\n * This is useful for any UI badges, but it is not recommended to build any core application\n * logic based on these counters being accurate in real time.\n */\n async getUnreadMessagesCount(): Promise<number | null> {\n const url = new UriBuilder(this.configuration.links.myConversations)\n .path(this.sid)\n .build();\n const response = await this.services.network.get<ConversationResponse>(url);\n\n if (response.body.conversation_sid !== this.sid) {\n throw new Error(\n \"Conversation was not found in the user conversations list\"\n );\n }\n\n const unreadMessageCount = response.body.unread_messages_count;\n\n if (typeof unreadMessageCount === \"number\") {\n return unreadMessageCount;\n }\n\n return null;\n }\n\n /**\n * Join the conversation and subscribe to its events.\n */\n async join(): Promise<Conversation> {\n await this.services.commandExecutor.mutateResource<\n AddParticipantRequest,\n ParticipantResponse\n >(\"post\", this.links.participants, {\n identity: this.configuration.userIdentity,\n });\n\n return this;\n }\n\n /**\n * Leave the conversation.\n */\n async leave(): Promise<Conversation> {\n if (this.channelState.status === \"joined\") {\n await this.services.commandExecutor.mutateResource(\n \"delete\",\n `${this.links.participants}/${this.configuration.userIdentity}`\n );\n }\n\n return this;\n }\n\n /**\n * Remove a participant from the conversation. When a string is passed as the\n * argument, it will assume that the string is an identity or SID.\n * @param participant Identity, SID or the participant object to remove.\n */\n /* eslint-disable @typescript-eslint/ban-ts-comment */\n // @ts-ignore TODO: fix validateTypesAsync typing\n @validateTypesAsync([nonEmptyString, Participant])\n async removeParticipant(participant: string | Participant): Promise<void> {\n await this.participantsEntity.remove(\n typeof participant === \"string\" ? participant : participant.sid\n );\n }\n\n /**\n * Send a message to the conversation.\n * @param message Message body for the text message,\n * `FormData` or {@link SendMediaOptions} for media content. Sending FormData is supported only with the browser engine.\n * @param messageAttributes Attributes for the message.\n * @param emailOptions Email options for the message.\n * @return Index of the new message.\n */\n @validateTypesAsync(\n [\n \"string\",\n literal(null),\n // Wrapping it into a custom rule is necessary because the FormData class is not available on initialization.\n custom((value) => [value instanceof FormData, \"an instance of FormData\"]),\n objectSchema(\"media options\", {\n contentType: nonEmptyString,\n media: custom((value) => {\n let isValid =\n (typeof value === \"string\" && value.length > 0) ||\n value instanceof Uint8Array ||\n value instanceof ArrayBuffer;\n\n if (typeof Blob === \"function\") {\n isValid = isValid || value instanceof Blob;\n }\n\n return [\n isValid,\n \"a non-empty string, an instance of Buffer or an instance of Blob\",\n ];\n }),\n }),\n ],\n optionalAttributesValidator,\n [\n \"undefined\",\n literal(null),\n objectSchema(\"email attributes\", {\n subject: [nonEmptyString, \"undefined\"],\n }),\n ]\n )\n async sendMessage(\n message: null | string | FormData | SendMediaOptions,\n messageAttributes?: JSONValue,\n emailOptions?: SendEmailOptions\n ): Promise<number> {\n if (typeof message === \"string\" || message === null) {\n const response = await this.messagesEntity.send(\n message,\n messageAttributes,\n emailOptions\n );\n return parseToNumber(response.index) ?? 0;\n }\n\n const response = await this.messagesEntity.sendMedia(\n message,\n messageAttributes,\n emailOptions\n );\n return parseToNumber(response.index) ?? 0;\n }\n\n /**\n * New interface to prepare for sending a message.\n * Use instead of `sendMessage`.\n * @return A MessageBuilder to help set all message sending options.\n */\n public prepareMessage(): MessageBuilder {\n return new MessageBuilder(this.limits, this.messagesEntity);\n }\n\n /**\n * Set last read message index of the conversation to the index of the last known message.\n * @return Resulting unread messages count in the conversation.\n */\n public async setAllMessagesRead(): Promise<number> {\n await this._subscribeStreams();\n\n const messagesPage = await this.getMessages(1);\n\n if (messagesPage.items.length > 0) {\n return this.advanceLastReadMessageIndex(messagesPage.items[0].index);\n }\n\n return Promise.resolve(0);\n }\n\n /**\n * Set all messages in the conversation unread.\n * @return Resulting unread messages count in the conversation.\n */\n public async setAllMessagesUnread(): Promise<number> {\n await this._subscribeStreams();\n return await this._setLastReadMessageIndex(null);\n }\n\n /**\n * Set user notification level for this conversation.\n * @param notificationLevel New user notification level.\n */\n @validateTypesAsync(literal(\"default\", \"muted\"))\n async setUserNotificationLevel(\n notificationLevel: NotificationLevel\n ): Promise<void> {\n await this.services.commandExecutor.mutateResource<EditNotificationLevelRequest>(\n \"post\",\n `${this.configuration.links.myConversations}/${this.sid}`,\n {\n notification_level: notificationLevel,\n }\n );\n }\n\n /**\n * Send a notification to the server indicating that this client is currently typing in this conversation.\n * Typing ended notification is sent after a while automatically, but by calling this method again you ensure that typing ended is not received.\n */\n typing(): Promise<void> {\n return this.services.typingIndicator.send(this.sid);\n }\n\n /**\n * Update the attributes of the conversation.\n * @param attributes New attributes.\n */\n @validateTypesAsync(attributesValidator)\n async updateAttributes(attributes: JSONValue): Promise<Conversation> {\n await this.services.commandExecutor.mutateResource<\n EditConversationRequest,\n ConversationResponse\n >(\"post\", this.links.self, {\n attributes:\n attributes !== undefined ? JSON.stringify(attributes) : undefined,\n });\n\n return this;\n }\n\n /**\n * Update the friendly name of the conversation.\n * @param friendlyName New friendly name.\n */\n @validateTypesAsync([\"string\"])\n async updateFriendlyName(friendlyName: string): Promise<Conversation> {\n if (this.channelState.friendlyName !== friendlyName) {\n await this.services.commandExecutor.mutateResource<\n EditConversationRequest,\n ConversationResponse\n >(\"post\", this.links.self, { friendly_name: friendlyName });\n }\n\n return this;\n }\n\n /**\n * Set the last read message index to the current read horizon.\n * @param index Message index to set as last read.\n * If null is provided, then the behavior is identical to {@link Conversation.setAllMessagesUnread}.\n * @returns Resulting unread messages count in the conversation.\n */\n @validateTypesAsync([literal(null), nonNegativeInteger])\n async updateLastReadMessageIndex(index: number | null): Promise<number> {\n await this._subscribeStreams();\n return this._setLastReadMessageIndex(index);\n }\n\n /**\n * Update the unique name of the conversation.\n * @param uniqueName New unique name for the conversation. Setting unique name to null removes it.\n */\n @validateTypesAsync([\"string\", literal(null)])\n async updateUniqueName(uniqueName: string | null): Promise<Conversation> {\n if (this.channelState.uniqueName !== uniqueName) {\n if (!uniqueName) {\n uniqueName = \"\";\n }\n\n await this.services.commandExecutor.mutateResource<\n EditConversationRequest,\n ConversationResponse\n >(\"post\", this.links.self, {\n unique_name: uniqueName,\n });\n }\n\n return this;\n }\n}\n\nexport {\n ConversationDescriptor,\n Conversation,\n ConversationUpdateReason,\n ConversationStatus,\n NotificationLevel,\n ConversationState,\n ConversationUpdatedEventArgs,\n SendMediaOptions,\n SendEmailOptions,\n LastMessage,\n ConversationBindings,\n ConversationEmailBinding,\n};\n","class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve;\n private _reject;\n\n public current!: T;\n\n constructor() {\n this._promise = new Promise<T>((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n public get promise(): Promise<T> {\n return this._promise;\n }\n\n update(value: T) {\n this._resolve(value);\n }\n\n set(value: T) {\n this.current = value;\n this._resolve(value);\n }\n\n fail(e) {\n this._reject(e);\n }\n}\n\nexport { Deferred };\n","import { Logger } from \"../logger\";\nimport {\n Conversation,\n ConversationDescriptor,\n ConversationUpdatedEventArgs,\n ConversationUpdateReason,\n} from \"../conversation\";\nimport { SyncMap, SyncClient, SyncMapItem } from \"twilio-sync\";\nimport { Users } from \"./users\";\nimport { Network } from \"../services/network\";\nimport { TypingIndicator } from \"../services/typing-indicator\";\nimport { McsClient } from \"@twilio/mcs-client\";\nimport { Deferred } from \"../util/deferred\";\nimport {\n Participant,\n ParticipantUpdatedEventArgs,\n ParticipantUpdateReason,\n} from \"../participant\";\nimport {\n Message,\n MessageUpdatedEventArgs,\n MessageUpdateReason,\n} from \"../message\";\nimport { UriBuilder } from \"../util\";\nimport { Configuration } from \"../configuration\";\nimport { CommandExecutor } from \"../command-executor\";\nimport { CreateConversationRequest } from \"../interfaces/commands/create-conversation\";\nimport { ConversationResponse } from \"../interfaces/commands/conversation-response\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport isEqual from \"lodash.isequal\";\nimport { ResponseMeta } from \"../interfaces/commands/response-meta\";\n\ntype ConversationsEvents = {\n conversationAdded: (conversation: Conversation) => void;\n conversationJoined: (conversation: Conversation) => void;\n conversationLeft: (conversation: Conversation) => void;\n conversationRemoved: (conversation: Conversation) => void;\n conversationUpdated: (data: {\n conversation: Conversation;\n updateReasons: ConversationUpdateReason[];\n }) => void;\n participantJoined: (participant: Participant) => void;\n participantLeft: (participant: Participant) => void;\n participantUpdated: (data: {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n }) => void;\n messageAdded: (message: Message) => void;\n messageRemoved: (message: Message) => void;\n messageUpdated: (data: {\n message: Message;\n updateReasons: MessageUpdateReason[];\n }) => void;\n typingEnded: (participant: Participant) => void;\n typingStarted: (participant: Participant) => void;\n};\n\ntype ConversationsDataSource = \"sync\" | \"chat\" | \"rest\";\n\ninterface ConversationsServices {\n syncClient: SyncClient;\n users: Users;\n typingIndicator: TypingIndicator;\n network: Network;\n mcsClient: McsClient;\n commandExecutor: CommandExecutor;\n}\n\ntype ConversationRestData = {\n roster: string;\n notificationLevel: \"default\" | \"muted\";\n lastConsumedMessageIndex: number;\n channel: string;\n messages: string;\n descriptor: ConversationResponse;\n channel_sid: string;\n status: string;\n};\n\nconst log = Logger.scope(\"Conversations\");\n\n/**\n * Represents conversations collection\n * {@see Conversation}\n */\nclass Conversations extends ReplayEventEmitter<ConversationsEvents> {\n public readonly conversations: Map<string, Conversation> = new Map();\n public readonly myConversationsRead: Deferred<boolean> = new Deferred();\n private readonly configuration: Configuration;\n private readonly services: ConversationsServices;\n private readonly tombstones: Set<string> = new Set();\n private myConversationsFetched = false;\n\n public constructor(\n configuration: Configuration,\n services: ConversationsServices\n ) {\n super();\n\n this.configuration = configuration;\n this.services = services;\n }\n\n public async addConversation(options): Promise<Conversation> {\n const attributes =\n typeof options?.attributes !== \"undefined\" ? options.attributes : {};\n\n const response = await this.services.commandExecutor.mutateResource<\n CreateConversationRequest,\n ConversationResponse\n >(\"post\", this.configuration.links.conversations, {\n friendly_name: options.friendlyName,\n unique_name: options.uniqueName,\n attributes:\n typeof attributes !== \"undefined\"\n ? JSON.stringify(attributes)\n : undefined,\n });\n\n const conversationSid = response.sid ?? null;\n const conversationDocument = response.sync_objects?.conversation ?? null;\n const links = {\n self: response.url,\n ...response.links,\n };\n const existingConversation = this.conversations.get(conversationSid);\n\n if (existingConversation) {\n await existingConversation._subscribe();\n return existingConversation;\n }\n\n const conversation = new Conversation(\n {\n channel: conversationDocument,\n entityName: \"\",\n uniqueName: \"\",\n attributes: null,\n createdBy: \"\",\n friendlyName: \"\",\n lastConsumedMessageIndex: 0,\n dateCreated: null,\n dateUpdated: null,\n },\n conversationSid,\n links,\n this.configuration,\n this.services\n );\n\n this.conversations.set(conversation.sid, conversation);\n this._registerForEvents(conversation);\n\n await conversation._subscribe();\n this.emit(\"conversationAdded\", conversation);\n\n return conversation;\n }\n\n /**\n * Fetch conversations list and instantiate all necessary objects\n */\n public async fetchConversations(): Promise<Conversations> {\n try {\n const map = await this._getMap();\n\n map.on(\"itemAdded\", (args) => {\n log.debug(`itemAdded: ${args.item.key}`);\n\n this._upsertConversation(\"sync\", args.item.key, args.item.data);\n });\n\n map.on(\"itemRemoved\", (args) => {\n log.debug(`itemRemoved: ${args.key}`);\n\n const sid = args.key;\n\n if (!this.myConversationsFetched) {\n this.tombstones.add(sid);\n }\n\n const conversation = this.conversations.get(sid);\n\n if (!conversation) {\n return;\n }\n\n if (conversation.status === \"joined\") {\n conversation._setStatus(\"notParticipating\", \"sync\");\n this.emit(\"conversationLeft\", conversation);\n }\n\n this.conversations.delete(sid);\n this.emit(\"conversationRemoved\", conversation);\n conversation.emit(\"removed\", conversation);\n });\n\n map.on(\"itemUpdated\", (args) => {\n log.debug(`itemUpdated: ${args.item.key}`);\n\n this._upsertConversation(\"sync\", args.item.key, args.item.data);\n });\n\n const myConversations: ConversationRestData[] =\n await this._fetchMyConversations();\n const upserts: Promise<Conversation | null>[] = [];\n\n for (const conversation of myConversations) {\n upserts.push(\n this._upsertConversation(\n \"rest\",\n conversation[\"channel_sid\"],\n conversation\n )\n );\n }\n\n this.myConversationsRead.set(true);\n\n await Promise.all(upserts);\n\n this.myConversationsFetched = true;\n this.tombstones.clear();\n\n log.debug(\"The conversations list has been successfully fetched\");\n\n return this;\n } catch (error) {\n const errorMessage = \"Failed to fetch the conversations list\";\n\n if (this.services.syncClient.connectionState !== \"disconnected\") {\n log.error(errorMessage, error);\n }\n\n log.debug(`ERROR: ${errorMessage}`, error);\n\n throw error;\n }\n }\n\n public async getConversations() {\n const conversationsMap = await this._getMap();\n const page = await conversationsMap.getItems();\n\n return this._wrapPaginator(page, (items) =>\n Promise.all(\n items.map((item: SyncMapItem) =>\n this._upsertConversation(\"sync\", item.key, item.data)\n )\n )\n );\n }\n\n public async getConversation(\n sid: string\n ): Promise<Conversation | undefined | null> {\n const conversationsMap = await this._getMap();\n const page = await conversationsMap.getItems({ key: sid });\n const items = page.items.map((item: SyncMapItem) =>\n this._upsertConversation(\"sync\", item.key, item.data)\n );\n\n return items.length > 0 ? items[0] : null;\n }\n\n public async getConversationByUniqueName(\n uniqueName: string\n ): Promise<Conversation | null> {\n const url = new UriBuilder(this.configuration.links.myConversations)\n .path(uniqueName)\n .build();\n const response = await this.services.network.get<ConversationResponse>(url);\n const body = response.body;\n\n const sid = body.conversation_sid;\n const data = {\n entityName: null,\n lastConsumedMessageIndex: body.last_read_message_index,\n status: body?.status || \"unknown\",\n friendlyName: body.friendly_name,\n dateUpdated: body.date_updated,\n dateCreated: body.date_created,\n uniqueName: body.unique_name,\n createdBy: body.created_by,\n attributes: body.attributes,\n channel: body.sync_objects.conversation,\n notificationLevel: body?.notification_level,\n sid,\n };\n\n return sid ? this._upsertConversation(\"sync\", sid, data) : null;\n }\n\n public async peekConversation(sid: string): Promise<Conversation | null> {\n const url = new UriBuilder(this.configuration.links.conversations)\n .path(sid)\n .build();\n const response = await this.services.network.get<ConversationResponse>(url);\n const body = response.body;\n\n const data = {\n entityName: null,\n // lastConsumedMessageIndex: body.last_read_message_index,\n status: body?.status || \"unknown\",\n friendlyName: body.friendly_name,\n dateUpdated: body.date_updated,\n dateCreated: body.date_created,\n uniqueName: body.unique_name,\n createdBy: body.created_by,\n attributes: body.attributes,\n channel: `${sid}.channel`,\n // notificationLevel: body?.notification_level,\n sid,\n };\n\n return this._upsertConversation(\"sync\", sid, data);\n }\n\n private async _getMap(): Promise<SyncMap> {\n return await this.services.syncClient.map({\n id: this.configuration.myConversations,\n mode: \"open_existing\",\n });\n }\n\n private async _wrapPaginator(page, op) {\n const items = await op(page.items);\n\n return {\n items,\n hasNextPage: page.hasNextPage,\n hasPrevPage: page.hasPrevPage,\n nextPage: () => page.nextPage().then((x) => this._wrapPaginator(x, op)),\n prevPage: () => page.prevPage().then((x) => this._wrapPaginator(x, op)),\n };\n }\n\n private async _updateConversation(\n source: ConversationsDataSource,\n conversation: Conversation,\n data\n ): Promise<void> {\n const areSourcesDifferent =\n conversation._statusSource() !== undefined &&\n source !== conversation._statusSource();\n const isChannelSourceSync =\n source !== \"rest\" || conversation._statusSource() === \"sync\";\n\n if (areSourcesDifferent && isChannelSourceSync && source !== \"sync\") {\n log.trace(\n \"upsertConversation: conversation is known from sync and came from chat, ignoring\",\n {\n sid: conversation.sid,\n data: data.status,\n conversation: conversation.status,\n }\n );\n\n return;\n }\n\n if (data.status === \"joined\" && conversation.status !== \"joined\") {\n conversation._setStatus(\"joined\", source);\n\n const updateData: Partial<ConversationDescriptor> = {};\n\n if (typeof data.notificationLevel !== \"undefined\") {\n updateData.notificationLevel = data.notificationLevel;\n }\n\n if (typeof data.lastConsumedMessageIndex !== \"undefined\") {\n updateData.lastConsumedMessageIndex = data.lastConsumedMessageIndex;\n }\n\n if (!isEqual(updateData, {})) {\n conversation._update(updateData);\n }\n\n conversation._subscribe().then(() => {\n this.emit(\"conversationJoined\", conversation);\n });\n\n return;\n }\n\n if (\n data.status === \"notParticipating\" &&\n conversation.status === \"joined\"\n ) {\n conversation._setStatus(\"notParticipating\", source);\n conversation._update(data);\n await conversation._subscribe();\n this.emit(\"conversationLeft\", conversation);\n\n return;\n }\n\n if (data.status === \"notParticipating\") {\n await conversation._subscribe();\n\n return;\n }\n\n conversation._update(data);\n }\n\n private async _upsertConversation(\n source: ConversationsDataSource,\n sid: string,\n data\n ): Promise<Conversation | null> {\n log.trace(`upsertConversation called for ${sid}`, data);\n\n const conversation = this.conversations.get(sid);\n\n // If the channel is known, update it\n if (conversation) {\n log.trace(\n `upsertConversation: the conversation ${conversation.sid} is known;` +\n `its status is known from the source ${conversation._statusSource()} ` +\n `and the update came from the source ${source}`,\n conversation\n );\n\n await this._updateConversation(source, conversation, data);\n await conversation._subscribe();\n\n return conversation;\n }\n\n // If the conversations is deleted, ignore it\n if ([\"chat\", \"rest\"].includes(source) && this.tombstones.has(sid)) {\n log.trace(\n \"upsertChannel: the channel is deleted but reappeared again from chat, ignoring\",\n sid\n );\n return null;\n }\n\n // If the conversation is unknown, fetch it\n log.trace(\n \"upsertConversation: creating a local conversation object with sid \" +\n sid,\n data\n );\n\n const baseLink = `${this.configuration.links.conversations}/${sid}`;\n const links = {\n self: baseLink,\n messages: `${baseLink}/Messages`,\n participants: `${baseLink}/Participants`,\n };\n const newConversation = new Conversation(\n data,\n sid,\n links,\n this.configuration,\n this.services\n );\n this.conversations.set(sid, newConversation);\n\n await newConversation._subscribe();\n this._registerForEvents(newConversation);\n this.emit(\"conversationAdded\", newConversation);\n\n if (data.status === \"joined\") {\n newConversation._setStatus(\"joined\", source);\n this.emit(\"conversationJoined\", newConversation);\n }\n\n return newConversation;\n }\n private async _fetchMyConversations(): Promise<ConversationRestData[]> {\n let conversations: ConversationRestData[] = [];\n let pageToken: null | string = null;\n\n do {\n const url = new UriBuilder(this.configuration.links.myConversations);\n\n if (pageToken) {\n url.arg(\"PageToken\", pageToken);\n }\n\n const response = await this.services.network.get<\n { conversations: ConversationResponse[] } & ResponseMeta\n >(url.build());\n const receivedConversations = response.body?.conversations.map(\n (conversationDescriptor) => ({\n descriptor: conversationDescriptor,\n channel_sid: conversationDescriptor.conversation_sid,\n status: conversationDescriptor.status,\n channel: conversationDescriptor.sync_objects.conversation,\n messages: conversationDescriptor.sync_objects.messages,\n roster: `${conversationDescriptor.conversation_sid}.roster`,\n lastConsumedMessageIndex:\n conversationDescriptor.last_read_message_index,\n notificationLevel: conversationDescriptor.notification_level,\n })\n );\n\n pageToken = response.body.meta.next_token;\n conversations = [...conversations, ...receivedConversations];\n } while (pageToken);\n\n return conversations;\n }\n\n private _onConversationRemoved(sid: string) {\n const conversation = this.conversations.get(sid);\n\n if (conversation) {\n this.conversations.delete(sid);\n this.emit(\"conversationRemoved\", conversation);\n }\n }\n\n private _registerForEvents(conversation) {\n conversation.on(\"removed\", () =>\n this._onConversationRemoved(conversation.sid)\n );\n conversation.on(\"updated\", (args: ConversationUpdatedEventArgs) =>\n this.emit(\"conversationUpdated\", args)\n );\n conversation.on(\"participantJoined\", (participant) =>\n this.emit(\"participantJoined\", participant)\n );\n conversation.on(\"participantLeft\", (participant) =>\n this.emit(\"participantLeft\", participant)\n );\n conversation.on(\"participantUpdated\", (args: ParticipantUpdatedEventArgs) =>\n this.emit(\"participantUpdated\", args)\n );\n conversation.on(\"messageAdded\", (message) =>\n this.emit(\"messageAdded\", message)\n );\n conversation.on(\"messageUpdated\", (args: MessageUpdatedEventArgs) =>\n this.emit(\"messageUpdated\", args)\n );\n conversation.on(\"messageRemoved\", (message) =>\n this.emit(\"messageRemoved\", message)\n );\n conversation.on(\"typingStarted\", (participant) =>\n this.emit(\"typingStarted\", participant)\n );\n conversation.on(\"typingEnded\", (participant) =>\n this.emit(\"typingEnded\", participant)\n );\n }\n}\n\nexport {\n ConversationsServices,\n ConversationsDataSource,\n Conversation,\n Conversations,\n};\n","import { User, UserUpdatedEventArgs, UserUpdateReason } from \"../user\";\nimport { Network } from \"../services/network\";\nimport { SyncClient } from \"twilio-sync\";\nimport { UriBuilder } from \"../util\";\nimport { Configuration } from \"../configuration\";\nimport { CommandExecutor } from \"../command-executor\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport { UserResponse } from \"../interfaces/commands/user\";\n\ntype UsersEvents = {\n userUpdated: (data: {\n user: User;\n updateReasons: UserUpdateReason[];\n }) => void;\n userSubscribed: (user: User) => void;\n userUnsubscribed: (user: User) => void;\n};\n\nexport interface UsersServices {\n network: Network;\n syncClient: SyncClient;\n commandExecutor: CommandExecutor;\n}\n\n/**\n * Container for known users\n */\nclass Users extends ReplayEventEmitter<UsersEvents> {\n private readonly configuration: Configuration;\n private readonly services: UsersServices;\n\n private subscribedUsers: Map<string, User>;\n private fifoStack: string[];\n public readonly myself: User;\n\n constructor(\n myself: User,\n configuration: Configuration,\n services: UsersServices\n ) {\n super();\n\n this.configuration = configuration;\n this.services = services;\n\n this.fifoStack = [];\n this.myself = myself;\n this.myself.on(\"updated\", (args: UserUpdatedEventArgs) =>\n this.emit(\"userUpdated\", args)\n );\n this.myself.on(\"userSubscribed\", () =>\n this.emit(\"userSubscribed\", this.myself)\n );\n this.myself.on(\"userUnsubscribed\", () => {\n this.emit(\"userUnsubscribed\", this.myself);\n this.myself._ensureFetched();\n });\n\n this.subscribedUsers = new Map<string, User>();\n }\n\n private handleUnsubscribeUser(user: User): void {\n if (this.subscribedUsers.has(user.identity)) {\n this.subscribedUsers.delete(user.identity);\n }\n let foundItemIndex = 0;\n const foundItem = this.fifoStack.find((item, index) => {\n if (item == user.identity) {\n foundItemIndex = index;\n return true;\n }\n return false;\n });\n if (foundItem) {\n this.fifoStack.splice(foundItemIndex, 1);\n }\n this.emit(\"userUnsubscribed\", user);\n }\n\n private handleSubscribeUser(user: User): void {\n if (this.subscribedUsers.has(user.identity)) {\n return;\n }\n if (this.fifoStack.length >= this.configuration.userInfosToSubscribe) {\n const item = this.fifoStack.shift() as string;\n this.subscribedUsers?.get(item)?.unsubscribe();\n }\n this.fifoStack.push(user.identity);\n this.subscribedUsers.set(user.identity, user);\n this.emit(\"userSubscribed\", user);\n }\n\n /**\n * Gets user, if it's in subscribed list - then return the user object from it,\n * if not - then subscribes and adds user to the FIFO stack\n * @returns {Promise<User>} Fully initialized user\n */\n async getUser(identity = \"\", entityName = \"\"): Promise<User> {\n await this.myself._ensureFetched();\n\n if (identity == this.myself.identity) {\n return this.myself;\n }\n\n const user = this.subscribedUsers.get(identity);\n\n if (user) {\n return user;\n }\n\n entityName = entityName || (await this.getSyncUniqueName(identity));\n\n const newUser = new User(\n identity,\n entityName,\n this.configuration,\n this.services\n );\n\n newUser.on(\"updated\", (args: UserUpdatedEventArgs) =>\n this.emit(\"userUpdated\", args)\n );\n newUser.on(\"userSubscribed\", () => this.handleSubscribeUser(newUser));\n newUser.on(\"userUnsubscribed\", () => this.handleUnsubscribeUser(newUser));\n await newUser._ensureFetched();\n\n return newUser;\n }\n\n /**\n * @returns {Promise<Array<User>>} returns list of subscribed User objects {@see User}\n */\n async getSubscribedUsers(): Promise<Array<User>> {\n await this.myself._ensureFetched();\n\n const users = [this.myself];\n this.subscribedUsers.forEach((user) => users.push(user));\n\n return users;\n }\n\n /**\n * @returns {Promise<string>} User's sync unique name\n */\n private async getSyncUniqueName(identity: string): Promise<string> {\n const url = new UriBuilder(this.configuration.links.users)\n .path(identity)\n .build();\n const response = await this.services.network.get<UserResponse>(url);\n return response.body?.sync_objects.user_info_map ?? \"\";\n }\n}\n\nexport { Users };\n","import { Logger } from \"../logger\";\n\nimport { Notifications } from \"@twilio/notifications\";\n\nimport { NotificationTypes } from \"../interfaces/notification-types\";\nimport { TwilsockClient } from \"twilsock\";\nimport { Configuration } from \"../configuration\";\n\nconst log = Logger.scope(\"TypingIndicator\");\n\nexport interface TypingIndicatorServices {\n twilsockClient: TwilsockClient;\n notificationClient: Notifications;\n}\n\n/**\n * An important note in regards to typing timeout timers. There are two places that the SDK can get the \"typing_timeout\" attribute from. The first\n * place that the attribute appears in is the response received from POST -> /v1/typing REST call. In the body of that response, the value of the\n * \"typing_timeout\" attribute will be exactly the same as defined in the console. The second place that the attribute appears in is from a\n * notification of type \"twilio.ipmsg.typing_indicator\". In this case, the \"typing_timeout\" value will be +1 of that in the console. This\n * intentional. The timeout returned from the POST -> /v1/typing call should be used to disable further calls for that period of time. On contrary,\n * the timeout returned from the notification should be used as the timeout for the \"typingEnded\" event, +1 is to account for latency.\n *\n * @private\n */\n\n/**\n * @class TypingIndicator\n *\n * @constructor\n * @private\n */\nclass TypingIndicator {\n private readonly services: TypingIndicatorServices;\n private readonly configuration: Configuration;\n\n private sentUpdates: Map<string, number>;\n private getConversation;\n private serviceTypingTimeout;\n\n constructor(\n getConversation,\n config: Configuration,\n services: TypingIndicatorServices\n ) {\n this.configuration = config;\n this.services = services;\n this.getConversation = getConversation;\n\n this.serviceTypingTimeout = null;\n this.sentUpdates = new Map();\n }\n\n public get typingTimeout(): number {\n return (\n this.configuration.typingIndicatorTimeoutOverride ||\n this.serviceTypingTimeout ||\n this.configuration.typingIndicatorTimeoutDefault\n );\n }\n\n /**\n * Initialize TypingIndicator controller\n * Registers for needed message types and sets listeners\n * @private\n */\n initialize(): void {\n // this.services.notificationClient.subscribe(NotificationTypes.TYPING_INDICATOR, 'twilsock');\n this.services.notificationClient.on(\"message\", async (type, message) => {\n if (type === NotificationTypes.TYPING_INDICATOR) {\n await this._handleRemoteTyping(message);\n }\n });\n }\n\n /**\n * Remote participants typing events handler\n */\n private async _handleRemoteTyping(message) {\n log.trace(\"Got new typing indicator \", message);\n\n this.getConversation(message.channel_sid)\n .then((conversation) => {\n if (!conversation) {\n return;\n }\n\n conversation.participants.forEach((participant) => {\n if (participant.identity !== message.identity) {\n return;\n }\n\n const timeout = this.configuration.typingIndicatorTimeoutOverride\n ? this.configuration.typingIndicatorTimeoutOverride + 1000\n : message.typing_timeout * 1000;\n participant._startTyping(timeout);\n });\n })\n .catch((err) => {\n log.error(err);\n throw err;\n });\n }\n\n /**\n * Send typing event for the given conversation sid\n * @param {String} conversationSid\n */\n send(conversationSid: string) {\n const lastUpdate = this.sentUpdates.get(conversationSid);\n if (lastUpdate && lastUpdate > Date.now() - this.typingTimeout) {\n return Promise.resolve();\n }\n\n this.sentUpdates.set(conversationSid, Date.now());\n return this._send(conversationSid);\n }\n\n private _send(conversationSid: string) {\n log.trace(\"Sending typing indicator\");\n\n const url = this.configuration.links.typing;\n const headers = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n };\n const body = `ChannelSid=${conversationSid}`;\n\n return this.services.twilsockClient\n .post<{ typing_timeout: number }>(\n url,\n headers,\n body,\n this.configuration.productId\n )\n .then((response) => {\n if (response.body.hasOwnProperty(\"typing_timeout\")) {\n this.serviceTypingTimeout = response.body.typing_timeout * 1000;\n }\n })\n .catch((err) => {\n log.error(\"Failed to send typing indicator:\", err);\n throw err;\n });\n }\n}\n\nexport { TypingIndicator };\n","/**\n * Push notification type.\n */\ntype PushNotificationType =\n | \"twilio.conversations.new_message\"\n | \"twilio.conversations.added_to_conversation\"\n | \"twilio.conversations.removed_from_conversation\";\n\ninterface PushNotificationDescriptor {\n title: string | null;\n body: string | null;\n sound: string | null;\n badge: number | null;\n action: string | null;\n type: PushNotificationType;\n data: Record<string, unknown>;\n}\n\n/**\n * Additional data for a given push notification.\n */\ninterface PushNotificationData {\n /**\n * SID of the conversation.\n */\n conversationSid?: string;\n\n /**\n * Index of the message in the conversation.\n */\n messageIndex?: number;\n\n /**\n * SID of the message in the conversation.\n */\n messageSid?: string;\n}\n\n/**\n * Push notification for a Conversations client.\n */\nclass PushNotification {\n /**\n * Title of the notification.\n */\n public readonly title: string | null;\n\n /**\n * Text of the notification.\n */\n public readonly body: string | null;\n\n /**\n * Sound of the notification.\n */\n public readonly sound: string | null;\n\n /**\n * Number of the badge.\n */\n public readonly badge: number | null;\n\n /**\n * Notification action (`click_action` in FCM terms and `category` in APN terms).\n */\n public readonly action: string | null;\n\n /**\n * Type of the notification.\n */\n public readonly type: PushNotificationType;\n\n /**\n * Additional data of the conversation.\n */\n public readonly data: PushNotificationData;\n\n /**\n * @internal\n */\n constructor(data: PushNotificationDescriptor) {\n this.title = data.title || null;\n this.body = data.body || null;\n this.sound = data.sound || null;\n this.badge = data.badge || null;\n this.action = data.action || null;\n this.type = data.type || null;\n this.data = data.data || {};\n }\n}\n\nexport {\n PushNotification,\n PushNotificationType,\n PushNotificationDescriptor,\n PushNotificationData,\n};\n","import { TransportResult as Result, Transport } from \"twilsock\";\nimport { MutationConflictResponse } from \"./interfaces/commands/mutation-conflict\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { AsyncRetrier } from \"@twilio/operation-retrier\";\n\nexport interface CommandExecutorServices {\n transport: Transport;\n}\n\nconst trimSlashes = (url: string): string => url.replace(/(^\\/+|\\/+$)/g, \"\");\n\nconst isMutationConflictResponse = (\n response: Result<unknown>\n): response is Result<MutationConflictResponse> => response.status.code === 202;\n\nclass CommandExecutor {\n constructor(\n private _serviceUrl: string,\n private _services: CommandExecutorServices,\n private _productId?: string\n ) {}\n\n private _preProcessUrl(url: string): string {\n const trimmedUrl = trimSlashes(url);\n\n if (/^https?:\\/\\//.test(url)) {\n return trimmedUrl;\n }\n\n return `${trimSlashes(this._serviceUrl)}/${trimmedUrl}`;\n }\n\n private async _makeRequest<REQ = void, RESP = void>(\n method: \"get\" | \"post\" | \"delete\",\n url: string,\n requestBody?: REQ,\n headers?: Record<string, string>\n ): Promise<Result<RESP>> {\n const preProcessedUrl = this._preProcessUrl(url);\n const finalHeaders = {\n \"Content-Type\": \"application/json; charset=utf-8\",\n ...(headers || {}),\n };\n let response: Result<RESP>;\n\n switch (method) {\n case \"get\":\n let getUrl = preProcessedUrl;\n\n if (requestBody) {\n getUrl +=\n \"?\" +\n Object.entries(requestBody)\n .map((entry) => entry.map(encodeURIComponent).join(\"=\"))\n .join(\"&\");\n }\n\n response = await this._services.transport.get(\n getUrl,\n finalHeaders,\n this._productId\n );\n break;\n case \"post\":\n response = await this._services.transport.post(\n preProcessedUrl,\n finalHeaders,\n JSON.stringify(requestBody),\n this._productId\n );\n break;\n case \"delete\":\n response = await this._services.transport.delete(\n preProcessedUrl,\n finalHeaders,\n {},\n this._productId\n );\n break;\n }\n\n if (response.status.code < 200 || response.status.code >= 300) {\n throw new Error(\n `Request responded with a non-success code ${response.status.code}`\n );\n }\n\n return response;\n }\n\n public async fetchResource<REQ = void, RESP = void>(\n url: string,\n requestBody?: REQ\n ): Promise<RESP> {\n const maxAttemptsCount = 6;\n try {\n const result = await new AsyncRetrier({\n min: 50,\n max: 1600,\n maxAttemptsCount,\n }).run(() => this._makeRequest<REQ, RESP>(\"get\", url, requestBody));\n return result.body;\n } catch {\n throw new Error(`Fetch resource from \"${url}\" failed.`);\n }\n }\n\n public async mutateResource<REQ = void, RESP = void>(\n method: \"post\" | \"delete\",\n url: string,\n requestBody?: REQ\n ): Promise<RESP> {\n const result = await this._makeRequest<REQ, RESP>(\n method,\n url,\n requestBody,\n {\n \"X-Twilio-Mutation-Id\": uuidv4(),\n }\n );\n\n if (isMutationConflictResponse(result)) {\n return await this.fetchResource<undefined, RESP>(\n result.body.resource_url\n );\n }\n\n return result.body;\n }\n}\n\nexport { CommandExecutor };\n","import { Logger } from \"./logger\";\nimport { Configuration } from \"./configuration\";\n\nimport { User, UserUpdatedEventArgs, UserUpdateReason } from \"./user\";\nimport { Network } from \"./services/network\";\n\nimport { NotificationTypes } from \"./interfaces/notification-types\";\n\nimport {\n TwilsockClient,\n InitRegistration,\n ConnectionState as TwilsockConnectionState,\n Transport,\n} from \"twilsock\";\nimport {\n ChannelType,\n Notifications as NotificationClient,\n} from \"@twilio/notifications\";\nimport { SyncClient } from \"twilio-sync\";\nimport { McsClient } from \"@twilio/mcs-client\";\n\nimport {\n Conversation,\n Conversations,\n Conversations as ConversationsEntity,\n} from \"./data/conversations\";\n\nimport { Users } from \"./data/users\";\nimport { TypingIndicator } from \"./services/typing-indicator\";\nimport { Paginator } from \"./interfaces/paginator\";\nimport { PushNotification } from \"./push-notification\";\nimport { deepClone, parseToNumber } from \"./util\";\nimport {\n Participant,\n ParticipantUpdatedEventArgs,\n ParticipantUpdateReason,\n} from \"./participant\";\nimport {\n Message,\n MessageUpdatedEventArgs,\n MessageUpdateReason,\n} from \"./message\";\nimport { TelemetryEventDescription, TelemetryPoint } from \"twilsock\";\nimport {\n validateTypesAsync,\n validateTypes,\n literal,\n nonEmptyString,\n pureObject,\n objectSchema,\n validateConstructorTypes,\n} from \"@twilio/declarative-type-validator\";\nimport { version as sdkVersion } from \"../package.json\";\nimport {\n ConversationUpdatedEventArgs,\n ConversationUpdateReason,\n} from \"./conversation\";\nimport { CommandExecutor } from \"./command-executor\";\nimport { ConfigurationResponse } from \"./interfaces/commands/configuration\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport { JSONValue } from \"./types\";\nimport { Media } from \"./media\";\nimport { CancellablePromise } from \"@twilio/mcs-client\";\n\n/**\n * Client events.\n */\ntype ClientEvents = {\n conversationAdded: (conversation: Conversation) => void;\n conversationJoined: (conversation: Conversation) => void;\n conversationLeft: (conversation: Conversation) => void;\n conversationRemoved: (conversation: Conversation) => void;\n conversationUpdated: (data: {\n conversation: Conversation;\n updateReasons: ConversationUpdateReason[];\n }) => void;\n participantJoined: (participant: Participant) => void;\n participantLeft: (participant: Participant) => void;\n participantUpdated: (data: {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n }) => void;\n messageAdded: (message: Message) => void;\n messageRemoved: (message: Message) => void;\n messageUpdated: (data: {\n message: Message;\n updateReasons: MessageUpdateReason[];\n }) => void;\n tokenAboutToExpire: (ttl: number) => void;\n tokenExpired: () => void;\n typingEnded: (participant: Participant) => void;\n typingStarted: (participant: Participant) => void;\n pushNotification: (pushNotification: PushNotification) => void;\n userSubscribed: (user: User) => void;\n userUnsubscribed: (user: User) => void;\n userUpdated: (data: {\n user: User;\n updateReasons: UserUpdateReason[];\n }) => void;\n stateChanged: ({ state, error }: { state: State; error?: Error }) => void;\n connectionStateChanged: (state: TwilsockConnectionState) => void;\n connectionError: (data: {\n terminal: boolean;\n message: string;\n httpStatusCode?: number;\n errorCode?: number;\n }) => void;\n};\n\n/**\n * Connection state of the client. Possible values are as follows:\n * * `'connecting'` - client is offline and connection attempt is in process\n * * `'connected'` - client is online and ready\n * * `'disconnecting'` - client is going offline as disconnection is in process\n * * `'disconnected'` - client is offline and no connection attempt is in\n * process\n * * `'denied'` - client connection is denied because of invalid JWT access\n * token. User must refresh token in order to proceed\n */\ntype ConnectionState = TwilsockConnectionState;\n\n/**\n * State of the client. Possible values are as follows:\n * * `'failed'` - the client failed to initialize\n * * `'initialized'` - the client successfully initialized\n */\ntype State = \"failed\" | \"initialized\";\n\n/**\n * Notifications channel type. Possible values are as follows:\n * * `'fcm'`\n * * `'apn'`\n */\ntype NotificationsChannelType = ChannelType;\n\n/**\n * Level of logging.\n */\ntype LogLevel = \"trace\" | \"debug\" | \"info\" | \"warn\" | \"error\" | \"silent\";\n\n/**\n * Conversations client options.\n */\ninterface ClientOptions {\n /**\n * The level of logging to enable.\n */\n logLevel?: LogLevel;\n\n region?: string;\n productId?: string;\n twilsockClient?: TwilsockClient;\n transport?: Transport;\n notificationsClient?: NotificationClient;\n syncClient?: SyncClient;\n typingIndicatorTimeoutOverride?: number;\n consumptionReportIntervalOverride?: string;\n httpCacheIntervalOverride?: string;\n userInfosToSubscribeOverride?: number;\n retryWhenThrottledOverride?: boolean;\n backoffConfigOverride?: Record<string, unknown>;\n Chat?: ClientOptions;\n IPMessaging?: ClientOptions;\n Sync?: Record<string, unknown>;\n Notification?: Record<string, unknown>;\n Twilsock?: Record<string, unknown>;\n clientMetadata?: Record<string, unknown>;\n initRegistrations?: InitRegistration[];\n disableDeepClone?: boolean;\n typingUri?: string;\n apiUri?: string;\n}\n\n/**\n * Options for {@link Client.createConversation}.\n */\ninterface CreateConversationOptions {\n /**\n * Any custom attributes to attach to the conversation.\n */\n attributes?: JSONValue;\n\n /**\n * A non-unique display name of the conversation.\n */\n friendlyName?: string;\n\n /**\n * A unique identifier of the conversation.\n */\n uniqueName?: string;\n}\n\n/**\n * Client services.\n */\nclass ClientServices {\n commandExecutor!: CommandExecutor;\n twilsockClient!: TwilsockClient;\n users!: Users;\n notificationClient!: NotificationClient;\n network!: Network;\n typingIndicator!: TypingIndicator;\n syncClient!: SyncClient;\n mcsClient!: McsClient;\n transport!: Transport;\n}\n\n/**\n * A client is the starting point to the Twilio Conversations functionality.\n */\n@validateConstructorTypes(nonEmptyString, [pureObject, \"undefined\"])\nclass Client extends ReplayEventEmitter<ClientEvents> {\n /**\n * Fired when a conversation becomes visible to the client. The event is also\n * triggered when the client creates a new conversation.\n * Fired for all conversations that the client has joined.\n *\n * Parameters:\n * 1. {@link Conversation} `conversation` - the conversation in question\n * @event\n */\n public static readonly conversationAdded = \"conversationAdded\";\n\n /**\n * Fired when the client joins a conversation.\n *\n * Parameters:\n * 1. {@link Conversation} `conversation` - the conversation in question\n * @event\n */\n public static readonly conversationJoined = \"conversationJoined\";\n\n /**\n * Fired when the client leaves a conversation.\n *\n * Parameters:\n * 1. {@link Conversation} `conversation` - the conversation in question\n * @event\n */\n public static readonly conversationLeft = \"conversationLeft\";\n\n /**\n * Fired when a conversation is no longer visible to the client.\n *\n * Parameters:\n * 1. {@link Conversation} `conversation` - the conversation in question\n * @event\n */\n public static readonly conversationRemoved = \"conversationRemoved\";\n\n /**\n * Fired when the attributes or the metadata of a conversation have been\n * updated. During conversation's creation and initialization, this event\n * might be fired multiple times for same joined or created conversation as\n * new data is arriving from different sources.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the\n * following properties:\n * * {@link Conversation} `conversation` - the conversation in question\n * * {@link ConversationUpdateReason}[] `updateReasons` - array of reasons\n * for the update\n * @event\n */\n public static readonly conversationUpdated = \"conversationUpdated\";\n\n /**\n * Fired when a participant has joined a conversation.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant in question\n * @event\n */\n public static readonly participantJoined = \"participantJoined\";\n\n /**\n * Fired when a participant has left a conversation.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant in question\n * @event\n */\n public static readonly participantLeft = \"participantLeft\";\n\n /**\n * Fired when a participant's fields have been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the\n * following properties:\n * * {@link Participant} `participant` - the participant in question\n * * {@link ParticipantUpdateReason}[] `updateReasons` - array of reasons\n * for the update\n * @event\n */\n public static readonly participantUpdated = \"participantUpdated\";\n\n /**\n * Fired when a new message has been added to the conversation on the server.\n *\n * Parameters:\n * 1. {@link Message} `message` - the message in question\n * @event\n */\n public static readonly messageAdded = \"messageAdded\";\n\n /**\n * Fired when a message is removed from the message list of a conversation.\n *\n * Parameters:\n * 1. {@link Message} `message` - the message in question\n * @event\n */\n public static readonly messageRemoved = \"messageRemoved\";\n\n /**\n * Fired when the fields of an existing message are updated with new values.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the\n * following properties:\n * * {@link Message} `message` - the message in question\n * * {@link MessageUpdateReason}[] `updateReasons` - array of reasons for\n * the update\n * @event\n */\n public static readonly messageUpdated = \"messageUpdated\";\n\n /**\n * Fired when the token is about to expire and needs to be updated.\n * * Parameters:\n * 1. number `message` - token's time to live\n * @event\n */\n public static readonly tokenAboutToExpire = \"tokenAboutToExpire\";\n\n /**\n * Fired when the token has expired.\n * @event\n */\n public static readonly tokenExpired = \"tokenExpired\";\n\n /**\n * Fired when a participant has stopped typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant in question\n * @event\n */\n public static readonly typingEnded = \"typingEnded\";\n\n /**\n * Fired when a participant has started typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant in question\n * @event\n */\n public static readonly typingStarted = \"typingStarted\";\n\n /**\n * Fired when the client has received (and parsed) a push notification via one\n * of the push channels (apn or fcm).\n *\n * Parameters:\n * 1. {@link PushNotification} `pushNotification` - the push notification in\n * question\n * @event\n */\n public static readonly pushNotification = \"pushNotification\";\n\n /**\n * Fired when the client has subscribed to a user.\n *\n * Parameters:\n * 1. {@link User} `user` - the user in question\n * @event\n */\n public static readonly userSubscribed = \"userSubscribed\";\n\n /**\n * Fired when the client has unsubscribed from a user.\n *\n * Parameters:\n * 1. {@link User} `user` - the user in question\n * @event\n */\n public static readonly userUnsubscribed = \"userUnsubscribed\";\n\n /**\n * Fired when the properties or the reachability status of a user have been\n * updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the\n * following properties:\n * * {@link User} `user` - the user in question\n * * {@link UserUpdateReason}[] `updateReasons` - array of reasons for the\n * update\n * @event\n */\n public static readonly userUpdated = \"userUpdated\";\n\n /**\n * Fired when the state of the client has been changed.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the\n * following properties:\n * * {@link State} `state` - the new client state\n * * Error? `error` - the initialization error if present\n * @event\n */\n public static readonly stateChanged = \"stateChanged\";\n\n /**\n * Fired when the connection state of the client has been changed.\n *\n * Parameters:\n * 1. {@link ConnectionState} `state` - the new connection state\n * @event\n */\n public static readonly connectionStateChanged = \"connectionStateChanged\";\n\n /**\n * Fired when the connection is interrupted for an unexpected reason.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the\n * following properties:\n * * boolean `terminal` - Twilsock will stop connection attempts if true\n * * string `message` - the error message of the root cause\n * * number? `httpStatusCode` - http status code if available\n * * number? `errorCode` - Twilio public error code if available\n * @event\n */\n public static readonly connectionError = \"connectionError\";\n\n /**\n * Current version of the Conversations client.\n */\n public static readonly version: string = sdkVersion;\n\n /**\n * Logger instance.\n */\n private static readonly _logger = Logger.scope(\"Client\");\n\n /**\n * Supported push notification channels.\n */\n private static readonly _supportedPushChannels: NotificationsChannelType[] = [\n \"fcm\",\n \"apn\",\n ];\n\n /**\n * Supported push data fields.\n */\n private static readonly _supportedPushDataFields = {\n conversation_sid: \"conversationSid\", // string\n conversation_title: \"conversationTitle\", // string\n message_sid: \"messageSid\", // string\n message_index: \"messageIndex\", // integer\n media_count: \"mediaCount\", // integer\n media: \"media\", // object\n };\n\n /**\n * Current version of the Conversations client.\n */\n public readonly version: string = sdkVersion;\n\n /**\n * Client connection state.\n */\n public connectionState: ConnectionState = \"unknown\";\n\n /**\n * Promise that resolves on successful initialization.\n */\n private readonly _ensureReady!: Promise<void>;\n\n /**\n * Options passed to the client.\n */\n private readonly _options: Partial<ClientOptions>;\n\n /**\n * Client service objects.\n */\n private readonly _services: ClientServices;\n\n /**\n * The user of the client.\n */\n private readonly _myself: User;\n\n /**\n * Resolves the {@link Client._ensureReady} promise.\n */\n private _resolveEnsureReady!: () => void;\n\n /**\n * Rejects the {@link Client._ensureReady} promise.\n */\n private _rejectEnsureReady!: (err: Error) => void;\n\n /**\n * The current token of the client.\n */\n private _fpaToken: string;\n\n /**\n * The constructed configuration object.\n */\n private _configuration!: Configuration;\n\n /**\n * The Conversations entity.\n */\n private _conversations!: Conversations;\n\n /**\n * Promise that resolves when initial conversations are fetched.\n */\n private _conversationsPromise!: Promise<Conversations>;\n\n /**\n * Returned Conversations instance is not yet fully initialized. Calling any\n * operations will block until it is. Use connection events to monitor when\n * client becomes fully available (connectionStateChanged with state\n * 'connected') or not available (connectionStateChange with state 'denied',\n * event tokenExpired, event connectionError).\n *\n * @param fpaToken Access token\n * @param options Options to customize the Client\n * @returns A not yet fully-initialized client.\n */\n public constructor(fpaToken: string, options: ClientOptions | null = {}) {\n super();\n\n this._fpaToken = fpaToken ?? \"\";\n this._options = options ?? {};\n\n if (!this._options.disableDeepClone) {\n let options: Partial<ClientOptions> = {\n ...this._options,\n transport: undefined,\n twilsockClient: undefined,\n };\n\n options = deepClone(options);\n options.transport = this._options.transport;\n options.twilsockClient = this._options.twilsockClient;\n\n this._options = options;\n }\n\n this._options.logLevel = this._options.logLevel ?? \"silent\";\n Client._logger.setLevel(this._options.logLevel);\n\n const productId = (this._options.productId = \"ip_messaging\");\n\n // Filling ClientMetadata\n this._options.clientMetadata = this._options.clientMetadata || {};\n\n if (!this._options.clientMetadata.hasOwnProperty(\"type\")) {\n this._options.clientMetadata.type = \"conversations\";\n }\n\n if (!this._options.clientMetadata.hasOwnProperty(\"sdk\")) {\n this._options.clientMetadata.sdk = \"JS\";\n this._options.clientMetadata.sdkv = sdkVersion;\n }\n\n // Enable session local storage for Sync\n this._options.Sync = this._options.Sync || {};\n\n if (typeof this._options.Sync.enableSessionStorage === \"undefined\") {\n this._options.Sync.enableSessionStorage = true;\n }\n\n if (this._options.region) {\n this._options.Sync.region = this._options.region;\n }\n\n if (!fpaToken) {\n throw new Error(\"A valid Twilio token should be provided\");\n }\n\n this._services = new ClientServices();\n\n this._myself = new User(\"\", \"\", null, this._services);\n\n const startTwilsock = !this._options.twilsockClient;\n\n // Create default init registrations if none were provided.\n // Otherwise, the outside party have to list all the init registrations they\n // need.\n // Init registrations passed to the Conversations client will be passed down\n // to the Sync client as well.\n if (!this._options.initRegistrations) {\n const initRegistration = new InitRegistration(productId);\n Client.populateInitRegistrations(initRegistration);\n this._options.initRegistrations = [initRegistration];\n }\n\n this._services.twilsockClient = this._options.twilsockClient =\n this._options.twilsockClient ??\n new TwilsockClient(fpaToken, productId, this._options);\n\n this._services.twilsockClient.on(\"tokenAboutToExpire\", (ttl) =>\n this.emit(\"tokenAboutToExpire\", ttl)\n );\n this._services.twilsockClient.on(\"tokenExpired\", () =>\n this.emit(\"tokenExpired\")\n );\n this._services.twilsockClient.on(\"connectionError\", (error) =>\n this.emit(\"connectionError\", error)\n );\n this._services.twilsockClient.on(\n \"stateChanged\",\n (state: ConnectionState) => {\n Client._logger.debug(\n `Handling stateChanged for ConversationsClient: new state ${state}`\n );\n if (state !== this.connectionState) {\n this.connectionState = state;\n this.emit(\"connectionStateChanged\", this.connectionState);\n }\n }\n );\n\n this._services.transport = this._options.transport = (this._options\n .transport ?? this._options.twilsockClient) as Transport;\n this._services.notificationClient = this._options.notificationsClient =\n this._options.notificationsClient ??\n new NotificationClient(fpaToken, this._options);\n this._services.syncClient = this._options.syncClient =\n this._options.syncClient ?? new SyncClient(fpaToken, this._options);\n\n const configurationOptions =\n options?.Chat || options?.IPMessaging || options || {};\n const region = configurationOptions.region || options?.region;\n const baseUrl: string =\n configurationOptions.apiUri ||\n configurationOptions.typingUri ||\n `https://aim.${region || \"us1\"}.twilio.com`;\n\n this._services.commandExecutor = new CommandExecutor(\n baseUrl,\n { transport: this._options.transport },\n productId\n );\n\n const emitFailed = (error: Error): void => {\n this._rejectEnsureReady(error);\n this.emit(\"stateChanged\", { state: \"failed\", error });\n };\n\n this._services.twilsockClient.once(\"connectionError\", emitFailed);\n this._services.twilsockClient.once(\"disconnected\", emitFailed);\n\n // The client will be able to initialize only after Twilsock is connected\n this._services.twilsockClient.once(\"connected\", async () => {\n Client._logger.debug(`ConversationsClient started INITIALIZING`);\n this._services.twilsockClient.off(\"connectionError\", emitFailed);\n this._services.twilsockClient.off(\"disconnected\", emitFailed);\n try {\n const startupEvent = \"conversations.client.startup\";\n\n this._services.twilsockClient.addPartialTelemetryEvent(\n new TelemetryEventDescription(\n startupEvent,\n \"Conversations client startup\",\n new Date()\n ),\n startupEvent,\n TelemetryPoint.Start\n );\n\n await this._initialize();\n\n this._services.twilsockClient.addPartialTelemetryEvent(\n new TelemetryEventDescription(\"\", \"\", new Date()),\n startupEvent,\n TelemetryPoint.End\n );\n } catch (err) {\n // Fail ChatClient if initialization is incomplete\n this._rejectEnsureReady(err);\n this.emit(\"stateChanged\", { state: \"failed\", error: err });\n }\n });\n\n this._ensureReady = new Promise<void>((resolve, reject) => {\n this._resolveEnsureReady = resolve;\n this._rejectEnsureReady = reject;\n }).catch(() => void 0); // @todo How to process unhandled rejection here?\n\n if (startTwilsock) {\n this._services.twilsockClient.connect();\n }\n }\n\n /**\n * Information of the logged-in user. Before client initialization, returns an\n * uninitialized user. Will trigger a {@link Client.userUpdated} event after\n * initialization.\n */\n public get user(): User {\n return this._myself;\n }\n\n /**\n * Client reachability state. Throws an error if accessed before the client\n * initialization was completed.\n */\n public get reachabilityEnabled(): boolean {\n if (!this._configuration) {\n throw new Error(\n \"Reachability information could not yet be accessed as the client \" +\n \"has not yet been initialized. Subscribe to the 'stateChanged' event \" +\n \"to properly react to the client initialization.\"\n );\n }\n\n return this._configuration.reachabilityEnabled;\n }\n\n /**\n * @deprecated Call constructor directly.\n *\n * Factory method to create a Conversations client instance.\n *\n * The factory method will automatically trigger connection.\n * Do not use it if you need finer-grained control.\n *\n * Since this method returns an already-initialized client, some of the events\n * will be lost because they happen *before* the initialization. It is\n * recommended that `client.onWithReplay` is used as opposed to `client.on`\n * for subscribing to client events. The `client.onWithReplay` will re-emit\n * the most recent value for a given event if it emitted before the\n * subscription.\n *\n * @param token Access token.\n * @param options Options to customize the client.\n * @returns Returns a fully initialized client.\n */\n @validateTypesAsync(\"string\", [\"undefined\", pureObject])\n public static async create(\n token: string,\n options?: ClientOptions | null\n ): Promise<Client> {\n // The logic is as follows:\n // - If twilsock is not passed in, then the ConversationsClient constructor will call twilsock.connect() by itself\n // and we do not need to do it here.\n // - If twilsock was passed in from the outside, but customer called ConversationsClient.create() then they are\n // using an obsolete workflow and the startup sequence will never complete.\n if (options?.twilsockClient) {\n throw new Error(\n \"Obsolete usage of ConversationsClient.create() \" +\n \"factory method: if you pass twilsock from the outside then you must \" +\n \"use ConversationsClient constructor and be prepared to work with \" +\n \"uninitialized client.\"\n );\n }\n\n const client = new Client(token, options);\n await client._ensureReady;\n\n return client;\n }\n\n /**\n * Static method for push notification payload parsing. Returns parsed push as\n * a {@link PushNotification} object.\n * @param notificationPayload Push notification payload.\n */\n @validateTypes(pureObject)\n public static parsePushNotification(notificationPayload): PushNotification {\n Client._logger.debug(\n \"parsePushNotification, notificationPayload=\",\n notificationPayload\n );\n\n // APNS specifics\n if (typeof notificationPayload.aps !== \"undefined\") {\n if (!notificationPayload.twi_message_type) {\n throw new Error(\n \"Provided push notification payload does not contain Programmable Chat push notification type\"\n );\n }\n\n const data = Client._parsePushNotificationChatData(notificationPayload);\n\n const apsPayload = notificationPayload.aps;\n let body: string | null;\n let title: string | null = null;\n if (typeof apsPayload.alert === \"string\") {\n body = apsPayload.alert || null;\n } else {\n body = apsPayload.alert.body || null;\n title = apsPayload.alert.title || null;\n }\n\n return new PushNotification({\n title,\n body,\n sound: apsPayload.sound || null,\n badge: apsPayload.badge || null,\n action: apsPayload.category || null,\n type: notificationPayload.twi_message_type,\n data: data,\n });\n }\n\n // FCM specifics\n if (typeof notificationPayload.data !== \"undefined\") {\n const dataPayload = notificationPayload.data;\n if (!dataPayload.twi_message_type) {\n throw new Error(\n \"Provided push notification payload does not contain Programmable Chat push notification type\"\n );\n }\n\n const data = Client._parsePushNotificationChatData(\n notificationPayload.data\n );\n return new PushNotification({\n title: dataPayload.twi_title || null,\n body: dataPayload.twi_body || null,\n sound: dataPayload.twi_sound || null,\n badge: null,\n action: dataPayload.twi_action || null,\n type: dataPayload.twi_message_type,\n data: data,\n });\n }\n\n throw new Error(\n \"Provided push notification payload is not Programmable Chat notification\"\n );\n }\n\n /**\n * Static method for parsing push notification chat data.\n * @param data Data to parse\n */\n private static _parsePushNotificationChatData(\n data: Record<string, unknown>\n ): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const key in Client._supportedPushDataFields) {\n const value = data[key];\n if (typeof value === \"undefined\" || value === null) {\n continue;\n }\n\n if (key === \"message_index\" || key === \"media_count\") {\n const number = parseToNumber(value);\n if (number !== null) {\n result[Client._supportedPushDataFields[key]] = number;\n }\n continue;\n }\n\n if (key === \"media\") {\n if (typeof value === \"string\") {\n try {\n result[Client._supportedPushDataFields[key]] = JSON.parse(value);\n } catch {\n Client._logger.debug(\"Media message notification parsing error\");\n }\n }\n continue;\n }\n\n result[Client._supportedPushDataFields[key]] = value;\n }\n\n return result;\n }\n\n /**\n * Populate the client with init registrations.\n * @param reg The init registration to populate.\n */\n public static populateInitRegistrations(reg: InitRegistration) {\n reg.populateInitRegistrations([NotificationTypes.TYPING_INDICATOR]);\n SyncClient.populateInitRegistrations(reg);\n }\n\n /**\n * Gracefully shut down the client.\n */\n public async shutdown(): Promise<void> {\n await this._ensureReady;\n await this._services.twilsockClient.disconnect();\n }\n\n /**\n * Update the token used by the client and re-register with the Conversations services.\n * @param token New access token.\n */\n @validateTypesAsync(nonEmptyString)\n public async updateToken(token: string): Promise<Client> {\n await this._ensureReady;\n Client._logger.info(\"updateToken\");\n\n if (this._fpaToken === token) {\n return this;\n }\n\n await this._services.twilsockClient.updateToken(token);\n await this._services.notificationClient.updateToken(token);\n await this._services.mcsClient.updateToken(token);\n this._fpaToken = token;\n\n return this;\n }\n\n /**\n * Get a known conversation by its SID.\n * @param conversationSid Conversation sid\n */\n @validateTypesAsync(nonEmptyString)\n public async getConversationBySid(\n conversationSid: string\n ): Promise<Conversation> {\n await this._ensureReady;\n await this._conversations.myConversationsRead.promise;\n\n const conversation = await this._conversations.getConversation(\n conversationSid\n );\n\n if (!conversation) {\n throw new Error(`Conversation with SID ${conversationSid} is not found.`);\n }\n\n return conversation;\n }\n\n /**\n * Peek a conversation by its SID.\n * @param conversationSid Conversation sid\n * @internal\n */\n @validateTypesAsync(nonEmptyString)\n public async peekConversationBySid(\n conversationSid: string\n ): Promise<Conversation> {\n await this._ensureReady;\n\n const conversation = await this._conversations.peekConversation(\n conversationSid\n );\n\n if (!conversation) {\n throw new Error(`Conversation with SID ${conversationSid} is not found.`);\n }\n\n return conversation;\n }\n\n /**\n * Get a known conversation by its unique identifier name.\n * @param uniqueName The unique identifier name of the conversation.\n */\n @validateTypesAsync(nonEmptyString)\n public async getConversationByUniqueName(\n uniqueName: string\n ): Promise<Conversation> {\n await this._ensureReady;\n await this._conversations.myConversationsRead.promise;\n const conversation = await this._conversations.getConversationByUniqueName(\n uniqueName\n );\n\n if (!conversation) {\n throw new Error(\n `Conversation with unique name ${uniqueName} is not found.`\n );\n }\n\n return conversation;\n }\n\n /**\n * Get the current list of all the subscribed conversations.\n */\n public async getSubscribedConversations(): Promise<Paginator<Conversation>> {\n await this._ensureReady;\n return this._conversationsPromise.then((conversations) =>\n conversations.getConversations()\n );\n }\n\n /**\n * Create a conversation on the server and subscribe to its events.\n * The default is a conversation with an empty friendly name.\n * @param options Options for the conversation.\n */\n @validateTypesAsync([\n \"undefined\",\n objectSchema(\"conversation options\", {\n friendlyName: [\"string\", \"undefined\"],\n isPrivate: [\"boolean\", \"undefined\"],\n uniqueName: [\"string\", \"undefined\"],\n }),\n ])\n public async createConversation(\n options?: CreateConversationOptions\n ): Promise<Conversation> {\n await this._ensureReady;\n options = options || {};\n return this._conversationsPromise.then((conversationsEntity) =>\n conversationsEntity.addConversation(options)\n );\n }\n\n /**\n * Register for push notifications.\n * @param channelType Channel type.\n * @param registrationId Push notification ID provided by the FCM/APNS service\n * on the platform.\n */\n @validateTypesAsync(literal(\"fcm\", \"apn\"), \"string\")\n public async setPushRegistrationId(\n channelType: NotificationsChannelType,\n registrationId: string\n ): Promise<void> {\n await this._ensureReady;\n this._subscribeToPushNotifications(channelType);\n this._services.notificationClient.setPushRegistrationId(\n channelType,\n registrationId\n );\n await this._services.notificationClient.commitChanges(); // Committing before this point is useless because we have no push id\n }\n\n /**\n * Unregister from push notifications.\n * @param channelType Channel type.\n * @deprecated Use removePushRegistrations() instead.\n */\n @validateTypesAsync(literal(\"fcm\", \"apn\"))\n public async unsetPushRegistrationId(\n channelType: NotificationsChannelType\n ): Promise<void> {\n await this._ensureReady;\n this._unsubscribeFromPushNotifications(channelType);\n await this._services.notificationClient.commitChanges();\n }\n\n /**\n * Clear existing registrations directly using provided device token.\n * This is useful to ensure stopped subscriptions without resubscribing.\n *\n * This function goes completely beside the state machine and removes all\n * registrations.\n * Use with caution: if it races with current state machine operations,\n * madness will ensue.\n *\n * @param channelType Channel type.\n * @param registrationId Push notification ID provided by the FCM/APNS service\n * on the platform.\n */\n @validateTypesAsync(literal(\"fcm\", \"apn\"), nonEmptyString)\n public async removePushRegistrations(\n channelType: ChannelType,\n registrationId: string\n ): Promise<void> {\n // do not await this._ensureReady() here - it could be called at any moment\n await this._services.notificationClient.removeRegistrations(\n channelType,\n registrationId\n );\n }\n\n /**\n * Current version of the Conversations client.\n */\n public parsePushNotification = Client.parsePushNotification;\n\n /**\n * Handle push notification payload parsing and emit the\n * {@link Client.pushNotification} event on this {@link Client} instance.\n * @param notificationPayload Push notification payload\n */\n @validateTypesAsync(pureObject)\n public async handlePushNotification(notificationPayload): Promise<void> {\n await this._ensureReady;\n Client._logger.debug(\n \"handlePushNotification, notificationPayload=\",\n notificationPayload\n );\n this.emit(\n \"pushNotification\",\n Client.parsePushNotification(notificationPayload)\n );\n }\n\n /**\n * Gets a user with the given identity. If it's in the subscribed list, then\n * return the user object from it;\n * if not, then subscribe and add user to the subscribed list.\n * @param identity Identity of the user.\n * @returns A fully initialized user.\n */\n @validateTypesAsync(nonEmptyString)\n public async getUser(identity: string): Promise<User> {\n await this._ensureReady;\n return this._services.users.getUser(identity);\n }\n\n /**\n * Get a list of subscribed user objects.\n */\n public async getSubscribedUsers(): Promise<Array<User>> {\n await this._ensureReady;\n return this._services.users.getSubscribedUsers();\n }\n\n /**\n * Get content URLs for all media attachments in the given set of media sids\n * using a single operation.\n * @param mediaSids Set of media sids to query for the content URL.\n */\n public getTemporaryContentUrlsForMediaSids(\n mediaSids: string[]\n ): CancellablePromise<Map<string, string>> {\n return new CancellablePromise(async (resolve, reject, onCancel) => {\n if (!this._services.mcsClient || !mediaSids) {\n reject(new Error(\"Media Content Service is unavailable\"));\n return;\n }\n\n const request =\n this._services.mcsClient.mediaSetGetContentUrls(mediaSids);\n\n onCancel(() => {\n request.cancel();\n });\n\n try {\n const urls = await request;\n resolve(urls);\n } catch (e) {\n reject(e);\n }\n });\n }\n\n /**\n * Get content URLs for all media attachments in the given set using a single\n * operation.\n * @param contentSet Set of media attachments to query content URLs.\n */\n public getTemporaryContentUrlsForMedia(\n contentSet: Media[]\n ): CancellablePromise<Map<string, string>> {\n // We ignore existing mcsMedia members of each of the media entries.\n // Instead, we just collect their sids and pull new descriptors from a\n // mediaSet GET endpoint.\n const sids = contentSet.map((m) => m.sid);\n return this.getTemporaryContentUrlsForMediaSids(sids);\n }\n\n /**\n * Initialize the client.\n */\n private async _initialize() {\n const configurationResponse =\n await this._services.commandExecutor.fetchResource<\n void,\n ConfigurationResponse\n >(\"Client/v2/Configuration\");\n\n this._configuration = new Configuration(\n this._options as ClientOptions,\n configurationResponse,\n Client._logger\n );\n\n this._myself._resolveInitialization(\n this._configuration,\n this._configuration.userIdentity,\n this._configuration.userInfo,\n true\n );\n\n this._services.typingIndicator = new TypingIndicator(\n this.getConversationBySid.bind(this),\n this._configuration,\n this._services\n );\n this._services.network = new Network(this._configuration, this._services);\n\n this._services.users = new Users(\n this._myself,\n this._configuration,\n this._services\n );\n this._services.users.on(\"userSubscribed\", (user) => {\n this.emit(\"userSubscribed\", user);\n });\n this._services.users.on(\"userUpdated\", (args: UserUpdatedEventArgs) =>\n this.emit(\"userUpdated\", args)\n );\n this._services.users.on(\"userUnsubscribed\", (user) => {\n this.emit(\"userUnsubscribed\", user);\n });\n\n this._conversations = new ConversationsEntity(\n this._configuration,\n this._services\n );\n\n this._conversations.on(\"conversationAdded\", (conversation) => {\n this.emit(\"conversationAdded\", conversation);\n });\n this._conversations.on(\"conversationRemoved\", (conversation) => {\n this.emit(\"conversationRemoved\", conversation);\n });\n this._conversations.on(\"conversationJoined\", (conversation) => {\n this.emit(\"conversationJoined\", conversation);\n });\n this._conversations.on(\"conversationLeft\", (conversation) => {\n this.emit(\"conversationLeft\", conversation);\n });\n this._conversations.on(\n \"conversationUpdated\",\n (args: ConversationUpdatedEventArgs) =>\n this.emit(\"conversationUpdated\", args)\n );\n\n this._conversations.on(\"participantJoined\", (participant) => {\n this.emit(\"participantJoined\", participant);\n });\n this._conversations.on(\"participantLeft\", (participant) => {\n this.emit(\"participantLeft\", participant);\n });\n this._conversations.on(\n \"participantUpdated\",\n (args: ParticipantUpdatedEventArgs) =>\n this.emit(\"participantUpdated\", args)\n );\n\n this._conversations.on(\"messageAdded\", (message) =>\n this.emit(\"messageAdded\", message)\n );\n this._conversations.on(\"messageUpdated\", (args: MessageUpdatedEventArgs) =>\n this.emit(\"messageUpdated\", args)\n );\n this._conversations.on(\"messageRemoved\", (message) =>\n this.emit(\"messageRemoved\", message)\n );\n\n this._conversations.on(\"typingStarted\", (participant) =>\n this.emit(\"typingStarted\", participant)\n );\n this._conversations.on(\"typingEnded\", (participant) =>\n this.emit(\"typingEnded\", participant)\n );\n\n this._conversationsPromise = this._conversations\n .fetchConversations()\n .then(() => this._conversations)\n .catch((error) => {\n throw error;\n });\n\n await this._services.users.myself._ensureFetched();\n\n Client._supportedPushChannels.forEach((channelType) =>\n this._subscribeToPushNotifications(channelType)\n );\n this._services.typingIndicator.initialize();\n\n this._services.mcsClient = new McsClient(\n this._fpaToken,\n this._configuration.links.mediaService,\n this._configuration.links.mediaSetService,\n {\n ...this._options,\n transport: undefined,\n }\n );\n\n this._resolveEnsureReady();\n this.emit(\"stateChanged\", { state: \"initialized\" });\n }\n\n /**\n * Subscribe to push notifications.\n * @param channelType The channel type to subscribe to.\n */\n private _subscribeToPushNotifications(channelType: NotificationsChannelType) {\n [\n NotificationTypes.NEW_MESSAGE,\n NotificationTypes.ADDED_TO_CONVERSATION,\n NotificationTypes.REMOVED_FROM_CONVERSATION,\n NotificationTypes.TYPING_INDICATOR,\n NotificationTypes.CONSUMPTION_UPDATE,\n ].forEach((messageType) => {\n this._services.notificationClient.subscribe(channelType, messageType);\n });\n }\n\n /**\n * Unsubscribe from push notifications.\n * @param channelType The channel type to unsubscribe from.\n */\n private _unsubscribeFromPushNotifications(\n channelType: NotificationsChannelType\n ) {\n [\n NotificationTypes.NEW_MESSAGE,\n NotificationTypes.ADDED_TO_CONVERSATION,\n NotificationTypes.REMOVED_FROM_CONVERSATION,\n NotificationTypes.TYPING_INDICATOR,\n NotificationTypes.CONSUMPTION_UPDATE,\n ].forEach((messageType) => {\n this._services.notificationClient.unsubscribe(channelType, messageType);\n });\n }\n}\n\nexport {\n Client,\n State,\n ConnectionState,\n NotificationsChannelType,\n LogLevel,\n ClientOptions,\n CreateConversationOptions,\n};\n"],"names":["__decorate","decorators","target","key","desc","c","arguments","length","r","Object","getOwnPropertyDescriptor","d","Reflect","decorate","i","defineProperty","__metadata","metadataKey","metadataValue","metadata","log","loglevelLog","toSeconds","parseDuration","parseTime","custom","isEqual","ReplayEventEmitter","validateTypesAsync","Retrier","McsMedia","CancellablePromise","validateTypes","nonEmptyString","nonNegativeInteger","literal","objectSchema","AsyncRetrier","uuidv4","Client","sdkVersion","InitRegistration","TwilsockClient","NotificationClient","SyncClient","TelemetryEventDescription","TelemetryPoint","ConversationsEntity","McsClient","pureObject","validateConstructorTypes"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDO,SAASA,UAAT,CAAoBC,UAApB,EAAgCC,MAAhC,EAAwCC,GAAxC,EAA6CC,IAA7C,EAAmD;AACtD,MAAIC,CAAC,GAAGC,SAAS,CAACC,MAAlB;AAAA,MAA0BC,CAAC,GAAGH,CAAC,GAAG,CAAJ,GAAQH,MAAR,GAAiBE,IAAI,KAAK,IAAT,GAAgBA,IAAI,GAAGK,MAAM,CAACC,wBAAP,CAAgCR,MAAhC,EAAwCC,GAAxC,CAAvB,GAAsEC,IAArH;AAAA,MAA2HO,CAA3H;AACA,MAAI,QAAOC,OAAP,6DAAOA,OAAP,OAAmB,QAAnB,IAA+B,OAAOA,OAAO,CAACC,QAAf,KAA4B,UAA/D,EAA2EL,CAAC,GAAGI,OAAO,CAACC,QAAR,CAAiBZ,UAAjB,EAA6BC,MAA7B,EAAqCC,GAArC,EAA0CC,IAA1C,CAA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