@twilio/conversations 2.1.0-rc.8 → 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.
@@ -182,21 +182,21 @@ class MessageBuilder {
182
182
  return this;
183
183
  }
184
184
  /**
185
- * Set email body with given MIME-type.
186
- * @param mimeType Format of the body to set (text/plain or text/html).
187
- * @param body Body payload in selected format.
185
+ * Set the email body with a given content type.
186
+ * @param contentType Format of the body to set (text/plain or text/html).
187
+ * @param body Body payload in the selected format.
188
188
  */
189
- setEmailBody(mimeType, body) {
190
- this.emailBodies.set(mimeType, body);
189
+ setEmailBody(contentType, body) {
190
+ this.emailBodies.set(contentType, body);
191
191
  return this;
192
192
  }
193
193
  /**
194
- * Set email history with given MIME-type.
195
- * @param mimeType Format of the history to set (text/plain or text/html).
196
- * @param history History payload in selected format.
194
+ * Set the email history with a given content type.
195
+ * @param contentType Format of the history to set (text/plain or text/html).
196
+ * @param history History payload in the selected format.
197
197
  */
198
- setEmailHistory(mimeType, history) {
199
- this.emailHistories.set(mimeType, history);
198
+ setEmailHistory(contentType, history) {
199
+ this.emailHistories.set(contentType, history);
200
200
  return this;
201
201
  }
202
202
  /**
@@ -221,21 +221,21 @@ class MessageBuilder {
221
221
  */
222
222
  build() {
223
223
  this.emailBodies.forEach((_, key) => {
224
- if (!this.limits.emailBodiesAllowedMimeTypes.includes(key)) {
225
- throw new Error(`Unsupported email body MIME type ${key}`);
224
+ if (!this.limits.emailBodiesAllowedContentTypes.includes(key)) {
225
+ throw new Error(`Unsupported email body content type ${key}`);
226
226
  }
227
227
  });
228
228
  this.emailHistories.forEach((_, key) => {
229
- if (!this.limits.emailHistoriesAllowedMimeTypes.includes(key)) {
230
- throw new Error(`Unsupported email history MIME type ${key}`);
229
+ if (!this.limits.emailHistoriesAllowedContentTypes.includes(key)) {
230
+ throw new Error(`Unsupported email history content type ${key}`);
231
231
  }
232
232
  });
233
- if (this.emailBodies.size > this.limits.emailBodiesAllowedMimeTypes.length) {
234
- throw new Error(`Too many email bodies attached to the message (${this.emailBodies.size} > ${this.limits.emailBodiesAllowedMimeTypes.length})`);
233
+ if (this.emailBodies.size > this.limits.emailBodiesAllowedContentTypes.length) {
234
+ throw new Error(`Too many email bodies attached to the message (${this.emailBodies.size} > ${this.limits.emailBodiesAllowedContentTypes.length})`);
235
235
  }
236
236
  if (this.emailHistories.size >
237
- this.limits.emailHistoriesAllowedMimeTypes.length) {
238
- throw new Error(`Too many email histories attached to the message (${this.emailHistories.size} > ${this.limits.emailHistoriesAllowedMimeTypes.length})`);
237
+ this.limits.emailHistoriesAllowedContentTypes.length) {
238
+ throw new Error(`Too many email histories attached to the message (${this.emailHistories.size} > ${this.limits.emailHistoriesAllowedContentTypes.length})`);
239
239
  }
240
240
  if (this.message.mediaContent.length > this.limits.mediaAttachmentsCountLimit) {
241
241
  throw new Error(`Too many media attachments in the message (${this.message.mediaContent.length} > ${this.limits.mediaAttachmentsCountLimit})`);
@@ -250,6 +250,12 @@ class MessageBuilder {
250
250
  });
251
251
  return this.message;
252
252
  }
253
+ /**
254
+ * Prepares a message and sends it to the conversation.
255
+ */
256
+ buildAndSend() {
257
+ return this.build().send();
258
+ }
253
259
  getPayloadContentType(payload) {
254
260
  if (typeof FormData !== "undefined" && payload instanceof FormData) {
255
261
  return payload.get("Content-Type");
@@ -1 +1 @@
1
- {"version":3,"file":"message-builder.js","sources":["../src/message-builder.ts"],"sourcesContent":["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"],"names":["UnsentMessage"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;AAeA,MAAM,cAAc;;;;IAQlB,YACmB,MAA0B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KAAK,CACb,8CAA8C,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,MAAM,MAAM,IAAI,CAAC,MAAM,CAAC,0BAA0B,GAAG,CAC9H,CAAC;SACH;;;QAKD,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,IAAI;YAC5B,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;SAChD,CAAC,CAAC;QAEH,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,OAAO;YAClC,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC;SACtD,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC,OAAO,CAAC;KACrB;IAEO,qBAAqB,CAC3B,OAAoC;QAEpC,IAAI,OAAO,QAAQ,KAAK,WAAW,IAAI,OAAO,YAAY,QAAQ,EAAE;YAClE,OAAO,OAAO,CAAC,GAAG,CAAC,cAAc,CAAW,CAAC;SAC9C;QACD,OAAQ,OAA4B,CAAC,WAAW,CAAC;KAClD;;;;;"}
1
+ {"version":3,"file":"message-builder.js","sources":["../src/message-builder.ts"],"sourcesContent":["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"],"names":["UnsentMessage"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;AAeA,MAAM,cAAc;;;;IAQlB,YACmB,MAA0B,EAC3C,cAAwB;QADP,WAAM,GAAN,MAAM,CAA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Y,CAAC,MAAM,MAAM,IAAI,CAAC,MAAM,CAAC,0BAA0B,GAAG,CAC9H,CAAC;SACH;;;QAKD,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,IAAI;YAC5B,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;SAChD,CAAC,CAAC;QAEH,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,OAAO;YAClC,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC;SACtD,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC,OAAO,CAAC;KACrB;;;;IAKD,YAAY;QACV,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,CAAC;KAC5B;IAEO,qBAAqB,CAC3B,OAAoC;QAEpC,IAAI,OAAO,QAAQ,KAAK,WAAW,IAAI,OAAO,YAAY,QAAQ,EAAE;YAClE,OAAO,OAAO,CAAC,GAAG,CAAC,cAAc,CAAW,CAAC;SAC9C;QACD,OAAQ,OAA4B,CAAC,WAAW,CAAC;KAClD;;;;;"}
package/dist/message.js CHANGED
@@ -133,6 +133,7 @@ Object.defineProperty(exports, '__esModule', { value: true });
133
133
  var tslib_es6 = require('./node_modules/tslib/tslib.es6.js');
134
134
  var index = require('./util/index.js');
135
135
  var logger = require('./logger.js');
136
+ var mcsClient = require('@twilio/mcs-client');
136
137
  var media = require('./media.js');
137
138
  var aggregatedDeliveryReceipt = require('./aggregated-delivery-receipt.js');
138
139
  var declarativeTypeValidator = require('@twilio/declarative-type-validator');
@@ -263,7 +264,7 @@ class Message extends replayEventEmitter.ReplayEventEmitter {
263
264
  * Return all media attachments, except email body/history attachments, without temporary urls.
264
265
  */
265
266
  get attachedMedia() {
266
- return this.getMediaByCategory(["media"]);
267
+ return this.getMediaByCategories(["media"]);
267
268
  }
268
269
  /**
269
270
  * The server-assigned unique identifier of the authoring participant.
@@ -283,27 +284,27 @@ class Message extends replayEventEmitter.ReplayEventEmitter {
283
284
  * @param categories Array of categories to match.
284
285
  * @returns Array of media descriptors matching given categories.
285
286
  */
286
- getMediaByCategory(categories) {
287
+ getMediaByCategories(categories) {
287
288
  var _a;
288
289
  return ((_a = this.state.medias) !== null && _a !== void 0 ? _a : []).filter((m) => categories.includes(m.category));
289
290
  }
290
291
  /**
291
292
  * Get a media descriptor for an email body attachment of a provided type.
292
- * Allowed body types are returned in the Conversation.limits().emailBodiesAllowedMimeTypes array.
293
+ * Allowed body types are returned in the Conversation.limits().emailBodiesAllowedContentTypes array.
293
294
  * @param type Type of email body to request, defaults to `text/plain`.
294
295
  */
295
296
  getEmailBody(type = "text/plain") {
296
297
  var _a, _b;
297
- return ((_b = (_a = this.getMediaByCategory(["body"])) === null || _a === void 0 ? void 0 : _a.filter((m) => m.contentType == type).shift()) !== null && _b !== void 0 ? _b : null);
298
+ return ((_b = (_a = this.getMediaByCategories(["body"])) === null || _a === void 0 ? void 0 : _a.filter((m) => m.contentType == type).shift()) !== null && _b !== void 0 ? _b : null);
298
299
  }
299
300
  /**
300
301
  * Get a media descriptor for an email history attachment of a provided type.
301
- * Allowed body types are returned in the Conversation.limits().emailHistoriesAllowedMimeTypes array.
302
+ * Allowed body types are returned in the Conversation.limits().emailHistoriesAllowedContentTypes array.
302
303
  * @param type Type of email history to request, defaults to `text/plain`.
303
304
  */
304
305
  getEmailHistory(type = "text/plain") {
305
306
  var _a, _b;
306
- return ((_b = (_a = this.getMediaByCategory(["history"])) === null || _a === void 0 ? void 0 : _a.filter((m) => m.contentType == type).shift()) !== null && _b !== void 0 ? _b : null);
307
+ return ((_b = (_a = this.getMediaByCategories(["history"])) === null || _a === void 0 ? void 0 : _a.filter((m) => m.contentType == type).shift()) !== null && _b !== void 0 ? _b : null);
307
308
  }
308
309
  _update(data) {
309
310
  const updateReasons = [];
@@ -452,21 +453,47 @@ class Message extends replayEventEmitter.ReplayEventEmitter {
452
453
  return this;
453
454
  }
454
455
  /**
455
- * Get content URLs for all media attachments in the given set using single operation.
456
- * @param contentSet Set of media attachments to query for content URL.
456
+ * Get content URLs for all media attachments in the given set using a single operation.
457
+ * @param contentSet Set of media attachments to query content URLs.
457
458
  */
458
- async attachTemporaryUrlsFor(contentSet) {
459
+ getTemporaryContentUrlsForMedia(contentSet) {
460
+ var _a;
459
461
  // We ignore existing mcsMedia members of each of the media entries.
460
462
  // Instead we just collect their sids and pull new descriptors from a mediaSet GET endpoint.
461
- const sids = contentSet === null || contentSet === void 0 ? void 0 : contentSet.map((m) => m.sid);
462
- if (this.services.mcsClient && sids) {
463
- return (await this.services.mcsClient.mediaSetGet(sids)).map((item) => {
464
- return new media.Media(item, this.services);
463
+ const sids = (_a = contentSet === null || contentSet === void 0 ? void 0 : contentSet.map((m) => m.sid)) !== null && _a !== void 0 ? _a : [];
464
+ return this.getTemporaryContentUrlsForMediaSids(sids);
465
+ }
466
+ /**
467
+ * Get content URLs for all media attachments in the given set of media sids using a single operation.
468
+ * @param mediaSids Set of media sids to query for the content URL.
469
+ */
470
+ getTemporaryContentUrlsForMediaSids(mediaSids) {
471
+ return new mcsClient.CancellablePromise(async (resolve, reject, onCancel) => {
472
+ const mediaGetRequest = this.services.mcsClient.mediaSetGetContentUrls(mediaSids !== null && mediaSids !== void 0 ? mediaSids : []);
473
+ if (!this.services.mcsClient || !mediaSids) {
474
+ reject(new Error("Media Content Service is unavailable"));
475
+ return;
476
+ }
477
+ onCancel(() => {
478
+ mediaGetRequest.cancel();
465
479
  });
466
- }
467
- else {
468
- throw new Error("Media Content Service is unavailable");
469
- }
480
+ try {
481
+ const urls = await mediaGetRequest;
482
+ resolve(urls);
483
+ }
484
+ catch (e) {
485
+ reject(e);
486
+ }
487
+ });
488
+ }
489
+ /**
490
+ * Get content URLs for all media attached to the message.
491
+ */
492
+ getTemporaryContentUrlsForAttachedMedia() {
493
+ var _a;
494
+ const media = this.attachedMedia;
495
+ const sids = (_a = media === null || media === void 0 ? void 0 : media.map((m) => m.sid)) !== null && _a !== void 0 ? _a : [];
496
+ return this.getTemporaryContentUrlsForMediaSids(sids);
470
497
  }
471
498
  async _getDetailedDeliveryReceiptsPaginator(options) {
472
499
  const messagesReceiptsUrl = this.configuration.links.messagesReceipts
@@ -522,8 +549,8 @@ tslib_es6.__decorate([
522
549
  ])),
523
550
  tslib_es6.__metadata("design:type", Function),
524
551
  tslib_es6.__metadata("design:paramtypes", [Array]),
525
- tslib_es6.__metadata("design:returntype", Promise)
526
- ], Message.prototype, "attachTemporaryUrlsFor", null);
552
+ tslib_es6.__metadata("design:returntype", mcsClient.CancellablePromise)
553
+ ], Message.prototype, "getTemporaryContentUrlsForMedia", null);
527
554
 
528
555
  exports.Message = Message;
529
556
  //# sourceMappingURL=message.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"message.js","sources":["../src/message.ts"],"sourcesContent":["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"],"names":["Logger","ReplayEventEmitter","index","parseAttributes","Media","AggregatedDeliveryReceipt","isEqual","UriBuilder","RestPaginator","DetailedDeliveryReceipt","__decorate","validateTypes","nonEmptyString","validateTypesAsync","attributesValidator","custom"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,GAAG,GAAGA,aAAM,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;AAsEpC;;;AAGA,MAAM,OAAQ,SAAQC,qCAAiC;;;;IAerD,YACEC,OAAa,EACb,IAAiB,EACjB,YAA0B,EAC1B,KAAmB,EACnB,aAA4B,EAC5B,QAAyB;;QAEzB,KAAK,EAAE,CAAC;QAER,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QAEjC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAEzB,IAAI,CAAC,KAAK,GAAG;YACX,GAAG,EAAE,IAAI,CAAC,GAAG;YACb,KAAK,EAAEA,OAAK;YACZ,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,IAAI,EAAE,MAAA,IAAI,CAA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;+CAavC;AAcDJ;IARCG,2CAAkB,CACjBE,+BAAM,CAAC,CAAC,KAAK,KAAK;QAChB,KAAK,YAAY,KAAK;YACpB,KAAK,CAAC,MAAM,GAAG,CAAC;YAChB,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,YAAYX,WAAK,EAAE,IAAI,CAAC;QACvD,4BAA4B;KAC7B,CAAC,CACH;;;;qDAcA;;;;"}
1
+ {"version":3,"file":"message.js","sources":["../src/message.ts"],"sourcesContent":["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"],"names":["Logger","ReplayEventEmitter","index","parseAttributes","Media","AggregatedDeliveryReceipt","isEqual","CancellablePromise","UriBuilder","RestPaginator","DetailedDeliveryReceipt","__decorate","validateTypes","nonEmptyString","validateTypesAsync","attributesValidator","custom"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,MAAM,GAAG,GAAGA,aAAM,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;AAsEpC;;;AAGA,MAAM,OAAQ,SAAQC,qCAAiC;;;;IAerD,YACEC,OAAa,EACb,IAAiB,EACjB,YAA0B,EAC1B,KAAmB,EACnB,aAA4B,EAC5B,QAAyB;;QAEzB,KAAK,EAAE,CAAC;QAER,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QAEjC,IAAI,CAAC,KAAK,GAAG,KAAK,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AkB;8DAKpB;;;;"}
@@ -130,7 +130,7 @@ This software includes platform.js under the following license.
130
130
 
131
131
  Object.defineProperty(exports, '__esModule', { value: true });
132
132
 
133
- var version = "2.1.0-rc.8";
133
+ var version = "3.0.0-rc.1";
134
134
 
135
135
  exports.version = version;
136
136
  //# sourceMappingURL=package.json.js.map
@@ -130,6 +130,7 @@ This software includes platform.js under the following license.
130
130
 
131
131
  Object.defineProperty(exports, '__esModule', { value: true });
132
132
 
133
+ var mcsClient = require('@twilio/mcs-client');
133
134
  var index = require('./util/index.js');
134
135
 
135
136
  /**
@@ -149,9 +150,18 @@ class UnsentMessage {
149
150
  * Send the prepared message to the conversation.
150
151
  * @returns Index of the new message in the conversation.
151
152
  */
152
- async send() {
153
- const response = await this.messagesEntity.sendV2(this);
154
- return index.parseToNumber(response.index);
153
+ send() {
154
+ return new mcsClient.CancellablePromise(async (resolve, reject, onCancel) => {
155
+ const request = this.messagesEntity.sendV2(this);
156
+ onCancel(() => request.cancel());
157
+ try {
158
+ const response = await request;
159
+ resolve(index.parseToNumber(response.index));
160
+ }
161
+ catch (e) {
162
+ reject(e);
163
+ }
164
+ });
155
165
  }
156
166
  }
157
167
 
@@ -1 +1 @@
1
- {"version":3,"file":"unsent-message.js","sources":["../src/unsent-message.ts"],"sourcesContent":["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"],"names":["parseToNumber"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA;;;AAGA,MAAM,aAAa;;;;IASjB,YAAoB,cAAc;QAAd,mBAAc,GAAd,cAAc,CAAA;QAP3B,eAAU,GAAc,EAAE,CAAC;QAC3B,iBAAY,GAAmD,EAAE,CAAC;QAClE,iBAAY,GAAqB,EAAE,CAAC;KAKL;;;;;IAMtC,MAAM,IAAI;QACR,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QACxD,OAAOA,mBAAa,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;KACtC;;;;;"}
1
+ {"version":3,"file":"unsent-message.js","sources":["../src/unsent-message.ts"],"sourcesContent":["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"],"names":["CancellablePromise","parseToNumber"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA;;;AAGA,MAAM,aAAa;;;;IASjB,YAAoB,cAAwB;QAAxB,mBAAc,GAAd,cAAc,CAAU;QAPrC,eAAU,GAAc,EAAE,CAAC;QAC3B,iBAAY,GAAmD,EAAE,CAAC;QAClE,iBAAY,GAAqB,EAAE,CAAC;KAKK;;;;;IAMhD,IAAI;QACF,OAAO,IAAIA,4BAAkB,CAAC,OAAO,OAAO,EAAE,MAAM,EAAE,QAAQ;YAC5D,MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACjD,QAAQ,CAAC,MAAM,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;YACjC,IAAI;gBACF,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC;gBAC/B,OAAO,CAACC,mBAAa,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;aACxC;YAAC,OAAO,CAAC,EAAE;gBACV,MAAM,CAAC,CAAC,CAAC,CAAC;aACX;SACF,CAAC,CAAC;KACJ;;;;;"}