@twilio/conversations 1.3.0-rc8 → 2.0.0-rc.4

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.
Files changed (282) hide show
  1. package/CHANGELOG.md +210 -0
  2. package/README.md +22 -17
  3. package/dist/browser.js +7873 -0
  4. package/dist/browser.js.map +1 -0
  5. package/dist/docs/assets/css/main.css +2660 -0
  6. package/dist/docs/assets/images/icons.png +0 -0
  7. package/dist/docs/assets/images/icons@2x.png +0 -0
  8. package/dist/docs/assets/images/widgets.png +0 -0
  9. package/dist/docs/assets/images/widgets@2x.png +0 -0
  10. package/dist/docs/assets/js/main.js +248 -0
  11. package/dist/docs/assets/js/search.js +1 -0
  12. package/dist/docs/classes/AggregatedDeliveryReceipt.html +3286 -0
  13. package/dist/docs/classes/Client.html +4181 -0
  14. package/dist/docs/classes/Conversation.html +4397 -0
  15. package/dist/docs/classes/DetailedDeliveryReceipt.html +3265 -0
  16. package/dist/docs/classes/Media.html +3295 -0
  17. package/dist/docs/classes/Message.html +3713 -0
  18. package/dist/docs/classes/MessageBuilder.html +3280 -0
  19. package/dist/docs/classes/Participant.html +3517 -0
  20. package/dist/docs/classes/PushNotification.html +3232 -0
  21. package/dist/docs/classes/RestPaginator.html +3262 -0
  22. package/dist/docs/classes/UnsentMessage.html +3144 -0
  23. package/dist/docs/classes/User.html +3451 -0
  24. package/dist/docs/index.html +3394 -212
  25. package/dist/docs/interfaces/ClientOptions.html +3136 -0
  26. package/dist/docs/interfaces/ConversationState.html +3152 -0
  27. package/dist/docs/interfaces/CreateConversationOptions.html +3168 -0
  28. package/dist/docs/interfaces/LastMessage.html +3152 -0
  29. package/dist/docs/interfaces/Paginator.html +3243 -0
  30. package/dist/docs/interfaces/PushNotificationData.html +3168 -0
  31. package/dist/docs/interfaces/SendEmailOptions.html +3136 -0
  32. package/dist/docs/interfaces/SendMediaOptions.html +3170 -0
  33. package/dist/docs/modules.html +3425 -0
  34. package/dist/lib.d.ts +1952 -0
  35. package/dist/lib.js +7873 -0
  36. package/dist/lib.js.map +1 -0
  37. package/dist/post-install.js +29 -0
  38. package/dist/react-native.js +4038 -0
  39. package/dist/react-native.js.map +1 -0
  40. package/dist/twilio-conversations.js +40912 -0
  41. package/dist/twilio-conversations.min.js +156 -0
  42. package/package.json +59 -48
  43. package/.circleci/config.yml +0 -650
  44. package/.deepsource.toml +0 -6
  45. package/.env.example +0 -13
  46. package/browser/aggregateddeliveryreceipt.js +0 -152
  47. package/browser/client.js +0 -991
  48. package/browser/configuration.js +0 -80
  49. package/browser/conversation.js +0 -1826
  50. package/browser/data/conversations.js +0 -632
  51. package/browser/data/messages.js +0 -522
  52. package/browser/data/participants.js +0 -411
  53. package/browser/data/users.js +0 -281
  54. package/browser/detaileddeliveryreceipt.js +0 -44
  55. package/browser/index.js +0 -4
  56. package/browser/interfaces/limits.js +0 -3
  57. package/browser/interfaces/notificationtypes.js +0 -21
  58. package/browser/interfaces/paginator.js +0 -53
  59. package/browser/interfaces/responsecodes.js +0 -20
  60. package/browser/interfaces/transport.js +0 -3
  61. package/browser/logger.js +0 -141
  62. package/browser/media.js +0 -198
  63. package/browser/message.js +0 -685
  64. package/browser/participant.js +0 -415
  65. package/browser/pushnotification.js +0 -49
  66. package/browser/restpaginator.js +0 -74
  67. package/browser/services/network.js +0 -223
  68. package/browser/services/readhorizon.js +0 -181
  69. package/browser/services/typingindicator.js +0 -142
  70. package/browser/session.js +0 -505
  71. package/browser/sessionerror.js +0 -93
  72. package/browser/sri.json +0 -1
  73. package/browser/synclist.js +0 -90
  74. package/browser/synclistdescriptor.js +0 -29
  75. package/browser/syncpaginator.js +0 -63
  76. package/browser/user.js +0 -431
  77. package/browser/util/deferred.js +0 -56
  78. package/browser/util/index.js +0 -108
  79. package/dist/@twilio/conversations.js +0 -35533
  80. package/dist/@twilio/conversations.min.js +0 -204
  81. package/dist/docs/AggregatedDeliveryReceipt.html +0 -948
  82. package/dist/docs/Client.html +0 -5075
  83. package/dist/docs/Conversation.html +0 -6018
  84. package/dist/docs/DetailedDeliveryReceipt.html +0 -641
  85. package/dist/docs/Media.html +0 -694
  86. package/dist/docs/Message.html +0 -1934
  87. package/dist/docs/Paginator.html +0 -605
  88. package/dist/docs/Participant.html +0 -1510
  89. package/dist/docs/PushNotification.html +0 -836
  90. package/dist/docs/SessionError.html +0 -379
  91. package/dist/docs/User.html +0 -1315
  92. package/dist/docs/classes.list.html +0 -4431
  93. package/dist/docs/fonts/glyphicons-halflings-regular.eot +0 -0
  94. package/dist/docs/fonts/glyphicons-halflings-regular.svg +0 -288
  95. package/dist/docs/fonts/glyphicons-halflings-regular.ttf +0 -0
  96. package/dist/docs/fonts/glyphicons-halflings-regular.woff +0 -0
  97. package/dist/docs/fonts/glyphicons-halflings-regular.woff2 +0 -0
  98. package/dist/docs/img/glyphicons-halflings-white.png +0 -0
  99. package/dist/docs/img/glyphicons-halflings.png +0 -0
  100. package/dist/docs/quicksearch.html +0 -31
  101. package/dist/docs/scripts/docstrap.lib.js +0 -11
  102. package/dist/docs/scripts/fulltext-search-ui.js +0 -89
  103. package/dist/docs/scripts/fulltext-search.js +0 -36
  104. package/dist/docs/scripts/lunr.min.js +0 -6
  105. package/dist/docs/scripts/prettify/Apache-License-2.0.txt +0 -202
  106. package/dist/docs/scripts/prettify/jquery.min.js +0 -6
  107. package/dist/docs/scripts/prettify/lang-css.js +0 -21
  108. package/dist/docs/scripts/prettify/prettify.js +0 -496
  109. package/dist/docs/scripts/sunlight.js +0 -1157
  110. package/dist/docs/scripts/toc.js +0 -203
  111. package/dist/docs/styles/darkstrap.css +0 -960
  112. package/dist/docs/styles/prettify-tomorrow.css +0 -132
  113. package/dist/docs/styles/site.cerulean.css +0 -7008
  114. package/dist/docs/styles/site.cosmo.css +0 -7061
  115. package/dist/docs/styles/site.cyborg.css +0 -7048
  116. package/dist/docs/styles/site.darkly.css +0 -7171
  117. package/dist/docs/styles/site.darkstrap.css +0 -5638
  118. package/dist/docs/styles/site.dibs-bootstrap.css +0 -5899
  119. package/dist/docs/styles/site.flatly.css +0 -7147
  120. package/dist/docs/styles/site.journal.css +0 -6973
  121. package/dist/docs/styles/site.lumen.css +0 -7298
  122. package/dist/docs/styles/site.paper.css +0 -7623
  123. package/dist/docs/styles/site.readable.css +0 -6997
  124. package/dist/docs/styles/site.sandstone.css +0 -7035
  125. package/dist/docs/styles/site.simplex.css +0 -7023
  126. package/dist/docs/styles/site.slate.css +0 -7343
  127. package/dist/docs/styles/site.spacelab.css +0 -7055
  128. package/dist/docs/styles/site.superhero.css +0 -7131
  129. package/dist/docs/styles/site.united.css +0 -6895
  130. package/dist/docs/styles/site.yeti.css +0 -7195
  131. package/dist/docs/styles/sunlight.dark.css +0 -345
  132. package/dist/docs/styles/sunlight.default.css +0 -344
  133. package/dist/sri.json +0 -1
  134. package/lib/aggregateddeliveryreceipt.d.ts +0 -98
  135. package/lib/aggregateddeliveryreceipt.js +0 -112
  136. package/lib/client.d.ts +0 -317
  137. package/lib/client.js +0 -633
  138. package/lib/configuration.d.ts +0 -21
  139. package/lib/configuration.js +0 -41
  140. package/lib/conversation.d.ts +0 -460
  141. package/lib/conversation.js +0 -940
  142. package/lib/data/conversations.d.ts +0 -57
  143. package/lib/data/conversations.js +0 -296
  144. package/lib/data/messages.d.ts +0 -75
  145. package/lib/data/messages.js +0 -208
  146. package/lib/data/participants.d.ts +0 -94
  147. package/lib/data/participants.js +0 -204
  148. package/lib/data/users.d.ts +0 -42
  149. package/lib/data/users.js +0 -113
  150. package/lib/detaileddeliveryreceipt.d.ts +0 -45
  151. package/lib/detaileddeliveryreceipt.js +0 -34
  152. package/lib/index.d.ts +0 -1
  153. package/lib/index.js +0 -3
  154. package/lib/interfaces/limits.d.ts +0 -8
  155. package/lib/interfaces/limits.js +0 -2
  156. package/lib/interfaces/notificationtypes.d.ts +0 -8
  157. package/lib/interfaces/notificationtypes.js +0 -11
  158. package/lib/interfaces/paginator.d.ts +0 -52
  159. package/lib/interfaces/paginator.js +0 -28
  160. package/lib/interfaces/responsecodes.d.ts +0 -8
  161. package/lib/interfaces/responsecodes.js +0 -10
  162. package/lib/interfaces/transport.d.ts +0 -13
  163. package/lib/interfaces/transport.js +0 -2
  164. package/lib/logger.d.ts +0 -18
  165. package/lib/logger.js +0 -35
  166. package/lib/media.d.ts +0 -52
  167. package/lib/media.js +0 -69
  168. package/lib/message.d.ts +0 -136
  169. package/lib/message.js +0 -305
  170. package/lib/participant.d.ts +0 -142
  171. package/lib/participant.js +0 -219
  172. package/lib/pushnotification.d.ts +0 -48
  173. package/lib/pushnotification.js +0 -39
  174. package/lib/restpaginator.d.ts +0 -19
  175. package/lib/restpaginator.js +0 -36
  176. package/lib/services/network.d.ts +0 -22
  177. package/lib/services/network.js +0 -87
  178. package/lib/services/readhorizon.d.ts +0 -28
  179. package/lib/services/readhorizon.js +0 -112
  180. package/lib/services/typingindicator.d.ts +0 -50
  181. package/lib/services/typingindicator.js +0 -102
  182. package/lib/session.d.ts +0 -63
  183. package/lib/session.js +0 -213
  184. package/lib/sessionerror.d.ts +0 -12
  185. package/lib/sessionerror.js +0 -24
  186. package/lib/sri.json +0 -1
  187. package/lib/synclist.d.ts +0 -24
  188. package/lib/synclist.js +0 -28
  189. package/lib/synclistdescriptor.d.ts +0 -27
  190. package/lib/synclistdescriptor.js +0 -19
  191. package/lib/syncpaginator.d.ts +0 -22
  192. package/lib/syncpaginator.js +0 -37
  193. package/lib/user.d.ts +0 -98
  194. package/lib/user.js +0 -219
  195. package/lib/util/deferred.d.ts +0 -12
  196. package/lib/util/deferred.js +0 -22
  197. package/lib/util/index.d.ts +0 -28
  198. package/lib/util/index.js +0 -82
  199. package/tools/rtd-sdk-cdn-pin/.gitrepo +0 -12
  200. package/tools/rtd-sdk-cdn-pin/README.md +0 -54
  201. package/tools/rtd-sdk-cdn-pin/bintray-settings.xml.template +0 -16
  202. package/tools/rtd-sdk-cdn-pin/cdn-common/cdn-prepare.sh +0 -67
  203. package/tools/rtd-sdk-cdn-pin/cdn-pin-latest.sh +0 -19
  204. package/tools/rtd-sdk-cdn-pin/cdn-pin.sh +0 -19
  205. package/tools/rtd-sdk-cdn-pin/cdn-upload.sh +0 -13
  206. package/tools/rtd-sdk-cdn-pin/fetch/common/fetch-bintray-android.sh +0 -34
  207. package/tools/rtd-sdk-cdn-pin/fetch/common/fetch-npm.sh +0 -18
  208. package/tools/rtd-sdk-cdn-pin/fetch/twilio-chat-android.sh +0 -5
  209. package/tools/rtd-sdk-cdn-pin/fetch/twilio-chat-js.sh +0 -5
  210. package/tools/rtd-sdk-cdn-pin/fetch/twilio-conversations-android.sh +0 -6
  211. package/tools/rtd-sdk-cdn-pin/fetch/twilio-conversations-js.sh +0 -5
  212. package/tools/rtd-sdk-cdn-pin/fetch/twilio-sync-android.sh +0 -5
  213. package/tools/rtd-sdk-cdn-pin/fetch/twilio-sync-js.sh +0 -5
  214. package/tools/rtd-sdk-cdn-pin/fetch-artifact.sh +0 -26
  215. package/tools/sdk-release-tool/.gitrepo +0 -12
  216. package/tools/sdk-release-tool/Makefile +0 -49
  217. package/tools/sdk-release-tool/README.md +0 -275
  218. package/tools/sdk-release-tool/delete +0 -3
  219. package/tools/sdk-release-tool/download +0 -3
  220. package/tools/sdk-release-tool/get-cors +0 -3
  221. package/tools/sdk-release-tool/list +0 -3
  222. package/tools/sdk-release-tool/pin +0 -3
  223. package/tools/sdk-release-tool/pin-latest +0 -3
  224. package/tools/sdk-release-tool/requirements.txt +0 -4
  225. package/tools/sdk-release-tool/sdk-release-tool +0 -3
  226. package/tools/sdk-release-tool/sdk_release_tools/__init__.py +0 -0
  227. package/tools/sdk-release-tool/sdk_release_tools/__main__.py +0 -110
  228. package/tools/sdk-release-tool/sdk_release_tools/aws.py +0 -70
  229. package/tools/sdk-release-tool/sdk_release_tools/cli.py +0 -181
  230. package/tools/sdk-release-tool/sdk_release_tools/log.py +0 -24
  231. package/tools/sdk-release-tool/sdk_release_tools/ops.py +0 -295
  232. package/tools/sdk-release-tool/sdk_release_tools/rpm.py +0 -28
  233. package/tools/sdk-release-tool/sdk_release_tools/util.py +0 -186
  234. package/tools/sdk-release-tool/sdk_release_tools/versions.py +0 -362
  235. package/tools/sdk-release-tool/signal-sdk-js.json +0 -28
  236. package/tools/sdk-release-tool/tests/test_versions.py +0 -94
  237. package/tools/sdk-release-tool/twilio-accessmanager-android.json +0 -19
  238. package/tools/sdk-release-tool/twilio-accessmanager-ios.json +0 -26
  239. package/tools/sdk-release-tool/twilio-auth-ios.json +0 -29
  240. package/tools/sdk-release-tool/twilio-authenticator-ios.json +0 -29
  241. package/tools/sdk-release-tool/twilio-chat-android-2.json +0 -19
  242. package/tools/sdk-release-tool/twilio-chat-android.json +0 -22
  243. package/tools/sdk-release-tool/twilio-chat-ios.json +0 -26
  244. package/tools/sdk-release-tool/twilio-chat-js.json +0 -27
  245. package/tools/sdk-release-tool/twilio-client-android-aar.json +0 -22
  246. package/tools/sdk-release-tool/twilio-client-android.json +0 -22
  247. package/tools/sdk-release-tool/twilio-client-ios.json +0 -20
  248. package/tools/sdk-release-tool/twilio-client-js.json +0 -17
  249. package/tools/sdk-release-tool/twilio-client-sounds-js.json +0 -14
  250. package/tools/sdk-release-tool/twilio-common-android-maven.json +0 -16
  251. package/tools/sdk-release-tool/twilio-common-android.json +0 -22
  252. package/tools/sdk-release-tool/twilio-common-ios-rtc.json +0 -25
  253. package/tools/sdk-release-tool/twilio-common-ios.json +0 -25
  254. package/tools/sdk-release-tool/twilio-common-js.json +0 -19
  255. package/tools/sdk-release-tool/twilio-conversations-android.json +0 -22
  256. package/tools/sdk-release-tool/twilio-conversations-ios.json +0 -26
  257. package/tools/sdk-release-tool/twilio-conversations-js.json +0 -27
  258. package/tools/sdk-release-tool/twilio-flex-js.json +0 -20
  259. package/tools/sdk-release-tool/twilio-flex-webchat-js.json +0 -16
  260. package/tools/sdk-release-tool/twilio-frame-chat-android.json +0 -22
  261. package/tools/sdk-release-tool/twilio-frame-chat-ios.json +0 -23
  262. package/tools/sdk-release-tool/twilio-frame-chat-js.json +0 -23
  263. package/tools/sdk-release-tool/twilio-ip-messaging-android-maven.json +0 -16
  264. package/tools/sdk-release-tool/twilio-ip-messaging-android.json +0 -22
  265. package/tools/sdk-release-tool/twilio-ip-messaging-ios.json +0 -25
  266. package/tools/sdk-release-tool/twilio-ip-messaging-js.json +0 -21
  267. package/tools/sdk-release-tool/twilio-sync-android.json +0 -22
  268. package/tools/sdk-release-tool/twilio-sync-ios.json +0 -26
  269. package/tools/sdk-release-tool/twilio-sync-js.json +0 -39
  270. package/tools/sdk-release-tool/twilio-taskrouter-js.json +0 -17
  271. package/tools/sdk-release-tool/twilio-video-android.json +0 -22
  272. package/tools/sdk-release-tool/twilio-video-cpp-linux-cross-rootfs.json +0 -13
  273. package/tools/sdk-release-tool/twilio-video-cpp.json +0 -33
  274. package/tools/sdk-release-tool/twilio-video-ios.json +0 -25
  275. package/tools/sdk-release-tool/twilio-video-js.json +0 -19
  276. package/tools/sdk-release-tool/twilio-video-jsdocs.json +0 -14
  277. package/tools/sdk-release-tool/twilio-voice-android.json +0 -22
  278. package/tools/sdk-release-tool/twilio-voice-ios.json +0 -29
  279. package/tools/sdk-release-tool/unpin +0 -3
  280. package/tools/sdk-release-tool/unpin-latest +0 -3
  281. package/tools/sdk-release-tool/upload +0 -3
  282. package/twilio-chat.js.iml +0 -9
@@ -0,0 +1,4038 @@
1
+ /*
2
+ @license
3
+ The following license applies to all parts of this software except as
4
+ documented below.
5
+
6
+ Copyright (c) 2019, Twilio, inc.
7
+ All rights reserved.
8
+
9
+ Redistribution and use in source and binary forms, with or without
10
+ modification, are permitted provided that the following conditions are
11
+ met:
12
+
13
+ 1. Redistributions of source code must retain the above copyright
14
+ notice, this list of conditions and the following disclaimer.
15
+
16
+ 2. Redistributions in binary form must reproduce the above copyright
17
+ notice, this list of conditions and the following disclaimer in
18
+ the documentation and/or other materials provided with the
19
+ distribution.
20
+
21
+ 3. Neither the name of Twilio nor the names of its contributors may
22
+ be used to endorse or promote products derived from this software
23
+ without specific prior written permission.
24
+
25
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36
+
37
+ This software includes javascript-state-machine under the following license.
38
+
39
+ Copyright (c) 2012, 2013, 2014, 2015, Jake Gordon and contributors
40
+
41
+ Permission is hereby granted, free of charge, to any person obtaining a copy
42
+ of this software and associated documentation files (the "Software"), to deal
43
+ in the Software without restriction, including without limitation the rights
44
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
45
+ copies of the Software, and to permit persons to whom the Software is
46
+ furnished to do so, subject to the following conditions:
47
+
48
+ The above copyright notice and this permission notice shall be included in all
49
+ copies or substantial portions of the Software.
50
+
51
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
52
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
53
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
54
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
55
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
56
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
57
+
58
+ This software includes loglevel under the following license.
59
+
60
+ Copyright (c) 2013 Tim Perry
61
+
62
+ Permission is hereby granted, free of charge, to any person
63
+ obtaining a copy of this software and associated documentation
64
+ files (the "Software"), to deal in the Software without
65
+ restriction, including without limitation the rights to use,
66
+ copy, modify, merge, publish, distribute, sublicense, and/or sell
67
+ copies of the Software, and to permit persons to whom the
68
+ Software is furnished to do so, subject to the following
69
+ conditions:
70
+
71
+ The above copyright notice and this permission notice shall be
72
+ included in all copies or substantial portions of the Software.
73
+
74
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
75
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
76
+ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
77
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
78
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
79
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
80
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
81
+ OTHER DEALINGS IN THE SOFTWARE.
82
+
83
+ This software includes q under the following license.
84
+
85
+ Copyright 2009–2014 Kristopher Michael Kowal. All rights reserved.
86
+ Permission is hereby granted, free of charge, to any person obtaining a copy
87
+ of this software and associated documentation files (the "Software"), to
88
+ deal in the Software without restriction, including without limitation the
89
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
90
+ sell copies of the Software, and to permit persons to whom the Software is
91
+ furnished to do so, subject to the following conditions:
92
+
93
+ The above copyright notice and this permission notice shall be included in
94
+ all copies or substantial portions of the Software.
95
+
96
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
97
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
98
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
99
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
100
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
101
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
102
+ IN THE SOFTWARE.
103
+
104
+ This software includes platform.js under the following license.
105
+
106
+ Copyright 2014 Benjamin Tan <https://d10.github.io/>
107
+ Copyright 2011-2015 John-David Dalton <http://allyoucanleet.com/>
108
+
109
+ Permission is hereby granted, free of charge, to any person obtaining
110
+ a copy of this software and associated documentation files (the
111
+ "Software"), to deal in the Software without restriction, including
112
+ without limitation the rights to use, copy, modify, merge, publish,
113
+ distribute, sublicense, and/or sell copies of the Software, and to
114
+ permit persons to whom the Software is furnished to do so, subject to
115
+ the following conditions:
116
+
117
+ The above copyright notice and this permission notice shall be
118
+ included in all copies or substantial portions of the Software.
119
+
120
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
121
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
122
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
123
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
124
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
125
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
126
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
127
+
128
+ */
129
+ 'use strict';
130
+
131
+ Object.defineProperty(exports, '__esModule', { value: true });
132
+
133
+ var loglevelLog = require('loglevel');
134
+ var iso8601Duration = require('iso8601-duration');
135
+ var JsonDiff = require('rfc6902');
136
+ var declarativeTypeValidator = require('@twilio/declarative-type-validator');
137
+ var replayEventEmitter = require('@twilio/replay-event-emitter');
138
+ var operationRetrier = require('@twilio/operation-retrier');
139
+ var twilsock = require('twilsock');
140
+ var notifications = require('@twilio/notifications');
141
+ var twilioSync = require('twilio-sync');
142
+ var mcsClient = require('@twilio/mcs-client');
143
+ var uuid = require('uuid');
144
+
145
+ function _interopNamespace(e) {
146
+ if (e && e.__esModule) return e;
147
+ var n = Object.create(null);
148
+ if (e) {
149
+ Object.keys(e).forEach(function (k) {
150
+ if (k !== 'default') {
151
+ var d = Object.getOwnPropertyDescriptor(e, k);
152
+ Object.defineProperty(n, k, d.get ? d : {
153
+ enumerable: true,
154
+ get: function () {
155
+ return e[k];
156
+ }
157
+ });
158
+ }
159
+ });
160
+ }
161
+ n['default'] = e;
162
+ return Object.freeze(n);
163
+ }
164
+
165
+ var loglevelLog__namespace = /*#__PURE__*/_interopNamespace(loglevelLog);
166
+ var JsonDiff__namespace = /*#__PURE__*/_interopNamespace(JsonDiff);
167
+
168
+ /*! *****************************************************************************
169
+ Copyright (c) Microsoft Corporation.
170
+
171
+ Permission to use, copy, modify, and/or distribute this software for any
172
+ purpose with or without fee is hereby granted.
173
+
174
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
175
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
176
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
177
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
178
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
179
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
180
+ PERFORMANCE OF THIS SOFTWARE.
181
+ ***************************************************************************** */
182
+
183
+ function __decorate(decorators, target, key, desc) {
184
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
185
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
186
+ 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;
187
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
188
+ }
189
+
190
+ function __metadata(metadataKey, metadataValue) {
191
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
192
+ }
193
+
194
+ function prepareLine(prefix, args) {
195
+ return [`${new Date().toISOString()} Conversations ${prefix}:`].concat(Array.from(args));
196
+ }
197
+ const log$9 = loglevelLog__namespace.getLogger('twilio-conversations'); // twilio-conversations is used by Flex SDK. Please DO NOT change
198
+ class Logger {
199
+ constructor(prefix) {
200
+ this.prefix = '';
201
+ this.prefix = prefix !== null && prefix !== undefined && prefix.length > 0
202
+ ? prefix + ' '
203
+ : '';
204
+ }
205
+ static scope(prefix) {
206
+ return new Logger(prefix);
207
+ }
208
+ setLevel(level) {
209
+ log$9.setLevel(level);
210
+ }
211
+ static setLevel(level) {
212
+ log$9.setLevel(level);
213
+ }
214
+ trace(...args) { log$9.trace.apply(null, prepareLine(this.prefix + 'T', args)); }
215
+ debug(...args) { log$9.debug.apply(null, prepareLine(this.prefix + 'D', args)); }
216
+ info(...args) { log$9.info.apply(null, prepareLine(this.prefix + 'I', args)); }
217
+ warn(...args) { log$9.warn.apply(null, prepareLine(this.prefix + 'W', args)); }
218
+ error(...args) { log$9.error.apply(null, prepareLine(this.prefix + 'E', args)); }
219
+ static trace(...args) { log$9.trace.apply(null, prepareLine('T', args)); }
220
+ static debug(...args) { log$9.debug.apply(null, prepareLine('D', args)); }
221
+ static info(...args) { log$9.info.apply(null, prepareLine('I', args)); }
222
+ static warn(...args) { log$9.warn.apply(null, prepareLine('W', args)); }
223
+ static error(...args) { log$9.error.apply(null, prepareLine('E', args)); }
224
+ }
225
+
226
+ const TYPING_TIMEOUT = 5;
227
+ const HTTP_CACHE_LIFETIME = 'PT5S';
228
+ const CONSUMPTION_HORIZON_SENDING_INTERVAL = 'PT5S';
229
+ const USER_INFOS_TO_SUBSCRIBE = 100;
230
+ const MINIMUM_RETRY_DELAY = 1000;
231
+ const MAXIMUM_RETRY_DELAY = 4000;
232
+ const MAXIMUM_ATTEMPTS_COUNT = 3;
233
+ const RETRY_WHEN_THROTTLED = true;
234
+ class Configuration {
235
+ constructor(options = {}, configurationResponse, logger) {
236
+ var _a, _b, _c, _d, _e, _f;
237
+ this.typingIndicatorTimeoutDefault = TYPING_TIMEOUT * 1000;
238
+ const constructorOptions = options.Chat || options.IPMessaging || options || {};
239
+ this.productId = constructorOptions.productId;
240
+ this.links = {
241
+ myConversations: configurationResponse.links.my_conversations,
242
+ conversations: configurationResponse.links.conversations,
243
+ users: configurationResponse.links.users,
244
+ currentUser: configurationResponse.links.current_user,
245
+ typing: configurationResponse.links.typing,
246
+ mediaService: configurationResponse.links.media_service,
247
+ mediaSetService: configurationResponse.links.media_set_service,
248
+ messagesReceipts: configurationResponse.links.messages_receipts
249
+ };
250
+ this.limits = {
251
+ mediaAttachmentsCountLimit: configurationResponse.options.media_attachments_count_limit,
252
+ mediaAttachmentSizeLimitInMb: configurationResponse.options.media_attachment_size_limit_in_mb,
253
+ mediaAttachmentsTotalSizeLimitInMb: configurationResponse.options.media_attachments_total_size_limit_in_mb,
254
+ emailHistoriesAllowedMimeTypes: configurationResponse.options.email_histories_allowed_mime_types,
255
+ emailBodiesAllowedMimeTypes: configurationResponse.options.email_bodies_allowed_mime_types
256
+ };
257
+ this.typingIndicatorTimeoutOverride = constructorOptions.typingIndicatorTimeoutOverride;
258
+ this.backoffConfiguration = Object.assign({ min: MINIMUM_RETRY_DELAY, max: MAXIMUM_RETRY_DELAY, maxAttemptsCount: MAXIMUM_ATTEMPTS_COUNT }, constructorOptions.backoffConfigOverride);
259
+ this.retryWhenThrottled = constructorOptions.retryWhenThrottledOverride !== undefined
260
+ ? constructorOptions.retryWhenThrottledOverride
261
+ : RETRY_WHEN_THROTTLED;
262
+ this.userInfosToSubscribe = (_b = (_a = constructorOptions.userInfosToSubscribeOverride) !== null && _a !== void 0 ? _a : configurationResponse.options.user_infos_to_subscribe) !== null && _b !== void 0 ? _b : USER_INFOS_TO_SUBSCRIBE;
263
+ this.reachabilityEnabled = configurationResponse.options.reachability_enabled;
264
+ this.userIdentity = configurationResponse.identity;
265
+ this.userInfo = configurationResponse.sync_objects.my_user_info;
266
+ this.myConversations = configurationResponse.sync_objects.my_conversations;
267
+ const httpCacheInterval = (_d = (_c = constructorOptions.httpCacheIntervalOverride) !== null && _c !== void 0 ? _c : configurationResponse.options.http_cache_interval) !== null && _d !== void 0 ? _d : HTTP_CACHE_LIFETIME;
268
+ try {
269
+ this.httpCacheInterval = iso8601Duration.toSeconds(iso8601Duration.parse(httpCacheInterval));
270
+ }
271
+ catch (_g) {
272
+ logger.error(`Failed to parse http cache interval ${httpCacheInterval}, using default value ${HTTP_CACHE_LIFETIME}`);
273
+ this.httpCacheInterval = iso8601Duration.toSeconds(iso8601Duration.parse(HTTP_CACHE_LIFETIME));
274
+ }
275
+ const consumptionReportInterval = (_f = (_e = constructorOptions.consumptionReportIntervalOverride) !== null && _e !== void 0 ? _e : configurationResponse.options.consumption_report_interval) !== null && _f !== void 0 ? _f : CONSUMPTION_HORIZON_SENDING_INTERVAL;
276
+ try {
277
+ this.consumptionReportInterval = iso8601Duration.toSeconds(iso8601Duration.parse(consumptionReportInterval));
278
+ }
279
+ catch (_h) {
280
+ logger.error(`Failed to parse consumption report interval ${consumptionReportInterval}, using default value ${CONSUMPTION_HORIZON_SENDING_INTERVAL}`);
281
+ this.consumptionReportInterval = iso8601Duration.toSeconds(iso8601Duration.parse(CONSUMPTION_HORIZON_SENDING_INTERVAL));
282
+ }
283
+ }
284
+ }
285
+
286
+ /**
287
+ * Checks if objects are equal
288
+ */
289
+ function isDeepEqual(o1, o2) {
290
+ return JsonDiff__namespace.createPatch(o1, o2).length === 0;
291
+ }
292
+ /**
293
+ * Deep-clone an object. Note that this does not work on object containing
294
+ * functions.
295
+ * @param {object} obj - the object to deep-clone
296
+ * @returns {object}
297
+ */
298
+ function deepClone(obj) {
299
+ return JSON.parse(JSON.stringify(obj));
300
+ }
301
+ function parseToNumber(value) {
302
+ if (typeof value !== 'undefined' && !isNaN(Number(value))) {
303
+ return Number(value);
304
+ }
305
+ return null;
306
+ }
307
+ // timeString cannot be typed `string` because in member.ts
308
+ // call to parseTime(data.lastReadTimestamp) uses number not a string for timestamp.
309
+ function parseTime$1(timeString) {
310
+ try {
311
+ return new Date(timeString);
312
+ }
313
+ catch (e) {
314
+ return null;
315
+ }
316
+ }
317
+ function parseAttributes(rawAttributes, warningMessage, log) {
318
+ let attributes = {};
319
+ if (rawAttributes) {
320
+ try {
321
+ attributes = JSON.parse(rawAttributes);
322
+ }
323
+ catch (e) {
324
+ log.warn(warningMessage, e);
325
+ }
326
+ }
327
+ return attributes;
328
+ }
329
+ /**
330
+ * Construct URI with query parameters
331
+ */
332
+ class UriBuilder {
333
+ constructor(base) {
334
+ this.base = base.replace(/\/$/, '');
335
+ this.args = [];
336
+ this.paths = [];
337
+ }
338
+ arg(name, value) {
339
+ if (typeof value !== 'undefined') {
340
+ this.args.push(encodeURIComponent(name) + '=' + encodeURIComponent(value));
341
+ }
342
+ return this;
343
+ }
344
+ path(name) {
345
+ this.paths.push(encodeURIComponent(name));
346
+ return this;
347
+ }
348
+ build() {
349
+ let result = this.base;
350
+ if (this.paths.length) {
351
+ result += '/' + this.paths.join('/');
352
+ }
353
+ if (this.args.length) {
354
+ result += '?' + this.args.join('&');
355
+ }
356
+ return result;
357
+ }
358
+ }
359
+
360
+ const log$8 = Logger.scope('User');
361
+ /**
362
+ * Extended user information.
363
+ * Note that `isOnline` and `isNotifiable` properties are eligible
364
+ * for use only if the reachability function is enabled.
365
+ * You may check if it is enabled by reading the value of {@link Client.reachabilityEnabled}.
366
+ */
367
+ class User extends replayEventEmitter.ReplayEventEmitter {
368
+ /**
369
+ * @internal
370
+ */
371
+ constructor(identity, entityName, configuration, services) {
372
+ super();
373
+ this.promiseToFetch = null;
374
+ /**
375
+ * Fired when the properties or the reachability status of the message has been updated.
376
+ *
377
+ * Parameters:
378
+ * 1. object `data` - info object provided with the event. It has the following properties:
379
+ * * {@link User} `user` - the user in question
380
+ * * {@link UserUpdateReason}[] `updateReasons` - array of reasons for the update
381
+ * @event
382
+ */
383
+ this.updated = 'updated';
384
+ /**
385
+ * Fired when the client has subscribed to the user.
386
+ *
387
+ * Parameters:
388
+ * 1. {@link User} `user` - the user in question
389
+ * @event
390
+ */
391
+ this.userSubscribed = 'userSubscribed';
392
+ /**
393
+ * Fired when the client has unsubscribed from the user.
394
+ *
395
+ * Parameters:
396
+ * 1. {@link User} `user` - the user in question
397
+ * @event
398
+ */
399
+ this.userUnsubscribed = 'userUnsubscribed';
400
+ this.services = services;
401
+ this.subscribed = 'initializing';
402
+ this.setMaxListeners(0);
403
+ this.state = {
404
+ identity,
405
+ entityName,
406
+ friendlyName: null,
407
+ attributes: {},
408
+ online: null,
409
+ notifiable: null
410
+ };
411
+ this._initializationPromise = new Promise((resolve) => {
412
+ this._resolveInitializationPromise = resolve;
413
+ });
414
+ if (configuration !== null) {
415
+ this._resolveInitialization(configuration, identity, entityName, false);
416
+ }
417
+ }
418
+ /**
419
+ * User identity.
420
+ */
421
+ get identity() { return this.state.identity; }
422
+ set identity(identity) { this.state.identity = identity; }
423
+ set entityName(name) { this.state.entityName = name; }
424
+ /**
425
+ * Custom attributes of the user.
426
+ */
427
+ get attributes() { return this.state.attributes; }
428
+ /**
429
+ * Friendly name of the user, null if not set.
430
+ */
431
+ get friendlyName() { return this.state.friendlyName; }
432
+ /**
433
+ * Status of the real-time conversation connection of the user.
434
+ */
435
+ get isOnline() { return this.state.online; }
436
+ /**
437
+ * User push notification registration status.
438
+ */
439
+ get isNotifiable() { return this.state.notifiable; }
440
+ /**
441
+ * True if this user is receiving real-time status updates.
442
+ */
443
+ get isSubscribed() { return this.subscribed == 'subscribed'; }
444
+ // Handles service updates
445
+ async _update(key, value) {
446
+ await this._initializationPromise;
447
+ let updateReasons = [];
448
+ log$8.debug('User for', this.state.identity, 'updated:', key, value);
449
+ switch (key) {
450
+ case 'friendlyName':
451
+ if (this.state.friendlyName !== value.value) {
452
+ updateReasons.push('friendlyName');
453
+ this.state.friendlyName = value.value;
454
+ }
455
+ break;
456
+ case 'attributes':
457
+ const updateAttributes = parseAttributes(value.value, `Retrieved malformed attributes from the server for user: ${this.state.identity}`, log$8);
458
+ if (!isDeepEqual(this.state.attributes, updateAttributes)) {
459
+ this.state.attributes = updateAttributes;
460
+ updateReasons.push('attributes');
461
+ }
462
+ break;
463
+ case 'reachability':
464
+ if (this.state.online !== value.online) {
465
+ this.state.online = value.online;
466
+ updateReasons.push('reachabilityOnline');
467
+ }
468
+ if (this.state.notifiable !== value.notifiable) {
469
+ this.state.notifiable = value.notifiable;
470
+ updateReasons.push('reachabilityNotifiable');
471
+ }
472
+ break;
473
+ default:
474
+ return;
475
+ }
476
+ if (updateReasons.length > 0) {
477
+ this.emit('updated', { user: this, updateReasons: updateReasons });
478
+ }
479
+ }
480
+ // Fetch reachability info
481
+ async _updateReachabilityInfo(map, update) {
482
+ await this._initializationPromise;
483
+ if (!this.configuration.reachabilityEnabled) {
484
+ return Promise.resolve();
485
+ }
486
+ return map.get('reachability')
487
+ .then(update)
488
+ .catch(err => { log$8.warn('Failed to get reachability info for ', this.state.identity, err); });
489
+ }
490
+ // Fetch user
491
+ async _fetch() {
492
+ await this._initializationPromise;
493
+ if (!this.state.entityName) {
494
+ return this;
495
+ }
496
+ this.promiseToFetch = this.services.syncClient.map({
497
+ id: this.state.entityName,
498
+ mode: 'open_existing',
499
+ includeItems: true
500
+ })
501
+ .then(map => {
502
+ this.entity = map;
503
+ map.on('itemUpdated', args => {
504
+ log$8.debug(this.state.entityName + ' (' + this.state.identity + ') itemUpdated: ' + args.item.key);
505
+ return this._update(args.item.key, args.item.data);
506
+ });
507
+ return Promise.all([
508
+ map.get('friendlyName')
509
+ .then(item => this._update(item.key, item.data)),
510
+ map.get('attributes')
511
+ .then(item => this._update(item.key, item.data)),
512
+ this._updateReachabilityInfo(map, item => this._update(item.key, item.data))
513
+ ]);
514
+ })
515
+ .then(() => {
516
+ log$8.debug('Fetched for', this.identity);
517
+ this.subscribed = 'subscribed';
518
+ this.emit('userSubscribed', this);
519
+ return this;
520
+ })
521
+ .catch(err => {
522
+ this.promiseToFetch = null;
523
+ throw err;
524
+ });
525
+ return this.promiseToFetch;
526
+ }
527
+ async _ensureFetched() {
528
+ await this._initializationPromise;
529
+ return this.promiseToFetch || this._fetch();
530
+ }
531
+ /**
532
+ * Edit user attributes.
533
+ * @param attributes New attributes.
534
+ */
535
+ async updateAttributes(attributes) {
536
+ await this._initializationPromise;
537
+ if (this.subscribed == 'unsubscribed') {
538
+ throw new Error('Can\'t modify unsubscribed object');
539
+ }
540
+ await this.services.commandExecutor.mutateResource('post', this.links.self, {
541
+ attributes: JSON.stringify(attributes)
542
+ });
543
+ return this;
544
+ }
545
+ /**
546
+ * Update the friendly name of the user.
547
+ * @param friendlyName New friendly name.
548
+ */
549
+ async updateFriendlyName(friendlyName) {
550
+ await this._initializationPromise;
551
+ if (this.subscribed == 'unsubscribed') {
552
+ throw new Error('Can\'t modify unsubscribed object');
553
+ }
554
+ await this.services.commandExecutor.mutateResource('post', this.links.self, {
555
+ friendly_name: friendlyName
556
+ });
557
+ return this;
558
+ }
559
+ /**
560
+ * Remove the user from the subscription list.
561
+ * @return A promise of completion.
562
+ */
563
+ async unsubscribe() {
564
+ await this._initializationPromise;
565
+ if (this.promiseToFetch) {
566
+ await this.promiseToFetch;
567
+ this.entity.close();
568
+ this.promiseToFetch = null;
569
+ this.subscribed = 'unsubscribed';
570
+ this.emit('userUnsubscribed', this);
571
+ }
572
+ }
573
+ _resolveInitialization(configuration, identity, entityName, emitUpdated) {
574
+ this.configuration = configuration;
575
+ this.identity = identity;
576
+ this.entityName = entityName;
577
+ this.links = {
578
+ self: `${this.configuration.links.users}/${this.identity}`
579
+ };
580
+ this._resolveInitializationPromise();
581
+ if (emitUpdated) {
582
+ this.emit('updated', {
583
+ user: this,
584
+ updateReasons: [
585
+ 'friendlyName',
586
+ 'attributes',
587
+ 'reachabilityOnline',
588
+ 'reachabilityNotifiable'
589
+ ]
590
+ });
591
+ }
592
+ }
593
+ }
594
+ __decorate([
595
+ declarativeTypeValidator.validateTypesAsync(['string', 'number', 'boolean', 'object', declarativeTypeValidator.literal(null)]),
596
+ __metadata("design:type", Function),
597
+ __metadata("design:paramtypes", [Object]),
598
+ __metadata("design:returntype", Promise)
599
+ ], User.prototype, "updateAttributes", null);
600
+ __decorate([
601
+ declarativeTypeValidator.validateTypesAsync(['string']),
602
+ __metadata("design:type", Function),
603
+ __metadata("design:paramtypes", [String]),
604
+ __metadata("design:returntype", Promise)
605
+ ], User.prototype, "updateFriendlyName", null);
606
+
607
+ class Network {
608
+ constructor(configuration, services) {
609
+ this.configuration = configuration;
610
+ this.services = services;
611
+ this.cache = new Map();
612
+ this.cacheLifetime = this.configuration.httpCacheInterval * 100;
613
+ this.cleanupCache();
614
+ }
615
+ isExpired(timestamp) {
616
+ return !this.cacheLifetime || (Date.now() - timestamp) > this.cacheLifetime;
617
+ }
618
+ cleanupCache() {
619
+ for (let [k, v] of this.cache) {
620
+ if (this.isExpired(v.timestamp)) {
621
+ this.cache.delete(k);
622
+ }
623
+ }
624
+ if (this.cache.size === 0) {
625
+ clearInterval(this.timer);
626
+ }
627
+ }
628
+ pokeTimer() {
629
+ this.timer = this.timer || setInterval(() => this.cleanupCache(), this.cacheLifetime * 2);
630
+ }
631
+ executeWithRetry(request, retryWhenThrottled = false) {
632
+ return new Promise((resolve, reject) => {
633
+ let codesToRetryOn = [502, 503, 504];
634
+ if (retryWhenThrottled) {
635
+ codesToRetryOn.push(429);
636
+ }
637
+ let retrier = new operationRetrier.Retrier(this.configuration.backoffConfiguration);
638
+ retrier.on('attempt', () => {
639
+ request()
640
+ .then(result => retrier.succeeded(result))
641
+ .catch(err => {
642
+ if (codesToRetryOn.indexOf(err.status) > -1) {
643
+ retrier.failed(err);
644
+ }
645
+ else if (err.message === 'Twilsock disconnected') {
646
+ // Ugly hack. We must make a proper exceptions for twilsock
647
+ retrier.failed(err);
648
+ }
649
+ else {
650
+ // Fatal error
651
+ retrier.removeAllListeners();
652
+ retrier.cancel();
653
+ reject(err);
654
+ }
655
+ });
656
+ });
657
+ retrier.on('succeeded', result => { resolve(result); });
658
+ retrier.on('cancelled', err => reject(err));
659
+ retrier.on('failed', err => reject(err));
660
+ retrier.start();
661
+ });
662
+ }
663
+ async get(url) {
664
+ let cacheEntry = this.cache.get(url);
665
+ if (cacheEntry && !this.isExpired(cacheEntry.timestamp)) {
666
+ return cacheEntry.response;
667
+ }
668
+ const headers = {};
669
+ let response = await this.executeWithRetry(() => this.services.transport.get(url, headers, this.configuration.productId), this.configuration.retryWhenThrottled);
670
+ this.cache.set(url, { response, timestamp: Date.now() });
671
+ this.pokeTimer();
672
+ return response;
673
+ }
674
+ }
675
+
676
+ class NotificationTypes {
677
+ }
678
+ NotificationTypes.TYPING_INDICATOR = 'twilio.ipmsg.typing_indicator';
679
+ NotificationTypes.NEW_MESSAGE = 'twilio.conversations.new_message';
680
+ NotificationTypes.ADDED_TO_CONVERSATION = 'twilio.conversations.added_to_conversation';
681
+ // static readonly INVITED_TO_CHANNEL = 'twilio.channel.invited_to_channel';
682
+ NotificationTypes.REMOVED_FROM_CONVERSATION = 'twilio.conversations.removed_from_conversation';
683
+ NotificationTypes.CONSUMPTION_UPDATE = 'twilio.channel.consumption_update';
684
+
685
+ const log$7 = Logger.scope('Participant');
686
+ /**
687
+ * A participant represents a remote client in a conversation.
688
+ */
689
+ class Participant extends replayEventEmitter.ReplayEventEmitter {
690
+ /**
691
+ * @internal
692
+ */
693
+ constructor(data, sid, conversation, links, services) {
694
+ super();
695
+ this.conversation = conversation;
696
+ this.links = links;
697
+ this.services = services;
698
+ this.state = {
699
+ attributes: parseAttributes(data.attributes, 'Retrieved malformed attributes from the server for participant: ' + sid, log$7),
700
+ dateCreated: data.dateCreated ? parseTime$1(data.dateCreated) : null,
701
+ dateUpdated: data.dateCreated ? parseTime$1(data.dateUpdated) : null,
702
+ sid: sid,
703
+ typingTimeout: null,
704
+ isTyping: false,
705
+ identity: data.identity || null,
706
+ roleSid: data.roleSid || null,
707
+ lastReadMessageIndex: Number.isInteger(data.lastConsumedMessageIndex) ? data.lastConsumedMessageIndex : null,
708
+ lastReadTimestamp: data.lastConsumptionTimestamp ? parseTime$1(data.lastConsumptionTimestamp) : null,
709
+ type: data.type || 'chat',
710
+ userInfo: data.userInfo
711
+ };
712
+ if (!data.identity && !data.type) {
713
+ throw new Error('Received invalid Participant object from server: Missing identity or type of Participant.');
714
+ }
715
+ }
716
+ /**
717
+ * The server-assigned unique identifier for the participant.
718
+ */
719
+ get sid() { return this.state.sid; }
720
+ /**
721
+ * Custom attributes of the participant.
722
+ */
723
+ get attributes() { return this.state.attributes; }
724
+ /**
725
+ * Date this participant was created on.
726
+ */
727
+ get dateCreated() { return this.state.dateCreated; }
728
+ /**
729
+ * Date this participant was last updated on.
730
+ */
731
+ get dateUpdated() { return this.state.dateUpdated; }
732
+ /**
733
+ * Identity of the participant.
734
+ */
735
+ get identity() { return this.state.identity; }
736
+ /**
737
+ * Indicates whether the participant is currently typing.
738
+ */
739
+ get isTyping() { return this.state.isTyping; }
740
+ /**
741
+ * The index of the last read message by the participant.
742
+ * Note that retrieving messages on a client endpoint does not mean that messages are read,
743
+ * please consider reading about the [Read Horizon feature](https://www.twilio.com/docs/api/chat/guides/consumption-horizon)
744
+ * to find out about the proper way to mark messages as read.
745
+ */
746
+ get lastReadMessageIndex() { return this.state.lastReadMessageIndex; }
747
+ /**
748
+ * Date of the most recent read horizon update.
749
+ */
750
+ get lastReadTimestamp() { return this.state.lastReadTimestamp; }
751
+ get roleSid() { return this.state.roleSid; }
752
+ /**
753
+ * Message type of the participant.
754
+ */
755
+ get type() { return this.state.type; }
756
+ /**
757
+ * Internal method used to start or reset the typing indicator timeout (with event emitting).
758
+ * @internal
759
+ */
760
+ _startTyping(timeout) {
761
+ clearTimeout(this.state.typingTimeout);
762
+ this.state.isTyping = true;
763
+ this.emit('typingStarted', this);
764
+ this.conversation.emit('typingStarted', this);
765
+ this.state.typingTimeout = setTimeout(() => this._endTyping(), timeout);
766
+ return this;
767
+ }
768
+ /**
769
+ * Internal method function used to stop the typing indicator timeout (with event emitting).
770
+ * @internal
771
+ */
772
+ _endTyping() {
773
+ if (!this.state.typingTimeout) {
774
+ return;
775
+ }
776
+ this.state.isTyping = false;
777
+ this.emit('typingEnded', this);
778
+ this.conversation.emit('typingEnded', this);
779
+ clearInterval(this.state.typingTimeout);
780
+ this.state.typingTimeout = null;
781
+ }
782
+ /**
783
+ * Internal method function used update local object's property roleSid with a new value.
784
+ * @internal
785
+ */
786
+ _update(data) {
787
+ let updateReasons = [];
788
+ let updateAttributes = parseAttributes(data.attributes, 'Retrieved malformed attributes from the server for participant: ' + this.state.sid, log$7);
789
+ if (data.attributes && !isDeepEqual(this.state.attributes, updateAttributes)) {
790
+ this.state.attributes = updateAttributes;
791
+ updateReasons.push('attributes');
792
+ }
793
+ let updatedDateUpdated = parseTime$1(data.dateUpdated);
794
+ if (data.dateUpdated &&
795
+ updatedDateUpdated.getTime() !== (this.state.dateUpdated && this.state.dateUpdated.getTime())) {
796
+ this.state.dateUpdated = updatedDateUpdated;
797
+ updateReasons.push('dateUpdated');
798
+ }
799
+ let updatedDateCreated = parseTime$1(data.dateCreated);
800
+ if (data.dateCreated &&
801
+ updatedDateCreated.getTime() !== (this.state.dateCreated && this.state.dateCreated.getTime())) {
802
+ this.state.dateCreated = updatedDateCreated;
803
+ updateReasons.push('dateCreated');
804
+ }
805
+ if (data.roleSid && this.state.roleSid !== data.roleSid) {
806
+ this.state.roleSid = data.roleSid;
807
+ updateReasons.push('roleSid');
808
+ }
809
+ if ((Number.isInteger(data.lastConsumedMessageIndex) || data.lastConsumedMessageIndex === null)
810
+ && this.state.lastReadMessageIndex !== data.lastConsumedMessageIndex) {
811
+ this.state.lastReadMessageIndex = data.lastConsumedMessageIndex;
812
+ updateReasons.push('lastReadMessageIndex');
813
+ }
814
+ if (data.lastConsumptionTimestamp) {
815
+ let lastReadTimestamp = new Date(data.lastConsumptionTimestamp);
816
+ if (!this.state.lastReadTimestamp ||
817
+ this.state.lastReadTimestamp.getTime() !== lastReadTimestamp.getTime()) {
818
+ this.state.lastReadTimestamp = lastReadTimestamp;
819
+ updateReasons.push('lastReadTimestamp');
820
+ }
821
+ }
822
+ if (updateReasons.length > 0) {
823
+ this.emit('updated', { participant: this, updateReasons: updateReasons });
824
+ }
825
+ return this;
826
+ }
827
+ /**
828
+ * Get the user for this participant and subscribes to it. Supported only for participants of type `chat`.
829
+ */
830
+ async getUser() {
831
+ if (this.type != 'chat') {
832
+ throw new Error('Getting User is not supported for this Participant type: ' + this.type);
833
+ }
834
+ return this.services.users.getUser(this.state.identity, this.state.userInfo);
835
+ }
836
+ /**
837
+ * Remove the participant from the conversation.
838
+ */
839
+ async remove() {
840
+ return this.conversation.removeParticipant(this);
841
+ }
842
+ /**
843
+ * Update the attributes of the participant.
844
+ * @param attributes New attributes.
845
+ */
846
+ async updateAttributes(attributes) {
847
+ await this.services.commandExecutor.mutateResource('post', this.links.self, {
848
+ attributes: JSON.stringify(attributes)
849
+ });
850
+ return this;
851
+ }
852
+ }
853
+ /**
854
+ * Fired when the participant has started typing.
855
+ *
856
+ * Parameters:
857
+ * 1. {@link Participant} `participant` - the participant in question
858
+ * @event
859
+ */
860
+ Participant.typingStarted = 'typingStarted';
861
+ /**
862
+ * Fired when the participant has stopped typing.
863
+ *
864
+ * Parameters:
865
+ * 1. {@link Participant} `participant` - the participant in question
866
+ * @event
867
+ */
868
+ Participant.typingEnded = 'typingEnded';
869
+ /**
870
+ * Fired when the fields of the participant have been updated.
871
+ *
872
+ * Parameters:
873
+ * 1. object `data` - info object provided with the event. It has the following properties:
874
+ * * {@link Participant} participant - the participant in question
875
+ * * {@link ParticipantUpdateReason}[] updateReasons - array of reasons for the update
876
+ * @event
877
+ */
878
+ Participant.updated = 'updated';
879
+ __decorate([
880
+ declarativeTypeValidator.validateTypesAsync(['string', 'number', 'boolean', 'object', declarativeTypeValidator.literal(null)]),
881
+ __metadata("design:type", Function),
882
+ __metadata("design:paramtypes", [Object]),
883
+ __metadata("design:returntype", Promise)
884
+ ], Participant.prototype, "updateAttributes", null);
885
+
886
+ const log$6 = Logger.scope('Participants');
887
+ /**
888
+ * @classdesc Represents the collection of participants for the conversation
889
+ * @fires Participants#participantJoined
890
+ * @fires Participants#participantLeft
891
+ * @fires Participants#participantUpdated
892
+ */
893
+ class Participants extends replayEventEmitter.ReplayEventEmitter {
894
+ constructor(conversation, participants, links, configuration, services) {
895
+ super();
896
+ this.conversation = conversation;
897
+ this.participants = participants;
898
+ this.links = links;
899
+ this.configuration = configuration;
900
+ this.services = services;
901
+ }
902
+ async unsubscribe() {
903
+ if (this.rosterEntityPromise) {
904
+ let entity = await this.rosterEntityPromise;
905
+ entity.close();
906
+ this.rosterEntityPromise = null;
907
+ }
908
+ }
909
+ subscribe(rosterObjectName) {
910
+ return this.rosterEntityPromise = this.rosterEntityPromise
911
+ || this.services.syncClient.map({ id: rosterObjectName, mode: 'open_existing' })
912
+ .then(rosterMap => {
913
+ rosterMap.on('itemAdded', args => {
914
+ log$6.debug(this.conversation.sid + ' itemAdded: ' + args.item.key);
915
+ this.upsertParticipant(args.item.key, args.item.data)
916
+ .then(participant => {
917
+ this.emit('participantJoined', participant);
918
+ });
919
+ });
920
+ rosterMap.on('itemRemoved', args => {
921
+ log$6.debug(this.conversation.sid + ' itemRemoved: ' + args.key);
922
+ let participantSid = args.key;
923
+ if (!this.participants.has(participantSid)) {
924
+ return;
925
+ }
926
+ let leftParticipant = this.participants.get(participantSid);
927
+ this.participants.delete(participantSid);
928
+ this.emit('participantLeft', leftParticipant);
929
+ });
930
+ rosterMap.on('itemUpdated', args => {
931
+ log$6.debug(this.conversation.sid + ' itemUpdated: ' + args.item.key);
932
+ this.upsertParticipant(args.item.key, args.item.data);
933
+ });
934
+ let participantsPromises = [];
935
+ let that = this;
936
+ const rosterMapHandler = function (paginator) {
937
+ paginator.items.forEach(item => { participantsPromises.push(that.upsertParticipant(item.key, item.data)); });
938
+ return paginator.hasNextPage ? paginator.nextPage().then(rosterMapHandler) : null;
939
+ };
940
+ return rosterMap
941
+ .getItems()
942
+ .then(rosterMapHandler)
943
+ .then(() => Promise.all(participantsPromises))
944
+ .then(() => rosterMap);
945
+ })
946
+ .catch(err => {
947
+ this.rosterEntityPromise = null;
948
+ if (this.services.syncClient.connectionState != 'disconnected') {
949
+ log$6.error('Failed to get roster object for conversation', this.conversation.sid, err);
950
+ }
951
+ log$6.debug('ERROR: Failed to get roster object for conversation', this.conversation.sid, err);
952
+ throw err;
953
+ });
954
+ }
955
+ async upsertParticipant(participantSid, data) {
956
+ let participant = this.participants.get(participantSid);
957
+ if (participant) {
958
+ return participant._update(data);
959
+ }
960
+ const links = {
961
+ self: `${this.links.participants}/${participantSid}`
962
+ };
963
+ participant = new Participant(data, participantSid, this.conversation, links, this.services);
964
+ this.participants.set(participantSid, participant);
965
+ participant.on('updated', (args) => this.emit('participantUpdated', args));
966
+ return participant;
967
+ }
968
+ /**
969
+ * @returns {Promise<Array<Participant>>} returns list of participants {@see Participant}
970
+ */
971
+ getParticipants() {
972
+ return this.rosterEntityPromise.then(() => {
973
+ let participants = [];
974
+ this.participants.forEach(participant => participants.push(participant));
975
+ return participants;
976
+ });
977
+ }
978
+ /**
979
+ * Get participant by SID from conversation
980
+ * @returns {Promise<Participant>}
981
+ */
982
+ async getParticipantBySid(participantSid) {
983
+ return this.rosterEntityPromise.then(() => {
984
+ let participant = this.participants.get(participantSid);
985
+ if (!participant) {
986
+ throw new Error('Participant with SID ' + participantSid + ' was not found');
987
+ }
988
+ return participant;
989
+ });
990
+ }
991
+ /**
992
+ * Get participant by identity from conversation
993
+ * @returns {Promise<Participant>}
994
+ */
995
+ async getParticipantByIdentity(identity) {
996
+ let foundParticipant = null;
997
+ return this.rosterEntityPromise.then(() => {
998
+ this.participants.forEach(participant => {
999
+ if (participant.identity === identity) {
1000
+ foundParticipant = participant;
1001
+ }
1002
+ });
1003
+ if (!foundParticipant) {
1004
+ throw new Error('Participant with identity ' + identity + ' was not found');
1005
+ }
1006
+ return foundParticipant;
1007
+ });
1008
+ }
1009
+ /**
1010
+ * Add a chat participant to the conversation
1011
+ * @returns {Promise<any>}
1012
+ */
1013
+ async add(identity, attributes) {
1014
+ return await this.services.commandExecutor.mutateResource('post', this.links.participants, {
1015
+ identity,
1016
+ attributes: typeof attributes !== 'undefined' ? JSON.stringify(attributes) : undefined
1017
+ });
1018
+ }
1019
+ /**
1020
+ * Add a non-chat participant to the conversation.
1021
+ *
1022
+ * @param proxyAddress
1023
+ * @param address
1024
+ * @param attributes
1025
+ * @returns {Promise<any>}
1026
+ */
1027
+ addNonChatParticipant(proxyAddress, address, attributes) {
1028
+ return this.services.commandExecutor.mutateResource('post', this.links.participants, {
1029
+ attributes: typeof attributes !== 'undefined' ? JSON.stringify(attributes) : undefined,
1030
+ messaging_binding: {
1031
+ address,
1032
+ proxy_address: proxyAddress
1033
+ }
1034
+ });
1035
+ }
1036
+ /**
1037
+ * Remove the participant with a given identity from a conversation.
1038
+ */
1039
+ remove(identity) {
1040
+ return this.services.commandExecutor.mutateResource('delete', `${this.links.participants}/${identity}`);
1041
+ }
1042
+ }
1043
+ /**
1044
+ * Fired when participant joined conversation
1045
+ * @event Participants#participantJoined
1046
+ * @type {Participant}
1047
+ */
1048
+ /**
1049
+ * Fired when participant left conversation
1050
+ * @event Participants#participantLeft
1051
+ * @type {Participant}
1052
+ */
1053
+ /**
1054
+ * Fired when participant updated
1055
+ * @event Participants#participantUpdated
1056
+ * @type {Object}
1057
+ * @property {Participant} participant - Updated Participant
1058
+ * @property {Participant#UpdateReason[]} updateReasons - Array of Participant's updated event reasons
1059
+ */
1060
+
1061
+ /**
1062
+ * Represents a media information for a message in a conversation.
1063
+ */
1064
+ class Media {
1065
+ /**
1066
+ * @internal
1067
+ */
1068
+ constructor(data, services) {
1069
+ this.mcsMedia = null;
1070
+ this.services = services;
1071
+ if (data instanceof mcsClient.McsMedia) {
1072
+ this.mcsMedia = data;
1073
+ }
1074
+ this.state = {
1075
+ sid: data.sid,
1076
+ category: data.category,
1077
+ filename: data.filename,
1078
+ contentType: data.contentType,
1079
+ size: data.size
1080
+ };
1081
+ }
1082
+ /**
1083
+ * Server-assigned unique identifier for the media.
1084
+ */
1085
+ get sid() { return this.state.sid; }
1086
+ /**
1087
+ * File name. Null if absent.
1088
+ */
1089
+ get filename() { return this.state.filename; }
1090
+ /**
1091
+ * Content type of the media.
1092
+ */
1093
+ get contentType() { return this.state.contentType; }
1094
+ /**
1095
+ * Size of the media in bytes.
1096
+ */
1097
+ get size() { return this.state.size; }
1098
+ /**
1099
+ * Media category, can be one of the {@link MediaCategory} values.
1100
+ */
1101
+ get category() { return this.state.category; }
1102
+ /**
1103
+ * Returns the direct content URL for the media.
1104
+ *
1105
+ * This URL is impermanent, it will expire in several minutes and cannot be cached.
1106
+ * If the URL becomes expired, you need to request a new one.
1107
+ * Each call to this function produces a new temporary URL.
1108
+ */
1109
+ async getContentTemporaryUrl() {
1110
+ await this._fetchMcsMedia();
1111
+ return this.mcsMedia.getContentUrl();
1112
+ }
1113
+ /**
1114
+ * Returns cached direct content URL for the media.
1115
+ *
1116
+ * This URL will expire in several minutes. This function does not refresh the URL and can be used to query it several times
1117
+ * without causing network traffic.
1118
+ * If the URL becomes expired, you need to request a new one using getContentTemporaryUrl().
1119
+ *
1120
+ * @returns {Promise<String>}
1121
+ */
1122
+ async getCachedTemporaryUrl() {
1123
+ await this._fetchMcsMedia();
1124
+ return this.mcsMedia.getCachedContentUrl();
1125
+ }
1126
+ async _fetchMcsMedia() {
1127
+ if (!this.mcsMedia) {
1128
+ if (this.services.mcsClient) {
1129
+ this.mcsMedia = await this.services.mcsClient.get(this.state.sid);
1130
+ }
1131
+ else {
1132
+ throw new Error('Media Content Service is unavailable');
1133
+ }
1134
+ }
1135
+ }
1136
+ }
1137
+
1138
+ /**
1139
+ * Contains aggregated information about delivery statuses of a message across all participants
1140
+ * of a conversation.
1141
+ *
1142
+ * At any moment during the message delivery to a participant, the message can have zero or more of following
1143
+ * delivery statuses:
1144
+ * * Message is considered as **sent** to a participant if the nearest upstream carrier accepted the message.
1145
+ * * Message is considered as **delivered** to a participant if Twilio has received confirmation of message
1146
+ * delivery from the upstream carrier, and, where available, the destination handset.
1147
+ * * Message considered as **undelivered** to a participant if Twilio has received a delivery receipt
1148
+ * indicating that the message was not delivered. This can happen for many reasons including carrier content
1149
+ * filtering and the availability of the destination handset.
1150
+ * * Message considered as **read** by a participant if the message has been delivered and opened by the
1151
+ * recipient in a conversation. The recipient must have enabled the read receipts.
1152
+ * * Message considered as **failed** to be delivered to a participant if the message could not be sent.
1153
+ * This can happen for various reasons including queue overflows, account suspensions and media
1154
+ * errors (in the case of MMS for instance).
1155
+ *
1156
+ * {@link AggregatedDeliveryReceipt} class contains an aggregated value {@link DeliveryAmount} for each delivery status.
1157
+ */
1158
+ class AggregatedDeliveryReceipt {
1159
+ /**
1160
+ * @internal
1161
+ */
1162
+ constructor(data) {
1163
+ this.state = data;
1164
+ }
1165
+ /**
1166
+ * Maximum number of delivery events expected for the message.
1167
+ */
1168
+ get total() {
1169
+ return this.state.total;
1170
+ }
1171
+ /**
1172
+ * Message is considered as **sent** to a participant if the nearest upstream carrier accepted the message.
1173
+ *
1174
+ * @return Amount of participants that have the **sent** delivery status for the message.
1175
+ */
1176
+ get sent() {
1177
+ return this.state.sent;
1178
+ }
1179
+ /**
1180
+ * Message is considered as **delivered** to a participant if Twilio has received confirmation of message
1181
+ * delivery from the upstream carrier, and, where available, the destination handset.
1182
+ *
1183
+ * @return Amount of participants that have the **delivered** delivery status for the message.
1184
+ */
1185
+ get delivered() {
1186
+ return this.state.delivered;
1187
+ }
1188
+ /**
1189
+ * Message is considered as **read** by a participant, if the message has been delivered and opened by the
1190
+ * recipient in a conversation. The recipient must have enabled the read receipts.
1191
+ *
1192
+ * @return Amount of participants that have the **read** delivery status for the message.
1193
+ */
1194
+ get read() {
1195
+ return this.state.read;
1196
+ }
1197
+ /**
1198
+ * Message is considered as **undelivered** to a participant if Twilio has received a delivery receipt
1199
+ * indicating that the message was not delivered. This can happen for many reasons including carrier content
1200
+ * filtering and the availability of the destination handset.
1201
+ *
1202
+ * @return Ammount of participants that have the **undelivered** delivery status for the message.
1203
+ */
1204
+ get undelivered() {
1205
+ return this.state.undelivered;
1206
+ }
1207
+ /**
1208
+ * Message is considered as **failed** to be delivered to a participant if the message could not be sent.
1209
+ * This can happen for various reasons including queue overflows, account suspensions and media
1210
+ * errors (in the case of MMS for instance). Twilio does not charge you for failed messages.
1211
+ *
1212
+ * @return Amount of participants that have the **failed** delivery status for the message.
1213
+ */
1214
+ get failed() {
1215
+ return this.state.failed;
1216
+ }
1217
+ _update(data) {
1218
+ this.state = data;
1219
+ }
1220
+ _isEquals(data) {
1221
+ const isTotalSame = this.total === data.total;
1222
+ const isSentSame = this.sent === data.sent;
1223
+ const isDeliveredSame = this.delivered === data.delivered;
1224
+ const isReadSame = this.read === data.read;
1225
+ const isUndeliveredSame = this.undelivered === data.undelivered;
1226
+ const isFailedSame = this.failed === data.failed;
1227
+ return isTotalSame && isSentSame && isDeliveredSame && isReadSame && isUndeliveredSame && isFailedSame;
1228
+ }
1229
+ }
1230
+
1231
+ /**
1232
+ * Pagination helper class.
1233
+ */
1234
+ class RestPaginator {
1235
+ /**
1236
+ * @internal
1237
+ */
1238
+ constructor(items, source, prevToken, nextToken) {
1239
+ this.state = {
1240
+ prevToken,
1241
+ nextToken,
1242
+ source,
1243
+ items
1244
+ };
1245
+ }
1246
+ /**
1247
+ * Indicates the existence of the next page.
1248
+ */
1249
+ get hasNextPage() { return !!this.state.nextToken; }
1250
+ /**
1251
+ * Indicates the existence of the previous page
1252
+ */
1253
+ get hasPrevPage() { return !!this.state.prevToken; }
1254
+ /**
1255
+ * Array of elements on the current page.
1256
+ */
1257
+ get items() { return this.state.items; }
1258
+ /**
1259
+ * Request the next page. Does not modify the existing object.
1260
+ */
1261
+ nextPage() {
1262
+ return this.hasNextPage ? this.state.source(this.state.nextToken) : Promise.reject(new Error('No next page'));
1263
+ }
1264
+ /**
1265
+ * Request the previous page. Does not modify the existing object.
1266
+ */
1267
+ prevPage() {
1268
+ return this.hasPrevPage ? this.state.source(this.state.prevToken) : Promise.reject(new Error('No previous page'));
1269
+ }
1270
+ }
1271
+
1272
+ /**
1273
+ * Represents a delivery receipt of a message.
1274
+ */
1275
+ class DetailedDeliveryReceipt {
1276
+ /**
1277
+ * @internal
1278
+ */
1279
+ constructor(descriptor) {
1280
+ this.sid = descriptor.sid;
1281
+ this.messageSid = descriptor.message_sid;
1282
+ this.conversationSid = descriptor.conversation_sid;
1283
+ this.channelMessageSid = descriptor.channel_message_sid;
1284
+ this.participantSid = descriptor.participant_sid;
1285
+ this.status = descriptor.status || 'queued';
1286
+ this.errorCode = descriptor.error_code || 0;
1287
+ this.dateCreated = descriptor.date_created;
1288
+ this.dateUpdated = descriptor.date_updated;
1289
+ }
1290
+ }
1291
+
1292
+ const log$5 = Logger.scope('Message');
1293
+ /**
1294
+ * A message in a conversation.
1295
+ */
1296
+ class Message extends replayEventEmitter.ReplayEventEmitter {
1297
+ /**
1298
+ * @internal
1299
+ */
1300
+ constructor(index, data, conversation, links, configuration, services) {
1301
+ var _a, _b, _c, _d, _e;
1302
+ super();
1303
+ this.conversation = conversation;
1304
+ this.links = links;
1305
+ this.configuration = configuration;
1306
+ this.services = services;
1307
+ this.state = {
1308
+ sid: data.sid,
1309
+ index: index,
1310
+ author: (_a = data.author) !== null && _a !== void 0 ? _a : null,
1311
+ subject: (_b = data.subject) !== null && _b !== void 0 ? _b : null,
1312
+ body: data.text,
1313
+ timestamp: data.timestamp ? new Date(data.timestamp) : null,
1314
+ dateUpdated: data.dateUpdated ? new Date(data.dateUpdated) : null,
1315
+ lastUpdatedBy: (_c = data.lastUpdatedBy) !== null && _c !== void 0 ? _c : null,
1316
+ attributes: parseAttributes(data.attributes, `Got malformed attributes for the message ${data.sid}`, log$5),
1317
+ type: (_d = data.type) !== null && _d !== void 0 ? _d : 'text',
1318
+ media: (data.type && data.type === 'media' && data.media)
1319
+ ? new Media(data.media, this.services) : null,
1320
+ medias: (data.type && data.type === 'media' && data.medias)
1321
+ ? data.medias.map((m) => new Media(m, this.services)) : null,
1322
+ participantSid: (_e = data.memberSid) !== null && _e !== void 0 ? _e : null,
1323
+ aggregatedDeliveryReceipt: data.delivery ? new AggregatedDeliveryReceipt(data.delivery) : null
1324
+ };
1325
+ }
1326
+ /**
1327
+ * The server-assigned unique identifier for the message.
1328
+ */
1329
+ get sid() { return this.state.sid; }
1330
+ /**
1331
+ * Name of the user that sent the message.
1332
+ */
1333
+ get author() { return this.state.author; }
1334
+ /**
1335
+ * Message subject. Used only in email conversations.
1336
+ */
1337
+ get subject() { return this.state.subject; }
1338
+ /**
1339
+ * Body of the message.
1340
+ */
1341
+ get body() { return this.state.body; }
1342
+ /**
1343
+ * Date this message was last updated on.
1344
+ */
1345
+ get dateUpdated() { return this.state.dateUpdated; }
1346
+ /**
1347
+ * Index of the message in the conversation's messages list.
1348
+ * By design of the Conversations system, the message indices may have arbitrary gaps between them,
1349
+ * that does not necessarily mean they were deleted or otherwise modified - just that
1350
+ * messages may have some non-contiguous indices even if they are being sent immediately one after another.
1351
+ *
1352
+ * Trying to use indices for some calculations is going to be unreliable.
1353
+ *
1354
+ * To calculate the number of unread messages it is better to use the read horizon API.
1355
+ * See {@link Conversation.getUnreadMessagesCount} for details.
1356
+ */
1357
+ get index() { return this.state.index; }
1358
+ /**
1359
+ * Identity of the last user that updated the message.
1360
+ */
1361
+ get lastUpdatedBy() { return this.state.lastUpdatedBy; }
1362
+ /**
1363
+ * Date this message was created on.
1364
+ */
1365
+ get dateCreated() { return this.state.timestamp; }
1366
+ /**
1367
+ * Custom attributes of the message.
1368
+ */
1369
+ get attributes() { return this.state.attributes; }
1370
+ /**
1371
+ * Push notification type of the message.
1372
+ */
1373
+ get type() { return this.state.type; }
1374
+ /**
1375
+ * One of the attached media.
1376
+ * @deprecated Use attachedMedia instead. Note that the latter is now an array.
1377
+ */
1378
+ get media() { return this.state.media; }
1379
+ /**
1380
+ * Return all media attachments, except email body/history attachments, without temporary urls.
1381
+ */
1382
+ get attachedMedia() { return this.getMediaByCategory(['media']); }
1383
+ /**
1384
+ * The server-assigned unique identifier of the authoring participant.
1385
+ */
1386
+ get participantSid() { return this.state.participantSid; }
1387
+ /**
1388
+ * Aggregated information about the message delivery statuses across all participants of a conversation..
1389
+ */
1390
+ get aggregatedDeliveryReceipt() {
1391
+ return this.state.aggregatedDeliveryReceipt;
1392
+ }
1393
+ /**
1394
+ * Return a (possibly empty) array of media matching a specific set of categories.
1395
+ * Allowed category is so far only 'media'.
1396
+ * @param categories Array of categories to match.
1397
+ * @returns Array of media descriptors matching given categories.
1398
+ */
1399
+ getMediaByCategory(categories) {
1400
+ var _a;
1401
+ return (_a = this.state.medias) === null || _a === void 0 ? void 0 : _a.filter((m) => categories.includes(m.category));
1402
+ }
1403
+ _update(data) {
1404
+ let updateReasons = [];
1405
+ if ((data.text || ((typeof data.text) === 'string')) && data.text !== this.state.body) {
1406
+ this.state.body = data.text;
1407
+ updateReasons.push('body');
1408
+ }
1409
+ if (data.subject && data.subject !== this.state.subject) {
1410
+ this.state.subject = data.subject;
1411
+ updateReasons.push('subject');
1412
+ }
1413
+ if (data.lastUpdatedBy && data.lastUpdatedBy !== this.state.lastUpdatedBy) {
1414
+ this.state.lastUpdatedBy = data.lastUpdatedBy;
1415
+ updateReasons.push('lastUpdatedBy');
1416
+ }
1417
+ if (data.author && data.author !== this.state.author) {
1418
+ this.state.author = data.author;
1419
+ updateReasons.push('author');
1420
+ }
1421
+ if (data.dateUpdated &&
1422
+ new Date(data.dateUpdated).getTime() !== (this.state.dateUpdated && this.state.dateUpdated.getTime())) {
1423
+ this.state.dateUpdated = new Date(data.dateUpdated);
1424
+ updateReasons.push('dateUpdated');
1425
+ }
1426
+ if (data.timestamp &&
1427
+ new Date(data.timestamp).getTime() !== (this.state.timestamp && this.state.timestamp.getTime())) {
1428
+ this.state.timestamp = new Date(data.timestamp);
1429
+ updateReasons.push('dateCreated');
1430
+ }
1431
+ let updatedAttributes = parseAttributes(data.attributes, `Got malformed attributes for the message ${this.sid}`, log$5);
1432
+ if (!isDeepEqual(this.state.attributes, updatedAttributes)) {
1433
+ this.state.attributes = updatedAttributes;
1434
+ updateReasons.push('attributes');
1435
+ }
1436
+ let updatedAggregatedDelivery = data.delivery;
1437
+ let currentAggregatedDelivery = this.state.aggregatedDeliveryReceipt;
1438
+ let isUpdatedAggregateDeliveryValid = !!updatedAggregatedDelivery && !!updatedAggregatedDelivery.total &&
1439
+ !!updatedAggregatedDelivery.delivered && !!updatedAggregatedDelivery.failed && !!updatedAggregatedDelivery.read &&
1440
+ !!updatedAggregatedDelivery.sent && !!updatedAggregatedDelivery.undelivered;
1441
+ if (isUpdatedAggregateDeliveryValid) {
1442
+ if (!currentAggregatedDelivery) {
1443
+ this.state.aggregatedDeliveryReceipt = new AggregatedDeliveryReceipt(updatedAggregatedDelivery);
1444
+ updateReasons.push('deliveryReceipt');
1445
+ }
1446
+ else if (!currentAggregatedDelivery._isEquals(updatedAggregatedDelivery)) {
1447
+ currentAggregatedDelivery._update(updatedAggregatedDelivery);
1448
+ updateReasons.push('deliveryReceipt');
1449
+ }
1450
+ }
1451
+ if (updateReasons.length > 0) {
1452
+ this.emit('updated', { message: this, updateReasons: updateReasons });
1453
+ }
1454
+ }
1455
+ /**
1456
+ * Get the participant who is the author of the message.
1457
+ */
1458
+ async getParticipant() {
1459
+ let participant = null;
1460
+ if (this.state.participantSid) {
1461
+ participant = await this.conversation.getParticipantBySid(this.participantSid)
1462
+ .catch(() => {
1463
+ log$5.debug(`Participant with sid "${this.participantSid}" not found for message ${this.sid}`);
1464
+ return null;
1465
+ });
1466
+ }
1467
+ if (!participant && this.state.author) {
1468
+ participant = await this.conversation.getParticipantByIdentity(this.state.author)
1469
+ .catch(() => {
1470
+ log$5.debug(`Participant with identity "${this.author}" not found for message ${this.sid}`);
1471
+ return null;
1472
+ });
1473
+ }
1474
+ if (participant) {
1475
+ return participant;
1476
+ }
1477
+ let errorMesage = 'Participant with ';
1478
+ if (this.state.participantSid) {
1479
+ errorMesage += 'SID \'' + this.state.participantSid + '\' ';
1480
+ }
1481
+ if (this.state.author) {
1482
+ if (this.state.participantSid) {
1483
+ errorMesage += 'or ';
1484
+ }
1485
+ errorMesage += 'identity \'' + this.state.author + '\' ';
1486
+ }
1487
+ if (errorMesage === 'Participant with ') {
1488
+ errorMesage = 'Participant ';
1489
+ }
1490
+ errorMesage += 'was not found';
1491
+ throw new Error(errorMesage);
1492
+ }
1493
+ /**
1494
+ * Get the delivery receipts of the message.
1495
+ */
1496
+ async getDetailedDeliveryReceipts() {
1497
+ let paginator = await this._getDetailedDeliveryReceiptsPaginator();
1498
+ let detailedDeliveryReceipts = [];
1499
+ while (true) {
1500
+ detailedDeliveryReceipts = [...detailedDeliveryReceipts, ...paginator.items];
1501
+ if (!paginator.hasNextPage) {
1502
+ break;
1503
+ }
1504
+ paginator = await paginator.nextPage();
1505
+ }
1506
+ return detailedDeliveryReceipts;
1507
+ }
1508
+ /**
1509
+ * Remove the message.
1510
+ */
1511
+ async remove() {
1512
+ await this.services.commandExecutor.mutateResource('delete', this.links.self);
1513
+ return this;
1514
+ }
1515
+ /**
1516
+ * Edit the message body.
1517
+ * @param body New body of the message.
1518
+ */
1519
+ async updateBody(body) {
1520
+ await this.services.commandExecutor.mutateResource('post', this.links.self, {
1521
+ body
1522
+ });
1523
+ return this;
1524
+ }
1525
+ /**
1526
+ * Edit the message attributes.
1527
+ * @param attributes New attributes.
1528
+ */
1529
+ async updateAttributes(attributes) {
1530
+ await this.services.commandExecutor.mutateResource('post', this.links.self, {
1531
+ attributes: typeof attributes !== 'undefined' ? JSON.stringify(attributes) : undefined
1532
+ });
1533
+ return this;
1534
+ }
1535
+ /**
1536
+ * Get content URLs for all media attachments in the given set using single operation.
1537
+ * @param contentSet Set of media attachments to query for content URL.
1538
+ */
1539
+ async attachTemporaryUrlsFor(contentSet) {
1540
+ // We ignore existing mcsMedia members of each of the media entries.
1541
+ // Instead we just collect their sids and pull new descriptors from a mediaSet GET endpoint.
1542
+ const sids = contentSet.map((m) => m.sid);
1543
+ if (this.services.mcsClient) {
1544
+ return (await this.services.mcsClient.mediaSetGet(sids)).map((item) => { return new Media(item, this.services); });
1545
+ }
1546
+ else {
1547
+ throw new Error('Media Content Service is unavailable');
1548
+ }
1549
+ }
1550
+ async _getDetailedDeliveryReceiptsPaginator(options) {
1551
+ const messagesReceiptsUrl = this.configuration.links.messagesReceipts
1552
+ .replace('%s', this.conversation.sid)
1553
+ .replace('%s', this.sid);
1554
+ const url = new UriBuilder(messagesReceiptsUrl)
1555
+ .arg('PageToken', options === null || options === void 0 ? void 0 : options.pageToken)
1556
+ .arg('PageSize', options === null || options === void 0 ? void 0 : options.pageSize)
1557
+ .build();
1558
+ const response = await this.services.network.get(url);
1559
+ return new RestPaginator(response.body.delivery_receipts.map((x) => new DetailedDeliveryReceipt(x)), (pageToken, pageSize) => this._getDetailedDeliveryReceiptsPaginator({ pageToken, pageSize }), response.body.meta.previous_token, response.body.meta.next_token);
1560
+ }
1561
+ }
1562
+ /**
1563
+ * Fired when the properties or the body of the message has been updated.
1564
+ *
1565
+ * Parameters:
1566
+ * 1. object `data` - info object provided with the event. It has the following properties:
1567
+ * * {@link Message} message - the message in question
1568
+ * * {@link MessageUpdateReason}[] updateReasons - array of reasons for the update
1569
+ */
1570
+ Message.updated = 'updated';
1571
+ __decorate([
1572
+ declarativeTypeValidator.validateTypesAsync('string'),
1573
+ __metadata("design:type", Function),
1574
+ __metadata("design:paramtypes", [String]),
1575
+ __metadata("design:returntype", Promise)
1576
+ ], Message.prototype, "updateBody", null);
1577
+ __decorate([
1578
+ declarativeTypeValidator.validateTypesAsync(['string', 'number', 'boolean', 'object', declarativeTypeValidator.literal(null)]),
1579
+ __metadata("design:type", Function),
1580
+ __metadata("design:paramtypes", [Object]),
1581
+ __metadata("design:returntype", Promise)
1582
+ ], Message.prototype, "updateAttributes", null);
1583
+ __decorate([
1584
+ declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.custom(value => [
1585
+ value instanceof Array && value.length > 0 && value.reduce((a, c) => a && c instanceof Media),
1586
+ 'a non-empty array of Media'
1587
+ ])),
1588
+ __metadata("design:type", Function),
1589
+ __metadata("design:paramtypes", [Array]),
1590
+ __metadata("design:returntype", Promise)
1591
+ ], Message.prototype, "attachTemporaryUrlsFor", null);
1592
+
1593
+ const log$4 = Logger.scope('Messages');
1594
+ /**
1595
+ * Represents the collection of messages in a conversation
1596
+ */
1597
+ class Messages extends replayEventEmitter.ReplayEventEmitter {
1598
+ constructor(conversation, configuration, services) {
1599
+ super();
1600
+ this.conversation = conversation;
1601
+ this.configuration = configuration;
1602
+ this.services = services;
1603
+ this.messagesByIndex = new Map();
1604
+ this.messagesListPromise = null;
1605
+ }
1606
+ /**
1607
+ * Subscribe to the Messages Event Stream
1608
+ * @param name - The name of Sync object for the Messages resource.
1609
+ */
1610
+ async subscribe(name) {
1611
+ if (this.messagesListPromise) {
1612
+ return this.messagesListPromise;
1613
+ }
1614
+ this.messagesListPromise = this.services.syncClient.list({
1615
+ id: name,
1616
+ mode: 'open_existing',
1617
+ });
1618
+ try {
1619
+ const list = await this.messagesListPromise;
1620
+ list.on('itemAdded', (args) => {
1621
+ log$4.debug(`${this.conversation.sid} itemAdded: ${args.item.index}`);
1622
+ const links = {
1623
+ self: `${this.conversation.links.messages}/${args.item.data.sid}`,
1624
+ conversation: this.conversation.links.self,
1625
+ messages_receipts: `${this.conversation.links.messages}/${args.item.data.sid}/Receipts`,
1626
+ };
1627
+ const message = new Message(args.item.index, args.item.data, this.conversation, links, this.configuration, this.services);
1628
+ if (this.messagesByIndex.has(message.index)) {
1629
+ log$4.debug('Message arrived, but is already known and ignored', this.conversation.sid, message.index);
1630
+ return;
1631
+ }
1632
+ this.messagesByIndex.set(message.index, message);
1633
+ message.on('updated', (args) => this.emit('messageUpdated', args));
1634
+ this.emit('messageAdded', message);
1635
+ });
1636
+ list.on('itemRemoved', (args) => {
1637
+ log$4.debug(`#{this.conversation.sid} itemRemoved: ${args.index}`);
1638
+ const index = args.index;
1639
+ if (this.messagesByIndex.has(index)) {
1640
+ let message = this.messagesByIndex.get(index);
1641
+ this.messagesByIndex.delete(message.index);
1642
+ message.removeAllListeners('updated');
1643
+ this.emit('messageRemoved', message);
1644
+ }
1645
+ });
1646
+ list.on('itemUpdated', (args) => {
1647
+ log$4.debug(`${this.conversation.sid} itemUpdated: ${args.item.index}`);
1648
+ const message = this.messagesByIndex.get(args.item.index);
1649
+ if (message) {
1650
+ message._update(args.item.data);
1651
+ }
1652
+ });
1653
+ return list;
1654
+ }
1655
+ catch (err) {
1656
+ this.messagesListPromise = null;
1657
+ if (this.services.syncClient.connectionState !== 'disconnected') {
1658
+ log$4.error('Failed to get messages object for conversation', this.conversation.sid, err);
1659
+ }
1660
+ log$4.debug('ERROR: Failed to get messages object for conversation', this.conversation.sid, err);
1661
+ throw err;
1662
+ }
1663
+ }
1664
+ async unsubscribe() {
1665
+ if (!this.messagesListPromise) {
1666
+ return;
1667
+ }
1668
+ const entity = await this.messagesListPromise;
1669
+ entity.close();
1670
+ this.messagesListPromise = null;
1671
+ }
1672
+ /**
1673
+ * Send Message to the conversation, message could include both text and multiple media attachments.
1674
+ * @param message Message to post
1675
+ * @returns Returns promise which can fail
1676
+ */
1677
+ async sendV2(message) {
1678
+ var _a;
1679
+ log$4.debug('Sending message V2', message.mediaContent, message.attributes, message.emailOptions);
1680
+ const media = [];
1681
+ for (const [category, mediaContent] of message.mediaContent) {
1682
+ log$4.debug(`Adding media to a message as ${mediaContent instanceof FormData ? 'FormData' : 'SendMediaOptions'}`, mediaContent);
1683
+ media.push(mediaContent instanceof FormData
1684
+ ? await this.services.mcsClient.postFormData(mediaContent, category)
1685
+ : await this.services.mcsClient.post(mediaContent.contentType, mediaContent.media, category, mediaContent.filename));
1686
+ }
1687
+ return await this.services.commandExecutor.mutateResource('post', this.conversation.links.messages, {
1688
+ body: message.text,
1689
+ subject: (_a = message.emailOptions) === null || _a === void 0 ? void 0 : _a.subject,
1690
+ media_sids: media.map((m) => m.sid),
1691
+ attributes: typeof message.attributes !== 'undefined'
1692
+ ? JSON.stringify(message.attributes)
1693
+ : undefined,
1694
+ });
1695
+ }
1696
+ /**
1697
+ * Send Message to the conversation
1698
+ * @param message Message to post
1699
+ * @param attributes Message attributes
1700
+ * @param emailOptions Options that modify E-mail integration behaviors.
1701
+ * @returns Returns promise which can fail
1702
+ */
1703
+ async send(message, attributes = {}, emailOptions) {
1704
+ log$4.debug('Sending text message', message, attributes, emailOptions);
1705
+ return await this.services.commandExecutor.mutateResource('post', this.conversation.links.messages, {
1706
+ body: message !== null && message !== void 0 ? message : '',
1707
+ attributes: typeof attributes !== 'undefined'
1708
+ ? JSON.stringify(attributes)
1709
+ : undefined,
1710
+ subject: emailOptions === null || emailOptions === void 0 ? void 0 : emailOptions.subject,
1711
+ });
1712
+ }
1713
+ /**
1714
+ * Send Media Message to the conversation
1715
+ * @param mediaContent Media content to post
1716
+ * @param attributes Message attributes
1717
+ * @param emailOptions Email options
1718
+ * @returns Returns promise which can fail
1719
+ */
1720
+ async sendMedia(mediaContent, attributes = {}, emailOptions) {
1721
+ log$4.debug('Sending media message', mediaContent, attributes, emailOptions);
1722
+ log$4.debug(`Sending media message as ${mediaContent instanceof FormData ? 'FormData' : 'SendMediaOptions'}`, mediaContent, attributes);
1723
+ const media = mediaContent instanceof FormData
1724
+ ? await this.services.mcsClient.postFormData(mediaContent)
1725
+ : await this.services.mcsClient.post(mediaContent.contentType, mediaContent.media, 'media', mediaContent.filename);
1726
+ // emailOptions are currently ignored for media messages.
1727
+ return await this.services.commandExecutor.mutateResource('post', this.conversation.links.messages, {
1728
+ media_sids: [media.sid],
1729
+ attributes: typeof attributes !== 'undefined'
1730
+ ? JSON.stringify(attributes)
1731
+ : undefined,
1732
+ });
1733
+ }
1734
+ /**
1735
+ * Returns messages from conversation using paginator interface
1736
+ * @param pageSize Number of messages to return in single chunk. By default it's 30.
1737
+ * @param anchor Most early message id which is already known, or 'end' by default
1738
+ * @param direction Pagination order 'backwards' or 'forward', 'forward' by default
1739
+ * @returns Last page of messages by default
1740
+ */
1741
+ async getMessages(pageSize, anchor, direction = 'backwards') {
1742
+ return this._getMessages(pageSize, anchor, direction);
1743
+ }
1744
+ _wrapPaginator(order, page, op) {
1745
+ // Due to an inconsistency between Sync and Chat conventions, next and
1746
+ // previous pages should be swapped.
1747
+ const shouldReverse = order === 'desc';
1748
+ const nextPage = () => page.nextPage().then((page) => this._wrapPaginator(order, page, op));
1749
+ const previousPage = () => page.prevPage().then((page) => this._wrapPaginator(order, page, op));
1750
+ return op(page.items).then((items) => ({
1751
+ items: items.sort((x, y) => {
1752
+ return x.index - y.index;
1753
+ }),
1754
+ hasPrevPage: shouldReverse ? page.hasNextPage : page.hasPrevPage,
1755
+ hasNextPage: shouldReverse ? page.hasPrevPage : page.hasNextPage,
1756
+ prevPage: shouldReverse ? nextPage : previousPage,
1757
+ nextPage: shouldReverse ? previousPage : nextPage,
1758
+ }));
1759
+ }
1760
+ _upsertMessage(index, value) {
1761
+ const cachedMessage = this.messagesByIndex.get(index);
1762
+ if (cachedMessage) {
1763
+ return cachedMessage;
1764
+ }
1765
+ const links = {
1766
+ self: `${this.conversation.links.messages}/${value.sid}`,
1767
+ conversation: this.conversation.links.self,
1768
+ messages_receipts: `${this.conversation.links.messages}/${value.sid}/Receipts`,
1769
+ };
1770
+ const message = new Message(index, value, this.conversation, links, this.configuration, this.services);
1771
+ this.messagesByIndex.set(message.index, message);
1772
+ message.on('updated', (args) => this.emit('messageUpdated', args));
1773
+ return message;
1774
+ }
1775
+ /**
1776
+ * Returns last messages from conversation
1777
+ * @param {Number} [pageSize] Number of messages to return in single chunk. By default it's 30.
1778
+ * @param {String} [anchor] Most early message id which is already known, or 'end' by default
1779
+ * @param {String} [direction] Pagination order 'backwards' or 'forward', or 'forward' by default
1780
+ * @returns {Promise<SyncPaginator<Message>>} last page of messages by default
1781
+ * @private
1782
+ */
1783
+ async _getMessages(pageSize = 30, anchor = 'end', direction = 'forward') {
1784
+ const order = direction === 'backwards' ? 'desc' : 'asc';
1785
+ const list = await this.messagesListPromise;
1786
+ const page = await list.getItems({
1787
+ from: anchor !== 'end' ? anchor : void 0,
1788
+ pageSize,
1789
+ order,
1790
+ limit: pageSize, // @todo Limit equals pageSize by default in Sync. This is probably not ideal.
1791
+ });
1792
+ return await this._wrapPaginator(order, page, (items) => Promise.all(items.map((item) => this._upsertMessage(item.index, item.data))));
1793
+ }
1794
+ }
1795
+
1796
+ /**
1797
+ * An unsent message. Returned from {@link MessageBuilder.build}.
1798
+ */
1799
+ class UnsentMessage {
1800
+ /**
1801
+ * @internal
1802
+ */
1803
+ constructor(messagesEntity) {
1804
+ this.messagesEntity = messagesEntity;
1805
+ this.attributes = {};
1806
+ this.mediaContent = [];
1807
+ this.emailOptions = {};
1808
+ }
1809
+ /**
1810
+ * Send the prepared message to the conversation.
1811
+ * @returns Index of the new message in the conversation.
1812
+ */
1813
+ async send() {
1814
+ const response = await this.messagesEntity.sendV2(this);
1815
+ return parseToNumber(response.index);
1816
+ }
1817
+ }
1818
+
1819
+ /**
1820
+ * Message builder. Allows the message to be built and sent via method chaining.
1821
+ *
1822
+ * Example:
1823
+ *
1824
+ * ```ts
1825
+ * await testConversation.prepareMessage()
1826
+ * .setBody('Hello!')
1827
+ * .setAttributes({foo: 'bar'})
1828
+ * .addMedia(media1)
1829
+ * .addMedia(media2)
1830
+ * .build()
1831
+ * .send();
1832
+ * ```
1833
+ */
1834
+ class MessageBuilder {
1835
+ /**
1836
+ * @internal
1837
+ */
1838
+ constructor(limits, messagesEntity) {
1839
+ this.limits = limits;
1840
+ this.message = new UnsentMessage(messagesEntity);
1841
+ }
1842
+ /**
1843
+ * Sets the message body.
1844
+ * @param text Contents of the body.
1845
+ */
1846
+ setBody(text) {
1847
+ this.message.text = text;
1848
+ return this;
1849
+ }
1850
+ /**
1851
+ * Sets the message subject.
1852
+ * @param subject Contents of the subject.
1853
+ */
1854
+ setSubject(subject) {
1855
+ this.message.emailOptions.subject = subject;
1856
+ return this;
1857
+ }
1858
+ /**
1859
+ * Sets the message attributes.
1860
+ * @param attributes Message attributes.
1861
+ */
1862
+ setAttributes(attributes) {
1863
+ this.message.attributes = attributes;
1864
+ return this;
1865
+ }
1866
+ /**
1867
+ * Adds media to the message.
1868
+ * @param payload Media to add.
1869
+ */
1870
+ addMedia(payload) {
1871
+ this.message.mediaContent.push(['media', payload]);
1872
+ return this;
1873
+ }
1874
+ /**
1875
+ * Builds the message, making it ready to be sent.
1876
+ */
1877
+ build() {
1878
+ if (this.message.mediaContent.length > this.limits.mediaAttachmentsCountLimit) {
1879
+ throw new Error(`Too many media attachments in the message (${this.message.mediaContent.length} > ${this.limits.mediaAttachmentsCountLimit})`);
1880
+ }
1881
+ // @todo we don't know the sizes of the attachments in FormData
1882
+ return this.message;
1883
+ }
1884
+ getPayloadContentType(payload) {
1885
+ if (typeof FormData !== 'undefined' && (payload instanceof FormData)) {
1886
+ return payload.get('Content-Type');
1887
+ }
1888
+ return payload.contentType;
1889
+ }
1890
+ }
1891
+
1892
+ const log$3 = Logger.scope('Conversation');
1893
+ const fieldMappings = {
1894
+ lastMessage: 'lastMessage',
1895
+ attributes: 'attributes',
1896
+ createdBy: 'createdBy',
1897
+ dateCreated: 'dateCreated',
1898
+ dateUpdated: 'dateUpdated',
1899
+ friendlyName: 'friendlyName',
1900
+ lastConsumedMessageIndex: 'lastConsumedMessageIndex',
1901
+ notificationLevel: 'notificationLevel',
1902
+ sid: 'sid',
1903
+ status: 'status',
1904
+ uniqueName: 'uniqueName',
1905
+ state: 'state'
1906
+ };
1907
+ function parseTime(timeString) {
1908
+ try {
1909
+ return new Date(timeString);
1910
+ }
1911
+ catch (e) {
1912
+ return null;
1913
+ }
1914
+ }
1915
+ /**
1916
+ * A conversation represents communication between multiple Conversations clients
1917
+ */
1918
+ class Conversation extends replayEventEmitter.ReplayEventEmitter {
1919
+ /**
1920
+ * @internal
1921
+ */
1922
+ constructor(descriptor, sid, links, configuration, services) {
1923
+ super();
1924
+ this.sid = sid;
1925
+ this.links = links;
1926
+ this.configuration = configuration;
1927
+ this.services = services;
1928
+ let attributes = descriptor.attributes || {};
1929
+ let createdBy = descriptor.createdBy;
1930
+ let dateCreated = parseTime(descriptor.dateCreated);
1931
+ let dateUpdated = parseTime(descriptor.dateUpdated);
1932
+ let friendlyName = descriptor.friendlyName || null;
1933
+ let lastReadMessageIndex = Number.isInteger(descriptor.lastConsumedMessageIndex) ? descriptor.lastConsumedMessageIndex : null;
1934
+ let uniqueName = descriptor.uniqueName || null;
1935
+ try {
1936
+ JSON.stringify(attributes);
1937
+ }
1938
+ catch (e) {
1939
+ throw new Error('Attributes must be a valid JSON object.');
1940
+ }
1941
+ this.entityName = descriptor.channel;
1942
+ this.channelState = {
1943
+ uniqueName,
1944
+ status: 'notParticipating',
1945
+ attributes,
1946
+ createdBy,
1947
+ dateCreated,
1948
+ dateUpdated,
1949
+ friendlyName,
1950
+ lastReadMessageIndex: lastReadMessageIndex
1951
+ };
1952
+ if (descriptor.notificationLevel) {
1953
+ this.channelState.notificationLevel = descriptor.notificationLevel;
1954
+ }
1955
+ const participantsLinks = {
1956
+ participants: this.links.participants
1957
+ };
1958
+ this.participants = new Map();
1959
+ this.participantsEntity = new Participants(this, this.participants, participantsLinks, this.configuration, this.services);
1960
+ this.participantsEntity.on('participantJoined', this.emit.bind(this, 'participantJoined'));
1961
+ this.participantsEntity.on('participantLeft', this.emit.bind(this, 'participantLeft'));
1962
+ this.participantsEntity.on('participantUpdated', (args) => this.emit('participantUpdated', args));
1963
+ this.messagesEntity = new Messages(this, configuration, services);
1964
+ this.messagesEntity.on('messageAdded', message => this._onMessageAdded(message));
1965
+ this.messagesEntity.on('messageUpdated', (args) => this.emit('messageUpdated', args));
1966
+ this.messagesEntity.on('messageRemoved', this.emit.bind(this, 'messageRemoved'));
1967
+ }
1968
+ /**
1969
+ * Unique name of the conversation.
1970
+ */
1971
+ get uniqueName() { return this.channelState.uniqueName; }
1972
+ /**
1973
+ * Status of the conversation.
1974
+ */
1975
+ get status() { return this.channelState.status; }
1976
+ /**
1977
+ * Name of the conversation.
1978
+ */
1979
+ get friendlyName() { return this.channelState.friendlyName; }
1980
+ /**
1981
+ * Date this conversation was last updated on.
1982
+ */
1983
+ get dateUpdated() { return this.channelState.dateUpdated; }
1984
+ /**
1985
+ * Date this conversation was created on.
1986
+ */
1987
+ get dateCreated() { return this.channelState.dateCreated; }
1988
+ /**
1989
+ * Identity of the user that created this conversation.
1990
+ */
1991
+ get createdBy() { return this.channelState.createdBy; }
1992
+ /**
1993
+ * Custom attributes of the conversation.
1994
+ */
1995
+ get attributes() { return this.channelState.attributes; }
1996
+ /**
1997
+ * Index of the last message the user has read in this conversation.
1998
+ */
1999
+ get lastReadMessageIndex() { return this.channelState.lastReadMessageIndex; }
2000
+ /**
2001
+ * Last message sent to this conversation.
2002
+ */
2003
+ get lastMessage() { return this.channelState.lastMessage; }
2004
+ /**
2005
+ * User notification level for this conversation.
2006
+ */
2007
+ get notificationLevel() { return this.channelState.notificationLevel; }
2008
+ get limits() { return this.configuration.limits; }
2009
+ /**
2010
+ * State of the conversation.
2011
+ */
2012
+ get state() { return this.channelState.state; }
2013
+ /**
2014
+ * Load and subscribe to this conversation and do not subscribe to its participants and messages.
2015
+ * This or _subscribeStreams will need to be called before any events on conversation will fire.
2016
+ * @internal
2017
+ */
2018
+ _subscribe() {
2019
+ var _a;
2020
+ return this.entityPromise = (_a = this.entityPromise) !== null && _a !== void 0 ? _a : this.services.syncClient.document({ id: this.entityName, mode: 'open_existing' })
2021
+ .then(entity => {
2022
+ this.entity = entity;
2023
+ this.entity.on('updated', args => { this._update(args.data); });
2024
+ this.entity.on('removed', () => this.emit('removed', this));
2025
+ this._update(this.entity.data);
2026
+ return entity;
2027
+ })
2028
+ .catch(err => {
2029
+ this.entity = null;
2030
+ this.entityPromise = null;
2031
+ if (this.services.syncClient.connectionState != 'disconnected') {
2032
+ log$3.error('Failed to get conversation object', err);
2033
+ }
2034
+ log$3.debug('ERROR: Failed to get conversation object', err);
2035
+ throw err;
2036
+ });
2037
+ }
2038
+ /**
2039
+ * Load the attributes of this conversation and instantiate its participants and messages.
2040
+ * This or _subscribe will need to be called before any events on the conversation will fire.
2041
+ * This will need to be called before any events on participants or messages will fire
2042
+ * @internal
2043
+ */
2044
+ async _subscribeStreams() {
2045
+ try {
2046
+ await this._subscribe();
2047
+ log$3.trace('_subscribeStreams, this.entity.data=', this.entity.data);
2048
+ const messagesObjectName = this.entity.data.messages;
2049
+ const rosterObjectName = this.entity.data.roster;
2050
+ await Promise.all([
2051
+ this.messagesEntity.subscribe(messagesObjectName),
2052
+ this.participantsEntity.subscribe(rosterObjectName)
2053
+ ]);
2054
+ }
2055
+ catch (err) {
2056
+ if (this.services.syncClient.connectionState !== 'disconnected') {
2057
+ log$3.error('Failed to subscribe on conversation objects', this.sid, err);
2058
+ }
2059
+ log$3.debug('ERROR: Failed to subscribe on conversation objects', this.sid, err);
2060
+ throw err;
2061
+ }
2062
+ }
2063
+ /**
2064
+ * Stop listening for and firing events on this conversation.
2065
+ * @internal
2066
+ */
2067
+ async _unsubscribe() {
2068
+ if (this.entity) {
2069
+ await this.entity.close();
2070
+ this.entity = null;
2071
+ this.entityPromise = null;
2072
+ }
2073
+ return Promise.all([
2074
+ this.participantsEntity.unsubscribe(),
2075
+ this.messagesEntity.unsubscribe()
2076
+ ]);
2077
+ }
2078
+ /**
2079
+ * Set conversation status.
2080
+ * @internal
2081
+ */
2082
+ _setStatus(status, source) {
2083
+ this.statusSource = source;
2084
+ if (this.channelState.status === status) {
2085
+ return;
2086
+ }
2087
+ this.channelState.status = status;
2088
+ if (status === 'joined') {
2089
+ this._subscribeStreams()
2090
+ .catch(err => {
2091
+ log$3.debug('ERROR while setting conversation status ' + status, err);
2092
+ if (this.services.syncClient.connectionState !== 'disconnected') {
2093
+ throw err;
2094
+ }
2095
+ });
2096
+ }
2097
+ else if (this.entityPromise) {
2098
+ this._unsubscribe().catch(err => {
2099
+ log$3.debug('ERROR while setting conversation status ' + status, err);
2100
+ if (this.services.syncClient.connectionState !== 'disconnected') {
2101
+ throw err;
2102
+ }
2103
+ });
2104
+ }
2105
+ }
2106
+ /**
2107
+ * Get the source of the conversation update.
2108
+ * @internal
2109
+ */
2110
+ _statusSource() {
2111
+ return this.statusSource;
2112
+ }
2113
+ static preprocessUpdate(update, conversationSid) {
2114
+ try {
2115
+ if (typeof update.attributes === 'string') {
2116
+ update.attributes = JSON.parse(update.attributes);
2117
+ }
2118
+ else if (update.attributes) {
2119
+ JSON.stringify(update.attributes);
2120
+ }
2121
+ }
2122
+ catch (e) {
2123
+ log$3.warn('Retrieved malformed attributes from the server for conversation: ' + conversationSid);
2124
+ update.attributes = {};
2125
+ }
2126
+ try {
2127
+ if (update.dateCreated) {
2128
+ update.dateCreated = new Date(update.dateCreated);
2129
+ }
2130
+ }
2131
+ catch (e) {
2132
+ log$3.warn('Retrieved malformed dateCreated from the server for conversation: ' + conversationSid);
2133
+ delete update.dateCreated;
2134
+ }
2135
+ try {
2136
+ if (update.dateUpdated) {
2137
+ update.dateUpdated = new Date(update.dateUpdated);
2138
+ }
2139
+ }
2140
+ catch (e) {
2141
+ log$3.warn('Retrieved malformed dateUpdated from the server for conversation: ' + conversationSid);
2142
+ delete update.dateUpdated;
2143
+ }
2144
+ try {
2145
+ if (update.lastMessage && update.lastMessage.timestamp) {
2146
+ update.lastMessage.timestamp = new Date(update.lastMessage.timestamp);
2147
+ }
2148
+ }
2149
+ catch (e) {
2150
+ log$3.warn('Retrieved malformed lastMessage.timestamp from the server for conversation: ' + conversationSid);
2151
+ delete update.lastMessage.timestamp;
2152
+ }
2153
+ }
2154
+ /**
2155
+ * Update the local conversation object with new values.
2156
+ * @internal
2157
+ */
2158
+ _update(update) {
2159
+ var _a, _b, _c, _d, _e;
2160
+ log$3.trace('_update', update);
2161
+ Conversation.preprocessUpdate(update, this.sid);
2162
+ const updateReasons = new Set();
2163
+ for (const key of Object.keys(update)) {
2164
+ const localKey = fieldMappings[key];
2165
+ if (!localKey) {
2166
+ continue;
2167
+ }
2168
+ switch (localKey) {
2169
+ case fieldMappings.status:
2170
+ if (!update.status || update.status === 'unknown'
2171
+ || this.channelState.status === update.status) {
2172
+ break;
2173
+ }
2174
+ this.channelState.status = update.status;
2175
+ updateReasons.add(localKey);
2176
+ break;
2177
+ case fieldMappings.attributes:
2178
+ if (isDeepEqual(this.channelState.attributes, update.attributes)) {
2179
+ break;
2180
+ }
2181
+ this.channelState.attributes = update.attributes;
2182
+ updateReasons.add(localKey);
2183
+ break;
2184
+ case fieldMappings.lastConsumedMessageIndex:
2185
+ if (update.lastConsumedMessageIndex === undefined
2186
+ || update.lastConsumedMessageIndex === this.channelState.lastReadMessageIndex) {
2187
+ break;
2188
+ }
2189
+ this.channelState.lastReadMessageIndex = update.lastConsumedMessageIndex;
2190
+ updateReasons.add('lastReadMessageIndex');
2191
+ break;
2192
+ case fieldMappings.lastMessage:
2193
+ if (this.channelState.lastMessage && !update.lastMessage) {
2194
+ delete this.channelState.lastMessage;
2195
+ updateReasons.add(localKey);
2196
+ break;
2197
+ }
2198
+ this.channelState.lastMessage = this.channelState.lastMessage || {};
2199
+ if (((_a = update.lastMessage) === null || _a === void 0 ? void 0 : _a.index) !== undefined
2200
+ && update.lastMessage.index !== this.channelState.lastMessage.index) {
2201
+ this.channelState.lastMessage.index = update.lastMessage.index;
2202
+ updateReasons.add(localKey);
2203
+ }
2204
+ if (((_b = update.lastMessage) === null || _b === void 0 ? void 0 : _b.timestamp) !== undefined
2205
+ && ((_d = (_c = this.channelState.lastMessage) === null || _c === void 0 ? void 0 : _c.dateCreated) === null || _d === void 0 ? void 0 : _d.getTime()) !== update.lastMessage.timestamp.getTime()) {
2206
+ this.channelState.lastMessage.dateCreated = update.lastMessage.timestamp;
2207
+ updateReasons.add(localKey);
2208
+ }
2209
+ if (isDeepEqual(this.channelState.lastMessage, {})) {
2210
+ delete this.channelState.lastMessage;
2211
+ }
2212
+ break;
2213
+ case fieldMappings.state:
2214
+ const state = update.state || undefined;
2215
+ if (state !== undefined) {
2216
+ state.dateUpdated = new Date(state.dateUpdated);
2217
+ }
2218
+ if (isDeepEqual(this.channelState.state, state)) {
2219
+ break;
2220
+ }
2221
+ this.channelState.state = state;
2222
+ updateReasons.add(localKey);
2223
+ break;
2224
+ default:
2225
+ const isDate = update[key] instanceof Date;
2226
+ const keysMatchAsDates = isDate && ((_e = this.channelState[localKey]) === null || _e === void 0 ? void 0 : _e.getTime()) === update[key].getTime();
2227
+ const keysMatchAsNonDates = !isDate && this[localKey] === update[key];
2228
+ if (keysMatchAsDates || keysMatchAsNonDates) {
2229
+ break;
2230
+ }
2231
+ this.channelState[localKey] = update[key];
2232
+ updateReasons.add(localKey);
2233
+ }
2234
+ }
2235
+ if (updateReasons.size > 0) {
2236
+ this.emit('updated', { conversation: this, updateReasons: [...updateReasons] });
2237
+ }
2238
+ }
2239
+ /**
2240
+ * @internal
2241
+ */
2242
+ _onMessageAdded(message) {
2243
+ for (let participant of this.participants.values()) {
2244
+ if (participant.identity === message.author) {
2245
+ participant._endTyping();
2246
+ break;
2247
+ }
2248
+ }
2249
+ this.emit('messageAdded', message);
2250
+ }
2251
+ async _setLastReadMessageIndex(index) {
2252
+ const result = await this.services.commandExecutor.mutateResource('post', `${this.configuration.links.myConversations}/${this.sid}`, {
2253
+ last_read_message_index: index
2254
+ });
2255
+ return result.unread_messages_count;
2256
+ }
2257
+ /**
2258
+ * Add a participant to the conversation by its identity.
2259
+ * @param identity Identity of the Client to add.
2260
+ * @param attributes Attributes to be attached to the participant.
2261
+ */
2262
+ async add(identity, attributes) {
2263
+ return this.participantsEntity.add(identity, attributes);
2264
+ }
2265
+ /**
2266
+ * Add a non-chat participant to the conversation.
2267
+ * @param proxyAddress Proxy (Twilio) address of the participant.
2268
+ * @param address User address of the participant.
2269
+ * @param attributes Attributes to be attached to the participant.
2270
+ */
2271
+ async addNonChatParticipant(proxyAddress, address, attributes) {
2272
+ return this.participantsEntity.addNonChatParticipant(proxyAddress, address, attributes);
2273
+ }
2274
+ /**
2275
+ * Advance the conversation's last read message index to the current read horizon.
2276
+ * Rejects if the user is not a participant of the conversation.
2277
+ * Last read message index is updated only if the new index value is higher than the previous.
2278
+ * @param index Message index to advance to.
2279
+ * @return Resulting unread messages count in the conversation.
2280
+ */
2281
+ async advanceLastReadMessageIndex(index) {
2282
+ await this._subscribeStreams();
2283
+ if (index < this.lastReadMessageIndex) {
2284
+ return await this._setLastReadMessageIndex(this.lastReadMessageIndex);
2285
+ }
2286
+ return await this._setLastReadMessageIndex(index);
2287
+ }
2288
+ /**
2289
+ * Delete the conversation and unsubscribe from its events.
2290
+ */
2291
+ async delete() {
2292
+ await this.services.commandExecutor.mutateResource('delete', this.links.self);
2293
+ return this;
2294
+ }
2295
+ /**
2296
+ * Get the custom attributes of this Conversation.
2297
+ */
2298
+ async getAttributes() {
2299
+ await this._subscribe();
2300
+ return this.attributes;
2301
+ }
2302
+ /**
2303
+ * Returns messages from the conversation using the paginator interface.
2304
+ * @param pageSize Number of messages to return in a single chunk. Default is 30.
2305
+ * @param anchor Index of the newest message to fetch. Default is from the end.
2306
+ * @param direction Query direction. By default it queries backwards
2307
+ * from newer to older. The `"forward"` value will query in the opposite direction.
2308
+ * @return A page of messages.
2309
+ */
2310
+ async getMessages(pageSize, anchor, direction) {
2311
+ await this._subscribeStreams();
2312
+ return this.messagesEntity.getMessages(pageSize, anchor, direction);
2313
+ }
2314
+ /**
2315
+ * Get a list of all the participants who are joined to this conversation.
2316
+ */
2317
+ async getParticipants() {
2318
+ await this._subscribeStreams();
2319
+ return this.participantsEntity.getParticipants();
2320
+ }
2321
+ /**
2322
+ * Get conversation participants count.
2323
+ *
2324
+ * This method is semi-realtime. This means that this data will be eventually correct,
2325
+ * but will also be possibly incorrect for a few seconds. The Conversations system does not
2326
+ * provide real time events for counter values changes.
2327
+ *
2328
+ * This is useful for any UI badges, but it is not recommended to build any core application
2329
+ * logic based on these counters being accurate in real time.
2330
+ */
2331
+ async getParticipantsCount() {
2332
+ const url = new UriBuilder(this.configuration.links.conversations)
2333
+ .path(this.sid)
2334
+ .build();
2335
+ const response = await this.services.network.get(url);
2336
+ return response.body.participants_count;
2337
+ }
2338
+ /**
2339
+ * Get a participant by its SID.
2340
+ * @param participantSid Participant SID.
2341
+ */
2342
+ async getParticipantBySid(participantSid) {
2343
+ return this.participantsEntity.getParticipantBySid(participantSid);
2344
+ }
2345
+ /**
2346
+ * Get a participant by its identity.
2347
+ * @param identity Participant identity.
2348
+ */
2349
+ async getParticipantByIdentity(identity) {
2350
+ return this.participantsEntity.getParticipantByIdentity(identity);
2351
+ }
2352
+ /**
2353
+ * Get the total message count in the conversation.
2354
+ *
2355
+ * This method is semi-realtime. This means that this data will be eventually correct,
2356
+ * but will also be possibly incorrect for a few seconds. The Conversations system does not
2357
+ * provide real time events for counter values changes.
2358
+ *
2359
+ * This is useful for any UI badges, but it is not recommended to build any core application
2360
+ * logic based on these counters being accurate in real time.
2361
+ */
2362
+ async getMessagesCount() {
2363
+ const url = new UriBuilder(this.configuration.links.conversations)
2364
+ .path(this.sid)
2365
+ .build();
2366
+ const response = await this.services.network.get(url);
2367
+ return response.body.messages_count;
2368
+ }
2369
+ /**
2370
+ * Get unread messages count for the user if they are a participant of this conversation.
2371
+ * Rejects if the user is not a participant of the conversation.
2372
+ *
2373
+ * Use this method to obtain the number of unread messages together with
2374
+ * {@link Conversation.updateLastReadMessageIndex} instead of relying on the
2375
+ * message indices which may have gaps. See {@link Message.index} for details.
2376
+ *
2377
+ * This method is semi-realtime. This means that this data will be eventually correct,
2378
+ * but will also be possibly incorrect for a few seconds. The Conversations system does not
2379
+ * provide real time events for counter values changes.
2380
+ *
2381
+ * This is useful for any UI badges, but it is not recommended to build any core application
2382
+ * logic based on these counters being accurate in real time.
2383
+ */
2384
+ async getUnreadMessagesCount() {
2385
+ const url = new UriBuilder(this.configuration.links.myConversations)
2386
+ .path(this.sid)
2387
+ .build();
2388
+ const response = await this.services.network.get(url);
2389
+ if (response.body.conversation_sid !== this.sid) {
2390
+ throw new Error('Conversation was not found in the user conversations list');
2391
+ }
2392
+ const unreadMessageCount = response.body.unread_messages_count;
2393
+ if (typeof unreadMessageCount === 'number') {
2394
+ return unreadMessageCount;
2395
+ }
2396
+ return null;
2397
+ }
2398
+ /**
2399
+ * Join the conversation and subscribe to its events.
2400
+ */
2401
+ async join() {
2402
+ await this.services.commandExecutor.mutateResource('post', this.links.participants, {
2403
+ identity: this.configuration.userIdentity
2404
+ });
2405
+ return this;
2406
+ }
2407
+ /**
2408
+ * Leave the conversation.
2409
+ */
2410
+ async leave() {
2411
+ if (this.channelState.status === 'joined') {
2412
+ await this.services.commandExecutor.mutateResource('delete', `${this.links.participants}/${this.configuration.userIdentity}`);
2413
+ }
2414
+ return this;
2415
+ }
2416
+ /**
2417
+ * Remove a participant from the conversation. When a string is passed as the
2418
+ * argument, it will assume that the string is an identity or SID.
2419
+ * @param participant Identity, SID or the participant object to remove.
2420
+ */
2421
+ async removeParticipant(participant) {
2422
+ await this.participantsEntity.remove(typeof participant === 'string'
2423
+ ? participant
2424
+ : participant.sid);
2425
+ }
2426
+ /**
2427
+ * Send a message to the conversation.
2428
+ * @param message Message body for the text message,
2429
+ * `FormData` or {@link SendMediaOptions} for media content. Sending FormData is supported only with the browser engine.
2430
+ * @param messageAttributes Attributes for the message.
2431
+ * @param emailOptions Email options for the message.
2432
+ * @return Index of the new message.
2433
+ */
2434
+ async sendMessage(message, messageAttributes, emailOptions) {
2435
+ if (typeof message === 'string' || message === null) {
2436
+ let response = await this.messagesEntity.send(message, messageAttributes, emailOptions);
2437
+ return parseToNumber(response.index);
2438
+ }
2439
+ let response = await this.messagesEntity.sendMedia(message, messageAttributes, emailOptions);
2440
+ return parseToNumber(response.index);
2441
+ }
2442
+ /**
2443
+ * New interface to prepare for sending a message.
2444
+ * Use instead of `sendMessage`.
2445
+ */
2446
+ prepareMessage() {
2447
+ return new MessageBuilder(this.limits, this.messagesEntity);
2448
+ }
2449
+ /**
2450
+ * Set last read message index of the conversation to the index of the last known message.
2451
+ * @return Resulting unread messages count in the conversation.
2452
+ */
2453
+ async setAllMessagesRead() {
2454
+ await this._subscribeStreams();
2455
+ let messagesPage = await this.getMessages(1);
2456
+ if (messagesPage.items.length > 0) {
2457
+ return this.advanceLastReadMessageIndex(messagesPage.items[0].index);
2458
+ }
2459
+ return Promise.resolve(0);
2460
+ }
2461
+ /**
2462
+ * Set all messages in the conversation unread.
2463
+ * @return Resulting unread messages count in the conversation.
2464
+ */
2465
+ async setAllMessagesUnread() {
2466
+ await this._subscribeStreams();
2467
+ return await this._setLastReadMessageIndex(null);
2468
+ }
2469
+ /**
2470
+ * Set user notification level for this conversation.
2471
+ * @param notificationLevel New user notification level.
2472
+ */
2473
+ async setUserNotificationLevel(notificationLevel) {
2474
+ await this.services.commandExecutor.mutateResource('post', `${this.configuration.links.myConversations}/${this.sid}`, {
2475
+ notification_level: notificationLevel
2476
+ });
2477
+ }
2478
+ /**
2479
+ * Send a notification to the server indicating that this client is currently typing in this conversation.
2480
+ * Typing ended notification is sent after a while automatically, but by calling this method again you ensure that typing ended is not received.
2481
+ */
2482
+ typing() {
2483
+ return this.services.typingIndicator.send(this.sid);
2484
+ }
2485
+ /**
2486
+ * Update the attributes of the conversation.
2487
+ * @param attributes New attributes.
2488
+ */
2489
+ async updateAttributes(attributes) {
2490
+ await this.services.commandExecutor.mutateResource('post', this.links.self, {
2491
+ attributes: attributes !== undefined ? JSON.stringify(attributes) : undefined
2492
+ });
2493
+ return this;
2494
+ }
2495
+ /**
2496
+ * Update the friendly name of the conversation.
2497
+ * @param friendlyName New friendly name.
2498
+ */
2499
+ async updateFriendlyName(friendlyName) {
2500
+ if (this.channelState.friendlyName !== friendlyName) {
2501
+ await this.services.commandExecutor.mutateResource('post', this.links.self, { friendly_name: friendlyName });
2502
+ }
2503
+ return this;
2504
+ }
2505
+ /**
2506
+ * Set the last read message index to the current read horizon.
2507
+ * @param index Message index to set as last read.
2508
+ * If null is provided, then the behavior is identical to {@link Conversation.setAllMessagesUnread}.
2509
+ * @returns Resulting unread messages count in the conversation.
2510
+ */
2511
+ async updateLastReadMessageIndex(index) {
2512
+ await this._subscribeStreams();
2513
+ return this._setLastReadMessageIndex(index);
2514
+ }
2515
+ /**
2516
+ * Update the unique name of the conversation.
2517
+ * @param uniqueName New unique name for the conversation. Setting unique name to null removes it.
2518
+ */
2519
+ async updateUniqueName(uniqueName) {
2520
+ if (this.channelState.uniqueName !== uniqueName) {
2521
+ if (!uniqueName) {
2522
+ uniqueName = '';
2523
+ }
2524
+ await this.services.commandExecutor.mutateResource('post', this.links.self, {
2525
+ unique_name: uniqueName
2526
+ });
2527
+ }
2528
+ return this;
2529
+ }
2530
+ }
2531
+ /**
2532
+ * Fired when a participant has joined the conversation.
2533
+ *
2534
+ * Parameters:
2535
+ * 1. {@link Participant} `participant` - participant that joined the conversation
2536
+ * @event
2537
+ */
2538
+ Conversation.participantJoined = 'participantJoined';
2539
+ /**
2540
+ * Fired when a participant has left the conversation.
2541
+ *
2542
+ * Parameters:
2543
+ * 1. {@link Participant} `participant` - participant that left the conversation
2544
+ * @event
2545
+ */
2546
+ Conversation.participantLeft = 'participantLeft';
2547
+ /**
2548
+ * Fired when data of a participant has been updated.
2549
+ *
2550
+ * Parameters:
2551
+ * 1. object `data` - info object provided with the event. It has the following properties:
2552
+ * * {@link Participant} `participant` - participant that has received the update
2553
+ * * {@link ParticipantUpdateReason}[] `updateReasons` - array of reasons for update
2554
+ * @event
2555
+ */
2556
+ Conversation.participantUpdated = 'participantUpdated';
2557
+ /**
2558
+ * Fired when a new message has been added to the conversation.
2559
+ *
2560
+ * Parameters:
2561
+ * 1. {@link Message} `message` - message that has been added
2562
+ * @event
2563
+ */
2564
+ Conversation.messageAdded = 'messageAdded';
2565
+ /**
2566
+ * Fired when message is removed from the conversation's message list.
2567
+ *
2568
+ * Parameters:
2569
+ * 1. {@link Message} `message` - message that has been removed
2570
+ * @event
2571
+ */
2572
+ Conversation.messageRemoved = 'messageRemoved';
2573
+ /**
2574
+ * Fired when data of a message has been updated.
2575
+ *
2576
+ * Parameters:
2577
+ * 1. object `data` - info object provided with the event. It has the following properties:
2578
+ * * {@link Message} `message` - message that has received the update
2579
+ * * {@link MessageUpdateReason}[] `updateReasons` - array of reasons for update
2580
+ * @event
2581
+ */
2582
+ Conversation.messageUpdated = 'messageUpdated';
2583
+ /**
2584
+ * Fired when a participant has stopped typing.
2585
+ *
2586
+ * Parameters:
2587
+ * 1. {@link Participant} `participant` - the participant that has stopped typing
2588
+ * @event
2589
+ */
2590
+ Conversation.typingEnded = 'typingEnded';
2591
+ /**
2592
+ * Fired when a participant has started typing.
2593
+ *
2594
+ * Parameters:
2595
+ * 1. {@link Participant} `participant` - the participant that has started typing
2596
+ * @event
2597
+ */
2598
+ Conversation.typingStarted = 'typingStarted';
2599
+ /**
2600
+ * Fired when the data of the conversation has been updated.
2601
+ *
2602
+ * Parameters:
2603
+ * 1. object `data` - info object provided with the event. It has the following properties:
2604
+ * * {@link Conversation} `conversation` - conversation that has received the update
2605
+ * * {@link ConversationUpdateReason}[] `updateReasons` - array of reasons for update
2606
+ * @event
2607
+ */
2608
+ Conversation.updated = 'updated';
2609
+ /**
2610
+ * Fired when the conversation was destroyed or the currently-logged-in user has left private conversation.
2611
+ *
2612
+ * Parameters:
2613
+ * 1. {@link Conversation} `conversation` - conversation that has been removed
2614
+ * @event
2615
+ */
2616
+ Conversation.removed = 'removed';
2617
+ __decorate([
2618
+ declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString, ['undefined', 'string', 'number', 'boolean', 'object', declarativeTypeValidator.literal(null)]),
2619
+ __metadata("design:type", Function),
2620
+ __metadata("design:paramtypes", [String, Object]),
2621
+ __metadata("design:returntype", Promise)
2622
+ ], Conversation.prototype, "add", null);
2623
+ __decorate([
2624
+ declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString, declarativeTypeValidator.nonEmptyString, ['undefined', 'string', 'number', 'boolean', 'object', declarativeTypeValidator.literal(null)]),
2625
+ __metadata("design:type", Function),
2626
+ __metadata("design:paramtypes", [String, String, Object]),
2627
+ __metadata("design:returntype", Promise)
2628
+ ], Conversation.prototype, "addNonChatParticipant", null);
2629
+ __decorate([
2630
+ declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonNegativeInteger),
2631
+ __metadata("design:type", Function),
2632
+ __metadata("design:paramtypes", [Number]),
2633
+ __metadata("design:returntype", Promise)
2634
+ ], Conversation.prototype, "advanceLastReadMessageIndex", null);
2635
+ __decorate([
2636
+ declarativeTypeValidator.validateTypesAsync(['undefined', declarativeTypeValidator.nonNegativeInteger], ['undefined', declarativeTypeValidator.nonNegativeInteger], ['undefined', declarativeTypeValidator.literal('backwards', 'forward')]),
2637
+ __metadata("design:type", Function),
2638
+ __metadata("design:paramtypes", [Number, Number, String]),
2639
+ __metadata("design:returntype", Promise)
2640
+ ], Conversation.prototype, "getMessages", null);
2641
+ __decorate([
2642
+ declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString),
2643
+ __metadata("design:type", Function),
2644
+ __metadata("design:paramtypes", [String]),
2645
+ __metadata("design:returntype", Promise)
2646
+ ], Conversation.prototype, "getParticipantBySid", null);
2647
+ __decorate([
2648
+ declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString),
2649
+ __metadata("design:type", Function),
2650
+ __metadata("design:paramtypes", [String]),
2651
+ __metadata("design:returntype", Promise)
2652
+ ], Conversation.prototype, "getParticipantByIdentity", null);
2653
+ __decorate([
2654
+ declarativeTypeValidator.validateTypesAsync([declarativeTypeValidator.nonEmptyString, Participant]),
2655
+ __metadata("design:type", Function),
2656
+ __metadata("design:paramtypes", [Object]),
2657
+ __metadata("design:returntype", Promise)
2658
+ ], Conversation.prototype, "removeParticipant", null);
2659
+ __decorate([
2660
+ declarativeTypeValidator.validateTypesAsync([
2661
+ 'string',
2662
+ declarativeTypeValidator.literal(null),
2663
+ // Wrapping it into a custom rule is necessary because the FormData class is not available on initialization.
2664
+ declarativeTypeValidator.custom((value) => [value instanceof FormData, 'an instance of FormData']),
2665
+ declarativeTypeValidator.objectSchema('media options', {
2666
+ contentType: declarativeTypeValidator.nonEmptyString,
2667
+ media: declarativeTypeValidator.custom((value) => {
2668
+ let isValid = (typeof value === 'string' && value.length > 0) || value instanceof Uint8Array || value instanceof ArrayBuffer;
2669
+ if (typeof Blob === 'function') {
2670
+ isValid = isValid || value instanceof Blob;
2671
+ }
2672
+ return [
2673
+ isValid,
2674
+ 'a non-empty string, an instance of Buffer or an instance of Blob'
2675
+ ];
2676
+ })
2677
+ })
2678
+ ], ['undefined', 'string', 'number', 'boolean', 'object', declarativeTypeValidator.literal(null)], ['undefined', declarativeTypeValidator.literal(null), declarativeTypeValidator.objectSchema('email attributes', {
2679
+ subject: [declarativeTypeValidator.nonEmptyString, 'undefined']
2680
+ })]),
2681
+ __metadata("design:type", Function),
2682
+ __metadata("design:paramtypes", [Object, Object, Object]),
2683
+ __metadata("design:returntype", Promise)
2684
+ ], Conversation.prototype, "sendMessage", null);
2685
+ __decorate([
2686
+ declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.literal('default', 'muted')),
2687
+ __metadata("design:type", Function),
2688
+ __metadata("design:paramtypes", [String]),
2689
+ __metadata("design:returntype", Promise)
2690
+ ], Conversation.prototype, "setUserNotificationLevel", null);
2691
+ __decorate([
2692
+ declarativeTypeValidator.validateTypesAsync(['string', 'number', 'boolean', 'object', declarativeTypeValidator.literal(null)]),
2693
+ __metadata("design:type", Function),
2694
+ __metadata("design:paramtypes", [Object]),
2695
+ __metadata("design:returntype", Promise)
2696
+ ], Conversation.prototype, "updateAttributes", null);
2697
+ __decorate([
2698
+ declarativeTypeValidator.validateTypesAsync(['string']),
2699
+ __metadata("design:type", Function),
2700
+ __metadata("design:paramtypes", [String]),
2701
+ __metadata("design:returntype", Promise)
2702
+ ], Conversation.prototype, "updateFriendlyName", null);
2703
+ __decorate([
2704
+ declarativeTypeValidator.validateTypesAsync([declarativeTypeValidator.literal(null), declarativeTypeValidator.nonNegativeInteger]),
2705
+ __metadata("design:type", Function),
2706
+ __metadata("design:paramtypes", [Number]),
2707
+ __metadata("design:returntype", Promise)
2708
+ ], Conversation.prototype, "updateLastReadMessageIndex", null);
2709
+ __decorate([
2710
+ declarativeTypeValidator.validateTypesAsync(['string', declarativeTypeValidator.literal(null)]),
2711
+ __metadata("design:type", Function),
2712
+ __metadata("design:paramtypes", [String]),
2713
+ __metadata("design:returntype", Promise)
2714
+ ], Conversation.prototype, "updateUniqueName", null);
2715
+
2716
+ class Deferred {
2717
+ constructor() {
2718
+ this._promise = new Promise((resolve, reject) => {
2719
+ this._resolve = resolve;
2720
+ this._reject = reject;
2721
+ });
2722
+ }
2723
+ get promise() { return this._promise; }
2724
+ update(value) {
2725
+ this._resolve(value);
2726
+ }
2727
+ set(value) {
2728
+ this.current = value;
2729
+ this._resolve(value);
2730
+ }
2731
+ fail(e) {
2732
+ this._reject(e);
2733
+ }
2734
+ }
2735
+
2736
+ const log$2 = Logger.scope('Conversations');
2737
+ /**
2738
+ * Represents conversations collection
2739
+ * {@see Conversation}
2740
+ */
2741
+ class Conversations extends replayEventEmitter.ReplayEventEmitter {
2742
+ constructor(configuration, services) {
2743
+ super();
2744
+ this.conversations = new Map();
2745
+ this.myConversationsRead = new Deferred();
2746
+ this.tombstones = new Set();
2747
+ this.myConversationsFetched = false;
2748
+ this.configuration = configuration;
2749
+ this.services = services;
2750
+ }
2751
+ async addConversation(options) {
2752
+ var _a, _b, _c;
2753
+ const attributes = typeof (options === null || options === void 0 ? void 0 : options.attributes) !== 'undefined'
2754
+ ? options.attributes
2755
+ : {};
2756
+ const response = await this.services.commandExecutor.mutateResource('post', this.configuration.links.conversations, {
2757
+ friendly_name: options.friendlyName,
2758
+ unique_name: options.uniqueName,
2759
+ attributes: typeof attributes !== 'undefined' ? JSON.stringify(attributes) : undefined
2760
+ });
2761
+ const conversationSid = (_a = response.sid) !== null && _a !== void 0 ? _a : null;
2762
+ const conversationDocument = (_c = (_b = response.sync_objects) === null || _b === void 0 ? void 0 : _b.conversation) !== null && _c !== void 0 ? _c : null;
2763
+ const links = Object.assign({ self: response.url }, response.links);
2764
+ const existingConversation = this.conversations.get(conversationSid);
2765
+ if (existingConversation) {
2766
+ await existingConversation._subscribe();
2767
+ return existingConversation;
2768
+ }
2769
+ const conversation = new Conversation({
2770
+ channel: conversationDocument,
2771
+ entityName: null,
2772
+ uniqueName: null,
2773
+ attributes: null,
2774
+ createdBy: null,
2775
+ friendlyName: null,
2776
+ lastConsumedMessageIndex: null,
2777
+ dateCreated: null,
2778
+ dateUpdated: null
2779
+ }, conversationSid, links, this.configuration, this.services);
2780
+ this.conversations.set(conversation.sid, conversation);
2781
+ this._registerForEvents(conversation);
2782
+ await conversation._subscribe();
2783
+ this.emit('conversationAdded', conversation);
2784
+ return conversation;
2785
+ }
2786
+ /**
2787
+ * Fetch conversations list and instantiate all necessary objects
2788
+ */
2789
+ async fetchConversations() {
2790
+ try {
2791
+ const map = await this._getMap();
2792
+ map.on('itemAdded', args => {
2793
+ log$2.debug(`itemAdded: ${args.item.key}`);
2794
+ this._upsertConversation('sync', args.item.key, args.item.data);
2795
+ });
2796
+ map.on('itemRemoved', args => {
2797
+ log$2.debug(`itemRemoved: ${args.key}`);
2798
+ const sid = args.key;
2799
+ if (!this.myConversationsFetched) {
2800
+ this.tombstones.add(sid);
2801
+ }
2802
+ const conversation = this.conversations.get(sid);
2803
+ if (!conversation) {
2804
+ return;
2805
+ }
2806
+ if (conversation.status === 'joined') {
2807
+ conversation._setStatus('notParticipating', 'sync');
2808
+ this.emit('conversationLeft', conversation);
2809
+ }
2810
+ this.conversations.delete(sid);
2811
+ this.emit('conversationRemoved', conversation);
2812
+ conversation.emit('removed', conversation);
2813
+ });
2814
+ map.on('itemUpdated', args => {
2815
+ log$2.debug(`itemUpdated: ${args.item.key}`);
2816
+ this._upsertConversation('sync', args.item.key, args.item.data);
2817
+ });
2818
+ const myConversations = await this._fetchMyConversations();
2819
+ const upserts = [];
2820
+ for (const conversation of myConversations) {
2821
+ upserts.push(this._upsertConversation('rest', conversation.channel_sid, conversation));
2822
+ }
2823
+ this.myConversationsRead.set(true);
2824
+ await Promise.all(upserts);
2825
+ this.myConversationsFetched = true;
2826
+ this.tombstones.clear();
2827
+ log$2.debug('The conversations list has been successfully fetched');
2828
+ return this;
2829
+ }
2830
+ catch (error) {
2831
+ const errorMessage = 'Failed to fetch the conversations list';
2832
+ if (this.services.syncClient.connectionState !== 'disconnected') {
2833
+ log$2.error(errorMessage, error);
2834
+ }
2835
+ log$2.debug(`ERROR: ${errorMessage}`, error);
2836
+ throw error;
2837
+ }
2838
+ }
2839
+ async getConversations(args) {
2840
+ const conversationsMap = await this._getMap();
2841
+ const page = await conversationsMap.getItems();
2842
+ return this._wrapPaginator(page, items => Promise.all(items.map((item) => this._upsertConversation('sync', item.key, item.data))));
2843
+ }
2844
+ async getConversation(sid) {
2845
+ const conversationsMap = await this._getMap();
2846
+ const page = await conversationsMap.getItems({ from: sid });
2847
+ const items = page.items.map((item) => this._upsertConversation('sync', item.key, item.data));
2848
+ return items.length > 0 ? items[0] : null;
2849
+ }
2850
+ async getConversationByUniqueName(uniqueName) {
2851
+ const url = new UriBuilder(this.configuration.links.myConversations)
2852
+ .path(uniqueName)
2853
+ .build();
2854
+ const response = await this.services.network.get(url);
2855
+ const body = response.body;
2856
+ const sid = body.conversation_sid;
2857
+ const data = {
2858
+ entityName: null,
2859
+ lastConsumedMessageIndex: body.last_read_message_index,
2860
+ status: (body === null || body === void 0 ? void 0 : body.status) || 'unknown',
2861
+ friendlyName: body.friendly_name,
2862
+ dateUpdated: body.date_updated,
2863
+ dateCreated: body.date_created,
2864
+ uniqueName: body.unique_name,
2865
+ createdBy: body.created_by,
2866
+ attributes: body.attributes,
2867
+ channel: body.sync_objects.conversation,
2868
+ notificationLevel: body === null || body === void 0 ? void 0 : body.notification_level,
2869
+ sid
2870
+ };
2871
+ return this._upsertConversation('sync', sid, data);
2872
+ }
2873
+ async peekConversation(sid) {
2874
+ const url = new UriBuilder(this.configuration.links.conversations)
2875
+ .path(sid)
2876
+ .build();
2877
+ const response = await this.services.network.get(url);
2878
+ const body = response.body;
2879
+ const data = {
2880
+ entityName: null,
2881
+ // lastConsumedMessageIndex: body.last_read_message_index,
2882
+ status: (body === null || body === void 0 ? void 0 : body.status) || 'unknown',
2883
+ friendlyName: body.friendly_name,
2884
+ dateUpdated: body.date_updated,
2885
+ dateCreated: body.date_created,
2886
+ uniqueName: body.unique_name,
2887
+ createdBy: body.created_by,
2888
+ attributes: body.attributes,
2889
+ channel: `${sid}.channel`,
2890
+ // notificationLevel: body?.notification_level,
2891
+ sid
2892
+ };
2893
+ return this._upsertConversation('sync', sid, data);
2894
+ }
2895
+ async _getMap() {
2896
+ return await this.services.syncClient.map({
2897
+ id: this.configuration.myConversations,
2898
+ mode: 'open_existing'
2899
+ });
2900
+ }
2901
+ async _wrapPaginator(page, op) {
2902
+ const items = await op(page.items);
2903
+ return {
2904
+ items,
2905
+ hasNextPage: page.hasNextPage,
2906
+ hasPrevPage: page.hasPrevPage,
2907
+ nextPage: () => page.nextPage().then(x => this._wrapPaginator(x, op)),
2908
+ prevPage: () => page.prevPage().then(x => this._wrapPaginator(x, op))
2909
+ };
2910
+ }
2911
+ async _updateConversation(source, conversation, data) {
2912
+ const areSourcesDifferent = conversation._statusSource() !== undefined && source !== conversation._statusSource();
2913
+ const isChannelSourceSync = source !== 'rest' || conversation._statusSource() === 'sync';
2914
+ if (areSourcesDifferent && isChannelSourceSync && source !== 'sync') {
2915
+ log$2.trace('upsertConversation: conversation is known from sync and came from chat, ignoring', {
2916
+ sid: conversation.sid,
2917
+ data: data.status,
2918
+ conversation: conversation.status
2919
+ });
2920
+ return;
2921
+ }
2922
+ if (data.status === 'joined' && conversation.status !== 'joined') {
2923
+ conversation._setStatus('joined', source);
2924
+ let updateData = {};
2925
+ if (typeof data.notificationLevel !== 'undefined') {
2926
+ updateData.notificationLevel = data.notificationLevel;
2927
+ }
2928
+ if (typeof data.lastConsumedMessageIndex !== 'undefined') {
2929
+ updateData.lastConsumedMessageIndex = data.lastConsumedMessageIndex;
2930
+ }
2931
+ if (!isDeepEqual(updateData, {})) {
2932
+ conversation._update(updateData);
2933
+ }
2934
+ conversation._subscribe().then(() => {
2935
+ this.emit('conversationJoined', conversation);
2936
+ });
2937
+ return;
2938
+ }
2939
+ if (data.status === 'notParticipating' && conversation.status === 'joined') {
2940
+ conversation._setStatus('notParticipating', source);
2941
+ conversation._update(data);
2942
+ await conversation._subscribe();
2943
+ this.emit('conversationLeft', conversation);
2944
+ return;
2945
+ }
2946
+ if (data.status === 'notParticipating') {
2947
+ await conversation._subscribe();
2948
+ return;
2949
+ }
2950
+ conversation._update(data);
2951
+ }
2952
+ async _upsertConversation(source, sid, data) {
2953
+ log$2.trace(`upsertConversation called for ${sid}`, data);
2954
+ const conversation = this.conversations.get(sid);
2955
+ // If the channel is known, update it
2956
+ if (conversation) {
2957
+ log$2.trace(`upsertConversation: the conversation ${conversation.sid} is known;` +
2958
+ `its status is known from the source ${conversation._statusSource()} ` +
2959
+ `and the update came from the source ${source}`, conversation);
2960
+ await this._updateConversation(source, conversation, data);
2961
+ await conversation._subscribe();
2962
+ return conversation;
2963
+ }
2964
+ // If the conversations is deleted, ignore it
2965
+ if (['chat', 'rest'].includes(source) && this.tombstones.has(sid)) {
2966
+ log$2.trace('upsertChannel: the channel is deleted but reappeared again from chat, ignoring', sid);
2967
+ return;
2968
+ }
2969
+ // If the conversation is unknown, fetch it
2970
+ log$2.trace('upsertConversation: creating a local conversation object with sid ' + sid, data);
2971
+ const baseLink = `${this.configuration.links.conversations}/${sid}`;
2972
+ const links = {
2973
+ self: baseLink,
2974
+ messages: `${baseLink}/Messages`,
2975
+ participants: `${baseLink}/Participants`
2976
+ };
2977
+ const newConversation = new Conversation(data, sid, links, this.configuration, this.services);
2978
+ this.conversations.set(sid, newConversation);
2979
+ await newConversation._subscribe();
2980
+ this._registerForEvents(newConversation);
2981
+ this.emit('conversationAdded', newConversation);
2982
+ if (data.status === 'joined') {
2983
+ newConversation._setStatus('joined', source);
2984
+ this.emit('conversationJoined', newConversation);
2985
+ }
2986
+ return newConversation;
2987
+ }
2988
+ async _fetchMyConversations() {
2989
+ let conversations = [];
2990
+ let pageToken = null;
2991
+ do {
2992
+ const url = new UriBuilder(this.configuration.links.myConversations);
2993
+ if (pageToken) {
2994
+ url.arg('PageToken', pageToken);
2995
+ }
2996
+ const response = await this.services.network.get(url.build());
2997
+ const receivedConversations = response.body.conversations.map((conversationDescriptor) => ({
2998
+ descriptor: conversationDescriptor,
2999
+ channel_sid: conversationDescriptor.conversation_sid,
3000
+ status: conversationDescriptor.status,
3001
+ channel: conversationDescriptor.sync_objects.conversation,
3002
+ messages: conversationDescriptor.sync_objects.messages,
3003
+ roster: `${conversationDescriptor.conversation_sid}.roster`,
3004
+ lastConsumedMessageIndex: conversationDescriptor.last_consumed_message_index,
3005
+ notificationLevel: conversationDescriptor.notification_level
3006
+ }));
3007
+ pageToken = response.body.meta.next_token;
3008
+ conversations = [...conversations, ...receivedConversations];
3009
+ } while (pageToken);
3010
+ return conversations;
3011
+ }
3012
+ _onConversationRemoved(sid) {
3013
+ const conversation = this.conversations.get(sid);
3014
+ if (conversation) {
3015
+ this.conversations.delete(sid);
3016
+ this.emit('conversationRemoved', conversation);
3017
+ }
3018
+ }
3019
+ _registerForEvents(conversation) {
3020
+ conversation.on('removed', () => this._onConversationRemoved(conversation.sid));
3021
+ conversation.on('updated', (args) => this.emit('conversationUpdated', args));
3022
+ conversation.on('participantJoined', this.emit.bind(this, 'participantJoined'));
3023
+ conversation.on('participantLeft', this.emit.bind(this, 'participantLeft'));
3024
+ conversation.on('participantUpdated', (args) => this.emit('participantUpdated', args));
3025
+ conversation.on('messageAdded', this.emit.bind(this, 'messageAdded'));
3026
+ conversation.on('messageUpdated', (args) => this.emit('messageUpdated', args));
3027
+ conversation.on('messageRemoved', this.emit.bind(this, 'messageRemoved'));
3028
+ conversation.on('typingStarted', this.emit.bind(this, 'typingStarted'));
3029
+ conversation.on('typingEnded', this.emit.bind(this, 'typingEnded'));
3030
+ }
3031
+ }
3032
+
3033
+ /**
3034
+ * Container for known users
3035
+ */
3036
+ class Users extends replayEventEmitter.ReplayEventEmitter {
3037
+ constructor(myself, configuration, services) {
3038
+ super();
3039
+ this.configuration = configuration;
3040
+ this.services = services;
3041
+ this.fifoStack = [];
3042
+ this.myself = myself;
3043
+ this.myself.on('updated', (args) => this.emit('userUpdated', args));
3044
+ this.myself.on('userSubscribed', () => this.emit('userSubscribed', this.myself));
3045
+ this.myself.on('userUnsubscribed', () => {
3046
+ this.emit('userUnsubscribed', this.myself);
3047
+ this.myself._ensureFetched();
3048
+ });
3049
+ this.subscribedUsers = new Map();
3050
+ }
3051
+ handleUnsubscribeUser(user) {
3052
+ if (this.subscribedUsers.has(user.identity)) {
3053
+ this.subscribedUsers.delete(user.identity);
3054
+ }
3055
+ let foundItemIndex = -1;
3056
+ let foundItem = this.fifoStack.find((item, index) => {
3057
+ if (item == user.identity) {
3058
+ foundItemIndex = index;
3059
+ return true;
3060
+ }
3061
+ return false;
3062
+ });
3063
+ if (foundItem) {
3064
+ this.fifoStack.splice(foundItemIndex, 1);
3065
+ }
3066
+ this.emit('userUnsubscribed', user);
3067
+ }
3068
+ handleSubscribeUser(user) {
3069
+ if (this.subscribedUsers.has(user.identity)) {
3070
+ return;
3071
+ }
3072
+ if (this.fifoStack.length >= this.configuration.userInfosToSubscribe) {
3073
+ this.subscribedUsers.get(this.fifoStack.shift()).unsubscribe();
3074
+ }
3075
+ this.fifoStack.push(user.identity);
3076
+ this.subscribedUsers.set(user.identity, user);
3077
+ this.emit('userSubscribed', user);
3078
+ }
3079
+ /**
3080
+ * Gets user, if it's in subscribed list - then return the user object from it,
3081
+ * if not - then subscribes and adds user to the FIFO stack
3082
+ * @returns {Promise<User>} Fully initialized user
3083
+ */
3084
+ async getUser(identity, entityName = null) {
3085
+ await this.myself._ensureFetched();
3086
+ if (identity == this.myself.identity) {
3087
+ return this.myself;
3088
+ }
3089
+ let user = this.subscribedUsers.get(identity);
3090
+ if (!user) {
3091
+ if (!entityName) {
3092
+ entityName = await this.getSyncUniqueName(identity);
3093
+ }
3094
+ user = new User(identity, entityName, this.configuration, this.services);
3095
+ user.on('updated', (args) => this.emit('userUpdated', args));
3096
+ user.on('userSubscribed', () => this.handleSubscribeUser(user));
3097
+ user.on('userUnsubscribed', () => this.handleUnsubscribeUser(user));
3098
+ await user._ensureFetched();
3099
+ }
3100
+ return user;
3101
+ }
3102
+ /**
3103
+ * @returns {Promise<Array<User>>} returns list of subscribed User objects {@see User}
3104
+ */
3105
+ async getSubscribedUsers() {
3106
+ await this.myself._ensureFetched();
3107
+ const users = [this.myself];
3108
+ this.subscribedUsers.forEach((user) => users.push(user));
3109
+ return users;
3110
+ }
3111
+ /**
3112
+ * @returns {Promise<string>} User's sync unique name
3113
+ */
3114
+ async getSyncUniqueName(identity) {
3115
+ const url = new UriBuilder(this.configuration.links.users)
3116
+ .path(identity)
3117
+ .build();
3118
+ const response = await this.services.network.get(url);
3119
+ return response.body.sync_objects.user_info_map;
3120
+ }
3121
+ }
3122
+
3123
+ const log$1 = Logger.scope('TypingIndicator');
3124
+ /**
3125
+ * 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
3126
+ * 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
3127
+ * "typing_timeout" attribute will be exactly the same as defined in the console. The second place that the attribute appears in is from a
3128
+ * notification of type "twilio.ipmsg.typing_indicator". In this case, the "typing_timeout" value will be +1 of that in the console. This
3129
+ * intentional. The timeout returned from the POST -> /v1/typing call should be used to disable further calls for that period of time. On contrary,
3130
+ * the timeout returned from the notification should be used as the timeout for the "typingEnded" event, +1 is to account for latency.
3131
+ *
3132
+ * @private
3133
+ */
3134
+ /**
3135
+ * @class TypingIndicator
3136
+ *
3137
+ * @constructor
3138
+ * @private
3139
+ */
3140
+ class TypingIndicator {
3141
+ constructor(getConversation, config, services) {
3142
+ this.configuration = config;
3143
+ this.services = services;
3144
+ this.getConversation = getConversation;
3145
+ this.serviceTypingTimeout = null;
3146
+ this.sentUpdates = new Map();
3147
+ }
3148
+ get typingTimeout() {
3149
+ return this.configuration.typingIndicatorTimeoutOverride
3150
+ || this.serviceTypingTimeout
3151
+ || this.configuration.typingIndicatorTimeoutDefault;
3152
+ }
3153
+ /**
3154
+ * Initialize TypingIndicator controller
3155
+ * Registers for needed message types and sets listeners
3156
+ * @private
3157
+ */
3158
+ initialize() {
3159
+ // this.services.notificationClient.subscribe(NotificationTypes.TYPING_INDICATOR, 'twilsock');
3160
+ this.services.notificationClient.on('message', async (type, message) => {
3161
+ if (type === NotificationTypes.TYPING_INDICATOR) {
3162
+ await this._handleRemoteTyping(message);
3163
+ }
3164
+ });
3165
+ }
3166
+ /**
3167
+ * Remote participants typing events handler
3168
+ */
3169
+ async _handleRemoteTyping(message) {
3170
+ log$1.trace('Got new typing indicator ', message);
3171
+ this.getConversation(message.channel_sid)
3172
+ .then(conversation => {
3173
+ if (!conversation) {
3174
+ return;
3175
+ }
3176
+ conversation.participants.forEach(participant => {
3177
+ if (participant.identity !== message.identity) {
3178
+ return;
3179
+ }
3180
+ const timeout = this.configuration.typingIndicatorTimeoutOverride + 1000 || message.typing_timeout * 1000;
3181
+ participant._startTyping(timeout);
3182
+ });
3183
+ })
3184
+ .catch(err => {
3185
+ log$1.error(err);
3186
+ throw err;
3187
+ });
3188
+ }
3189
+ /**
3190
+ * Send typing event for the given conversation sid
3191
+ * @param {String} conversationSid
3192
+ */
3193
+ send(conversationSid) {
3194
+ const lastUpdate = this.sentUpdates.get(conversationSid);
3195
+ if (lastUpdate && lastUpdate > (Date.now() - this.typingTimeout)) {
3196
+ return Promise.resolve();
3197
+ }
3198
+ this.sentUpdates.set(conversationSid, Date.now());
3199
+ return this._send(conversationSid);
3200
+ }
3201
+ _send(conversationSid) {
3202
+ log$1.trace('Sending typing indicator');
3203
+ const url = this.configuration.links.typing;
3204
+ const headers = {
3205
+ 'Content-Type': 'application/x-www-form-urlencoded'
3206
+ };
3207
+ const body = `ChannelSid=${conversationSid}`;
3208
+ return (this.services.twilsockClient.post(url, headers, body, this.configuration.productId)
3209
+ .then((response) => {
3210
+ if (response.body.hasOwnProperty('typing_timeout')) {
3211
+ this.serviceTypingTimeout = response.body.typing_timeout * 1000;
3212
+ }
3213
+ })
3214
+ .catch((err) => {
3215
+ log$1.error('Failed to send typing indicator:', err);
3216
+ throw err;
3217
+ }));
3218
+ }
3219
+ }
3220
+
3221
+ /**
3222
+ * Push notification for a Conversations client.
3223
+ */
3224
+ class PushNotification {
3225
+ /**
3226
+ * @internal
3227
+ */
3228
+ constructor(data) {
3229
+ this.title = data.title || null;
3230
+ this.body = data.body || null;
3231
+ this.sound = data.sound || null;
3232
+ this.badge = data.badge || null;
3233
+ this.action = data.action || null;
3234
+ this.type = data.type || null;
3235
+ this.data = data.data || {};
3236
+ }
3237
+ }
3238
+
3239
+ var version = "2.0.0-rc.4";
3240
+
3241
+ const trimSlashes = (url) => url.replace(/(^\/+|\/+$)/g, '');
3242
+ const isMutationConflictResponse = (response) => response.status.code === 202;
3243
+ class CommandExecutor {
3244
+ constructor(_serviceUrl, _services, _productId) {
3245
+ this._serviceUrl = _serviceUrl;
3246
+ this._services = _services;
3247
+ this._productId = _productId;
3248
+ }
3249
+ _preProcessUrl(url) {
3250
+ const trimmedUrl = trimSlashes(url);
3251
+ if (/^https?:\/\//.test(url)) {
3252
+ return trimmedUrl;
3253
+ }
3254
+ return `${trimSlashes(this._serviceUrl)}/${trimmedUrl}`;
3255
+ }
3256
+ async _makeRequest(method, url, requestBody, headers) {
3257
+ const preProcessedUrl = this._preProcessUrl(url);
3258
+ const finalHeaders = Object.assign({ 'Content-Type': 'application/json; charset=utf-8' }, (headers || {}));
3259
+ let response;
3260
+ switch (method) {
3261
+ case 'get':
3262
+ let getUrl = preProcessedUrl;
3263
+ if (requestBody) {
3264
+ getUrl +=
3265
+ '?' +
3266
+ Object.entries(requestBody)
3267
+ .map((entry) => entry.map(encodeURIComponent).join('='))
3268
+ .join('&');
3269
+ }
3270
+ response = await this._services.transport.get(getUrl, finalHeaders, this._productId);
3271
+ break;
3272
+ case 'post':
3273
+ response = await this._services.transport.post(preProcessedUrl, finalHeaders, JSON.stringify(requestBody), this._productId);
3274
+ break;
3275
+ case 'delete':
3276
+ response = await this._services.transport.delete(preProcessedUrl, finalHeaders, null, this._productId);
3277
+ break;
3278
+ }
3279
+ if (response.status.code < 200 || response.status.code >= 300) {
3280
+ throw new Error(`Request responded with a non-success code ${response.status.code}`);
3281
+ }
3282
+ return response;
3283
+ }
3284
+ async fetchResource(url, requestBody) {
3285
+ const maxAttemptsCount = 6;
3286
+ let result;
3287
+ try {
3288
+ result = await new operationRetrier.AsyncRetrier({ min: 50, max: 1600, maxAttemptsCount })
3289
+ .run(() => this._makeRequest('get', url, requestBody));
3290
+ }
3291
+ catch (_a) {
3292
+ throw new Error(`Fetch resource from "${url}" failed.`);
3293
+ }
3294
+ return result.body;
3295
+ }
3296
+ async mutateResource(method, url, requestBody) {
3297
+ const result = await this._makeRequest(method, url, requestBody, {
3298
+ 'X-Twilio-Mutation-Id': uuid.v4()
3299
+ });
3300
+ if (isMutationConflictResponse(result)) {
3301
+ return await this.fetchResource(result.body.resource_url);
3302
+ }
3303
+ return result.body;
3304
+ }
3305
+ }
3306
+
3307
+ var Client_1;
3308
+ const log = Logger.scope('Client');
3309
+ const SDK_VERSION = version;
3310
+ class ClientServices {
3311
+ }
3312
+ /**
3313
+ * A client is the starting point to the Twilio Conversations functionality.
3314
+ */
3315
+ exports.Client = Client_1 = class Client extends replayEventEmitter.ReplayEventEmitter {
3316
+ /**
3317
+ * Returned Conversations instance is not yet fully initialized. Calling any operations will block until it is.
3318
+ * Use connection events to monitor when client becomes fully available (connectionStateChanged with state
3319
+ * 'connected') or not available (connectionStateChange with state 'denied', event tokenExpired, event connectionError).
3320
+ *
3321
+ * @param fpaToken Access token
3322
+ * @param options Options to customize the Client
3323
+ * @returns A not yet fully-initialized client.
3324
+ */
3325
+ constructor(fpaToken, options = {}) {
3326
+ var _a, _b, _c, _d, _e;
3327
+ super();
3328
+ /**
3329
+ * Client connection state.
3330
+ */
3331
+ this.connectionState = 'unknown';
3332
+ this.conversationsPromise = null;
3333
+ this._ensureReady = null;
3334
+ this._resolveEnsureReady = null;
3335
+ this._rejectEnsureReady = null;
3336
+ /**
3337
+ * Current version of the Conversations client.
3338
+ */
3339
+ this.version = SDK_VERSION;
3340
+ this.parsePushNotification = Client_1.parsePushNotification;
3341
+ this.fpaToken = fpaToken;
3342
+ this.options = options;
3343
+ if (!this.options.disableDeepClone) {
3344
+ let options = Object.assign(Object.assign({}, this.options), { transport: undefined, twilsockClient: undefined });
3345
+ options = deepClone(options);
3346
+ options.transport = this.options.transport;
3347
+ options.twilsockClient = this.options.twilsockClient;
3348
+ this.options = options;
3349
+ }
3350
+ this.options.logLevel = (_a = this.options.logLevel) !== null && _a !== void 0 ? _a : 'silent';
3351
+ log.setLevel(this.options.logLevel);
3352
+ const productId = this.options.productId = 'ip_messaging';
3353
+ // Filling ClientMetadata
3354
+ this.options.clientMetadata = this.options.clientMetadata || {};
3355
+ if (!this.options.clientMetadata.hasOwnProperty('type')) {
3356
+ this.options.clientMetadata.type = 'conversations';
3357
+ }
3358
+ if (!this.options.clientMetadata.hasOwnProperty('sdk')) {
3359
+ this.options.clientMetadata.sdk = 'JS';
3360
+ this.options.clientMetadata.sdkv = SDK_VERSION;
3361
+ }
3362
+ // Enable session local storage for Sync
3363
+ this.options.Sync = this.options.Sync || {};
3364
+ if (typeof this.options.Sync.enableSessionStorage === 'undefined') {
3365
+ this.options.Sync.enableSessionStorage = true;
3366
+ }
3367
+ if (this.options.region) {
3368
+ this.options.Sync.region = this.options.region;
3369
+ }
3370
+ if (!fpaToken) {
3371
+ throw new Error('A valid Twilio token should be provided');
3372
+ }
3373
+ this.services = new ClientServices();
3374
+ this._myself = new User('', '', null, this.services);
3375
+ const startTwilsock = !this.options.twilsockClient;
3376
+ // Create default init registrations if none were provided.
3377
+ // Otherwise, the outside party have to list all the init registrations they
3378
+ // need.
3379
+ // Init registrations passed to the Conversations client will be passed down
3380
+ // to the Sync client as well.
3381
+ if (!this.options.initRegistrations) {
3382
+ const initRegistration = new twilsock.InitRegistration(productId);
3383
+ Client_1.populateInitRegistrations(initRegistration);
3384
+ this.options.initRegistrations = [initRegistration];
3385
+ }
3386
+ this.services.twilsockClient = (this.options.twilsockClient = (_b = this.options.twilsockClient) !== null && _b !== void 0 ? _b : new twilsock.TwilsockClient(fpaToken, productId, this.options));
3387
+ this.services.twilsockClient.on('tokenAboutToExpire', ttl => this.emit('tokenAboutToExpire', ttl));
3388
+ this.services.twilsockClient.on('tokenExpired', () => this.emit('tokenExpired'));
3389
+ this.services.twilsockClient.on('connectionError', (error) => this.emit('connectionError', error));
3390
+ this.services.twilsockClient.on('stateChanged', (state) => {
3391
+ log.debug(`Handling stateChanged for ConversationsClient: new state ${state}`);
3392
+ if (state !== this.connectionState) {
3393
+ this.connectionState = state;
3394
+ this.emit('connectionStateChanged', this.connectionState);
3395
+ }
3396
+ });
3397
+ this.services.transport = (this.options.transport = ((_c = this.options.transport) !== null && _c !== void 0 ? _c : this.options.twilsockClient));
3398
+ this.services.notificationClient = (this.options.notificationsClient = (_d = this.options.notificationsClient) !== null && _d !== void 0 ? _d : new notifications.Notifications(fpaToken, this.options));
3399
+ this.services.syncClient = (this.options.syncClient = (_e = this.options.syncClient) !== null && _e !== void 0 ? _e : new twilioSync.SyncClient(fpaToken, this.options));
3400
+ const configurationOptions = options.Chat || options.IPMessaging || options || {};
3401
+ const region = configurationOptions.region || options.region;
3402
+ const baseUrl = configurationOptions.apiUri
3403
+ || configurationOptions.typingUri
3404
+ || `https://aim.${region || 'us1'}.twilio.com`;
3405
+ this.services.commandExecutor = new CommandExecutor(baseUrl, { transport: this.options.transport }, productId);
3406
+ const emitFailed = (err) => {
3407
+ this._rejectEnsureReady(err);
3408
+ this.emit('stateChanged', 'failed');
3409
+ };
3410
+ this.services.twilsockClient.once('connectionError', emitFailed);
3411
+ this.services.twilsockClient.once('disconnected', emitFailed);
3412
+ // ConversationsClient will be able to initialize only after twilsock is connected
3413
+ this.services.twilsockClient.once('connected', async () => {
3414
+ log.debug(`ConversationsClient started INITIALIZING`);
3415
+ this.services.twilsockClient.off('connectionError', emitFailed);
3416
+ this.services.twilsockClient.off('disconnected', emitFailed);
3417
+ try {
3418
+ const startupEvent = 'conversations.client.startup';
3419
+ this.services.twilsockClient.addPartialTelemetryEvent(new twilsock.TelemetryEventDescription(startupEvent, 'Conversations client startup', new Date()), startupEvent, twilsock.TelemetryPoint.Start);
3420
+ await this._initialize();
3421
+ this.services.twilsockClient.addPartialTelemetryEvent(new twilsock.TelemetryEventDescription('', '', new Date()), startupEvent, twilsock.TelemetryPoint.End);
3422
+ }
3423
+ catch (err) {
3424
+ // Fail ChatClient if initialization is incomplete
3425
+ this._rejectEnsureReady(err);
3426
+ this.emit('stateChanged', 'failed');
3427
+ }
3428
+ });
3429
+ this._ensureReady = new Promise((resolve, reject) => {
3430
+ this._resolveEnsureReady = resolve;
3431
+ this._rejectEnsureReady = reject;
3432
+ }).catch((err) => { }); // @todo How to process unhandled rejection here?
3433
+ if (startTwilsock) {
3434
+ this.services.twilsockClient.connect();
3435
+ }
3436
+ }
3437
+ static populateInitRegistrations(reg) {
3438
+ reg.populateInitRegistrations([NotificationTypes.TYPING_INDICATOR]);
3439
+ twilioSync.SyncClient.populateInitRegistrations(reg);
3440
+ }
3441
+ /**
3442
+ * @deprecated Call constructor directly.
3443
+ *
3444
+ * Factory method to create a Conversations client instance.
3445
+ *
3446
+ * The factory method will automatically trigger connection.
3447
+ * Do not use it if you need finer-grained control.
3448
+ *
3449
+ * Since this method returns an already-initialized client, some of the events
3450
+ * will be lost because they happen *before* the initialization. It is
3451
+ * recommended that `client.onWithReplay` is used as opposed to `client.on`
3452
+ * for subscribing to client events. The `client.onWithReplay` will re-emit
3453
+ * the most recent value for a given event if it emitted before the
3454
+ * subscription.
3455
+ *
3456
+ * @param token Access token.
3457
+ * @param options Options to customize the client.
3458
+ * @returns Returns a fully initialized client.
3459
+ */
3460
+ static async create(token, options) {
3461
+ // The logic is as follows:
3462
+ // - If twilsock is not passed in, then the ConversationsClient constructor will call twilsock.connect() by itself
3463
+ // and we do not need to do it here.
3464
+ // - If twilsock was passed in from the outside, but customer called ConversationsClient.create() then they are
3465
+ // using an obsolete workflow and the startup sequence will never complete.
3466
+ if (options === null || options === void 0 ? void 0 : options.twilsockClient) {
3467
+ throw new Error('Obsolete usage of ConversationsClient.create() ' +
3468
+ 'factory method: if you pass twilsock from the outside then you must ' +
3469
+ 'use ConversationsClient constructor and be prepared to work with ' +
3470
+ 'uninitialized client.');
3471
+ }
3472
+ const client = new Client_1(token, options);
3473
+ await client._ensureReady;
3474
+ return client;
3475
+ }
3476
+ /**
3477
+ * Information of the logged-in user. Before client initialization, returns an
3478
+ * uninitialized user. Will trigger a {@link Client.userUpdated} event after
3479
+ * initialization.
3480
+ */
3481
+ get user() { return this._myself; }
3482
+ /**
3483
+ * Client reachability state. Throws if accessed before the client
3484
+ * initialization was completed.
3485
+ */
3486
+ get reachabilityEnabled() {
3487
+ if (!this.configuration) {
3488
+ throw new Error('Reachability information could not yet be accessed as the client ' +
3489
+ "has not yet been initialized. Subscribe to the 'stateChanged' event " +
3490
+ 'to properly react to the client initialization.');
3491
+ }
3492
+ return this.configuration.reachabilityEnabled;
3493
+ }
3494
+ get token() { return this.fpaToken; }
3495
+ _subscribeToPushNotifications(channelType) {
3496
+ [NotificationTypes.NEW_MESSAGE,
3497
+ NotificationTypes.ADDED_TO_CONVERSATION,
3498
+ NotificationTypes.REMOVED_FROM_CONVERSATION,
3499
+ NotificationTypes.TYPING_INDICATOR,
3500
+ NotificationTypes.CONSUMPTION_UPDATE]
3501
+ .forEach(messageType => {
3502
+ this.services.notificationClient.subscribe(channelType, messageType);
3503
+ });
3504
+ }
3505
+ _unsubscribeFromPushNotifications(channelType) {
3506
+ [NotificationTypes.NEW_MESSAGE,
3507
+ NotificationTypes.ADDED_TO_CONVERSATION,
3508
+ NotificationTypes.REMOVED_FROM_CONVERSATION,
3509
+ NotificationTypes.TYPING_INDICATOR,
3510
+ NotificationTypes.CONSUMPTION_UPDATE]
3511
+ .forEach(messageType => {
3512
+ this.services.notificationClient.unsubscribe(channelType, messageType);
3513
+ });
3514
+ }
3515
+ async _initialize() {
3516
+ const configurationResponse = await this.services.commandExecutor.fetchResource('Client/v2/Configuration');
3517
+ this.configuration = new Configuration(this.options, configurationResponse, log);
3518
+ this._myself._resolveInitialization(this.configuration, this.configuration.userIdentity, this.configuration.userInfo, true);
3519
+ this.services.typingIndicator = new TypingIndicator(this.getConversationBySid.bind(this), this.configuration, this.services);
3520
+ this.services.network = new Network(this.configuration, this.services);
3521
+ this.services.users = new Users(this._myself, this.configuration, this.services);
3522
+ this.services.users.on('userSubscribed', this.emit.bind(this, 'userSubscribed'));
3523
+ this.services.users.on('userUpdated', (args) => this.emit('userUpdated', args));
3524
+ this.services.users.on('userUnsubscribed', this.emit.bind(this, 'userUnsubscribed'));
3525
+ this.conversations = new Conversations(this.configuration, this.services);
3526
+ this.conversations.on('conversationAdded', this.emit.bind(this, 'conversationAdded'));
3527
+ this.conversations.on('conversationRemoved', this.emit.bind(this, 'conversationRemoved'));
3528
+ this.conversations.on('conversationJoined', this.emit.bind(this, 'conversationJoined'));
3529
+ this.conversations.on('conversationLeft', this.emit.bind(this, 'conversationLeft'));
3530
+ this.conversations.on('conversationUpdated', (args) => this.emit('conversationUpdated', args));
3531
+ this.conversations.on('participantJoined', this.emit.bind(this, 'participantJoined'));
3532
+ this.conversations.on('participantLeft', this.emit.bind(this, 'participantLeft'));
3533
+ this.conversations.on('participantUpdated', (args) => this.emit('participantUpdated', args));
3534
+ this.conversations.on('messageAdded', this.emit.bind(this, 'messageAdded'));
3535
+ this.conversations.on('messageUpdated', (args) => this.emit('messageUpdated', args));
3536
+ this.conversations.on('messageRemoved', this.emit.bind(this, 'messageRemoved'));
3537
+ this.conversations.on('typingStarted', this.emit.bind(this, 'typingStarted'));
3538
+ this.conversations.on('typingEnded', this.emit.bind(this, 'typingEnded'));
3539
+ this.conversationsPromise = this.conversations.fetchConversations()
3540
+ .then(() => this.conversations)
3541
+ .catch((error) => {
3542
+ throw error;
3543
+ });
3544
+ await this.services.users.myself._ensureFetched();
3545
+ Client_1.supportedPushChannels.forEach(channelType => this._subscribeToPushNotifications(channelType));
3546
+ this.services.typingIndicator.initialize();
3547
+ this.services.mcsClient = new mcsClient.McsClient(this.fpaToken, this.configuration.links.mediaService, this.configuration.links.mediaSetService, Object.assign(Object.assign({}, this.options), { transport: null }));
3548
+ this._resolveEnsureReady();
3549
+ this.emit('stateChanged', 'initialized');
3550
+ }
3551
+ /**
3552
+ * Gracefully shut down the client.
3553
+ */
3554
+ async shutdown() {
3555
+ await this._ensureReady;
3556
+ await this.services.twilsockClient.disconnect();
3557
+ }
3558
+ /**
3559
+ * Update the token used by the client and re-register with the Conversations services.
3560
+ * @param token New access token.
3561
+ */
3562
+ async updateToken(token) {
3563
+ await this._ensureReady;
3564
+ log.info('updateToken');
3565
+ if (this.fpaToken === token) {
3566
+ return this;
3567
+ }
3568
+ await this.services.twilsockClient.updateToken(token);
3569
+ await this.services.notificationClient.updateToken(token);
3570
+ await this.services.mcsClient.updateToken(token);
3571
+ this.fpaToken = token;
3572
+ return this;
3573
+ }
3574
+ /**
3575
+ * Get a known conversation by its SID.
3576
+ * @param conversationSid Conversation sid
3577
+ */
3578
+ async getConversationBySid(conversationSid) {
3579
+ await this._ensureReady;
3580
+ await this.conversations.myConversationsRead.promise;
3581
+ let conversation = await this.conversations.getConversation(conversationSid);
3582
+ if (!conversation) {
3583
+ conversation = await this.conversations.peekConversation(conversationSid);
3584
+ }
3585
+ if (!conversation) {
3586
+ throw new Error(`Conversation with SID ${conversationSid} is not found.`);
3587
+ }
3588
+ return conversation;
3589
+ }
3590
+ /**
3591
+ * Get a known conversation by its unique identifier name.
3592
+ * @param uniqueName The unique identifier name of the conversation.
3593
+ */
3594
+ async getConversationByUniqueName(uniqueName) {
3595
+ await this._ensureReady;
3596
+ await this.conversations.myConversationsRead.promise;
3597
+ const conversation = await this.conversations.getConversationByUniqueName(uniqueName);
3598
+ if (!conversation) {
3599
+ throw new Error(`Conversation with unique name ${uniqueName} is not found.`);
3600
+ }
3601
+ return conversation;
3602
+ }
3603
+ /**
3604
+ * Get the current list of all the subscribed conversations.
3605
+ */
3606
+ async getSubscribedConversations(args) {
3607
+ await this._ensureReady;
3608
+ return this.conversationsPromise.then(conversations => conversations.getConversations(args));
3609
+ }
3610
+ /**
3611
+ * Create a conversation on the server and subscribe to its events.
3612
+ * The default is a conversation with an empty friendly name.
3613
+ * @param options Options for the conversation.
3614
+ */
3615
+ async createConversation(options) {
3616
+ await this._ensureReady;
3617
+ options = options || {};
3618
+ return this.conversationsPromise.then(conversationsEntity => conversationsEntity.addConversation(options));
3619
+ }
3620
+ /**
3621
+ * Register for push notifications.
3622
+ * @param channelType Channel type.
3623
+ * @param registrationId Push notification ID provided by the FCM/APNS service on the platform.
3624
+ */
3625
+ async setPushRegistrationId(channelType, registrationId) {
3626
+ await this._ensureReady;
3627
+ this._subscribeToPushNotifications(channelType);
3628
+ this.services.notificationClient.setPushRegistrationId(channelType, registrationId);
3629
+ await this.services.notificationClient.commitChanges(); // Committing before this point is useless because we have no push id
3630
+ }
3631
+ /**
3632
+ * Unregister from push notifications.
3633
+ * @param channelType Channel type.
3634
+ * @deprecated Use removePushRegistrations() instead.
3635
+ */
3636
+ async unsetPushRegistrationId(channelType) {
3637
+ await this._ensureReady;
3638
+ this._unsubscribeFromPushNotifications(channelType);
3639
+ await this.services.notificationClient.commitChanges();
3640
+ }
3641
+ /**
3642
+ * Clear existing registrations directly using provided device token.
3643
+ * This is useful to ensure stopped subscriptions without resubscribing.
3644
+ *
3645
+ * This function goes completely beside the state machine and removes all registrations.
3646
+ * Use with caution: if it races with current state machine operations, madness will ensue.
3647
+ *
3648
+ * @param channelType Channel type.
3649
+ * @param registrationId Push notification ID provided by the FCM/APNS service on the platform.
3650
+ */
3651
+ async removePushRegistrations(channelType, registrationId) {
3652
+ // do not await this._ensureReady() here - it could be called at any moment
3653
+ await this.services.notificationClient.removeRegistrations(channelType, registrationId);
3654
+ }
3655
+ static parsePushNotificationChatData(data) {
3656
+ const result = {};
3657
+ for (let key in Client_1.supportedPushDataFields) {
3658
+ if (typeof data[key] === 'undefined' || data[key] === null) {
3659
+ continue;
3660
+ }
3661
+ if (key !== 'message_index') {
3662
+ result[Client_1.supportedPushDataFields[key]] = data[key];
3663
+ continue;
3664
+ }
3665
+ if (parseToNumber(data[key]) !== null) {
3666
+ result[Client_1.supportedPushDataFields[key]] = Number(data[key]);
3667
+ }
3668
+ }
3669
+ return result;
3670
+ }
3671
+ /**
3672
+ * Static method for push notification payload parsing. Returns parsed push as a {@link PushNotification} object.
3673
+ * @param notificationPayload Push notification payload.
3674
+ */
3675
+ static parsePushNotification(notificationPayload) {
3676
+ log.debug('parsePushNotification, notificationPayload=', notificationPayload);
3677
+ // APNS specifics
3678
+ if (typeof notificationPayload.aps !== 'undefined') {
3679
+ if (!notificationPayload.twi_message_type) {
3680
+ throw new Error('Provided push notification payload does not contain Programmable Chat push notification type');
3681
+ }
3682
+ let data = Client_1.parsePushNotificationChatData(notificationPayload);
3683
+ let apsPayload = notificationPayload.aps;
3684
+ let body = null;
3685
+ let title = null;
3686
+ if (typeof apsPayload.alert === 'string') {
3687
+ body = apsPayload.alert || null;
3688
+ }
3689
+ else {
3690
+ body = apsPayload.alert.body || null;
3691
+ title = apsPayload.alert.title || null;
3692
+ }
3693
+ return new PushNotification({
3694
+ title: title,
3695
+ body: body,
3696
+ sound: apsPayload.sound || null,
3697
+ badge: apsPayload.badge || null,
3698
+ action: apsPayload.category || null,
3699
+ type: notificationPayload.twi_message_type,
3700
+ data: data
3701
+ });
3702
+ }
3703
+ // FCM specifics
3704
+ if (typeof notificationPayload.data !== 'undefined') {
3705
+ let dataPayload = notificationPayload.data;
3706
+ if (!dataPayload.twi_message_type) {
3707
+ throw new Error('Provided push notification payload does not contain Programmable Chat push notification type');
3708
+ }
3709
+ let data = Client_1.parsePushNotificationChatData(notificationPayload.data);
3710
+ return new PushNotification({
3711
+ title: dataPayload.twi_title || null,
3712
+ body: dataPayload.twi_body || null,
3713
+ sound: dataPayload.twi_sound || null,
3714
+ badge: null,
3715
+ action: dataPayload.twi_action || null,
3716
+ type: dataPayload.twi_message_type,
3717
+ data: data
3718
+ });
3719
+ }
3720
+ throw new Error('Provided push notification payload is not Programmable Chat notification');
3721
+ }
3722
+ /**
3723
+ * Handle push notification payload parsing and emit the {@link Client.pushNotification} event on this {@link Client} instance.
3724
+ * @param notificationPayload Push notification payload
3725
+ */
3726
+ async handlePushNotification(notificationPayload) {
3727
+ await this._ensureReady;
3728
+ log.debug('handlePushNotification, notificationPayload=', notificationPayload);
3729
+ this.emit('pushNotification', Client_1.parsePushNotification(notificationPayload));
3730
+ }
3731
+ /**
3732
+ * Gets a user with the given identity. If it's in the subscribed list, then return the user object from it;
3733
+ * if not, then subscribe and add user to the subscribed list.
3734
+ * @param identity Identity of the user.
3735
+ * @returns A fully initialized user.
3736
+ */
3737
+ async getUser(identity) {
3738
+ await this._ensureReady;
3739
+ return this.services.users.getUser(identity);
3740
+ }
3741
+ /**
3742
+ * Get a list of subscribed user objects.
3743
+ */
3744
+ async getSubscribedUsers() {
3745
+ await this._ensureReady;
3746
+ return this.services.users.getSubscribedUsers();
3747
+ }
3748
+ };
3749
+ /**
3750
+ * Current version of the Conversations client.
3751
+ */
3752
+ exports.Client.version = SDK_VERSION;
3753
+ exports.Client.supportedPushChannels = ['fcm', 'apn'];
3754
+ exports.Client.supportedPushDataFields = {
3755
+ 'conversation_sid': 'conversationSid',
3756
+ 'message_sid': 'messageSid',
3757
+ 'message_index': 'messageIndex'
3758
+ };
3759
+ /**
3760
+ * Fired when a conversation becomes visible to the client. The event is also triggered when the client creates a new conversation.
3761
+ * Fired for all conversations client has joined.
3762
+ *
3763
+ * Parameters:
3764
+ * 1. {@link Conversation} `conversation` - the conversation in question
3765
+ * @event
3766
+ */
3767
+ exports.Client.conversationAdded = 'conversationAdded';
3768
+ /**
3769
+ * Fired when the client joins a conversation.
3770
+ *
3771
+ * Parameters:
3772
+ * 1. {@link Conversation} `conversation` - the conversation in question
3773
+ * @event
3774
+ */
3775
+ exports.Client.conversationJoined = 'conversationJoined';
3776
+ /**
3777
+ * Fired when the client leaves a conversation.
3778
+ *
3779
+ * Parameters:
3780
+ * 1. {@link Conversation} `conversation` - the conversation in question
3781
+ * @event
3782
+ */
3783
+ exports.Client.conversationLeft = 'conversationLeft';
3784
+ /**
3785
+ * Fired when a conversation is no longer visible to the client.
3786
+ *
3787
+ * Parameters:
3788
+ * 1. {@link Conversation} `conversation` - the conversation in question
3789
+ * @event
3790
+ */
3791
+ exports.Client.conversationRemoved = 'conversationRemoved';
3792
+ /**
3793
+ * Fired when the attributes or the metadata of a conversation have been updated.
3794
+ * During conversation's creation and initialization, this event might be fired multiple times
3795
+ * for same joined or created conversation as new data is arriving from different sources.
3796
+ *
3797
+ * Parameters:
3798
+ * 1. object `data` - info object provided with the event. It has the following properties:
3799
+ * * {@link Conversation} `conversation` - the conversation in question
3800
+ * * {@link ConversationUpdateReason}[] `updateReasons` - array of reasons for the update
3801
+ * @event
3802
+ */
3803
+ exports.Client.conversationUpdated = 'conversationUpdated';
3804
+ /**
3805
+ * Fired when a participant has joined a conversation.
3806
+ *
3807
+ * Parameters:
3808
+ * 1. {@link Participant} `participant` - the participant in question
3809
+ * @event
3810
+ */
3811
+ exports.Client.participantJoined = 'participantJoined';
3812
+ /**
3813
+ * Fired when a participant has left a conversation.
3814
+ *
3815
+ * Parameters:
3816
+ * 1. {@link Participant} `participant` - the participant in question
3817
+ * @event
3818
+ */
3819
+ exports.Client.participantLeft = 'participantLeft';
3820
+ /**
3821
+ * Fired when a participant's fields have been updated.
3822
+ *
3823
+ * Parameters:
3824
+ * 1. object `data` - info object provided with the event. It has the following properties:
3825
+ * * {@link Participant} `participant` - the participant in question
3826
+ * * {@link ParticipantUpdateReason}[] `updateReasons` - array of reasons for the update
3827
+ * @event
3828
+ */
3829
+ exports.Client.participantUpdated = 'participantUpdated';
3830
+ /**
3831
+ * Fired when a new message has been added to the conversation on the server.
3832
+ *
3833
+ * Parameters:
3834
+ * 1. {@link Message} `message` - the message in question
3835
+ * @event
3836
+ */
3837
+ exports.Client.messageAdded = 'messageAdded';
3838
+ /**
3839
+ * Fired when a message is removed from the message list of a conversation.
3840
+ *
3841
+ * Parameters:
3842
+ * 1. {@link Message} `message` - the message in question
3843
+ * @event
3844
+ */
3845
+ exports.Client.messageRemoved = 'messageRemoved';
3846
+ /**
3847
+ * Fired when the fields of an existing message are updated with new values.
3848
+ *
3849
+ * Parameters:
3850
+ * 1. object `data` - info object provided with the event. It has the following properties:
3851
+ * * {@link Message} `message` - the message in question
3852
+ * * {@link MessageUpdateReason}[] `updateReasons` - array of reasons for the update
3853
+ * @event
3854
+ */
3855
+ exports.Client.messageUpdated = 'messageUpdated';
3856
+ /**
3857
+ * Fired when the token is about to expire and needs to be updated.
3858
+ * * Parameters:
3859
+ * 1. number `message` - token's time to live
3860
+ * @event
3861
+ */
3862
+ exports.Client.tokenAboutToExpire = 'tokenAboutToExpire';
3863
+ /**
3864
+ * Fired when the token has expired.
3865
+ * @event
3866
+ */
3867
+ exports.Client.tokenExpired = 'tokenExpired';
3868
+ /**
3869
+ * Fired when a participant has stopped typing.
3870
+ *
3871
+ * Parameters:
3872
+ * 1. {@link Participant} `participant` - the participant in question
3873
+ * @event
3874
+ */
3875
+ exports.Client.typingEnded = 'typingEnded';
3876
+ /**
3877
+ * Fired when a participant has started typing.
3878
+ *
3879
+ * Parameters:
3880
+ * 1. {@link Participant} `participant` - the participant in question
3881
+ * @event
3882
+ */
3883
+ exports.Client.typingStarted = 'typingStarted';
3884
+ /**
3885
+ * Fired when the client has received (and parsed) a push notification via one of the push channels (apn or fcm).
3886
+ *
3887
+ * Parameters:
3888
+ * 1. {@link PushNotification} `pushNotification` - the push notification in question
3889
+ * @event
3890
+ */
3891
+ exports.Client.pushNotification = 'pushNotification';
3892
+ /**
3893
+ * Fired when the client has subscribed to a user.
3894
+ *
3895
+ * Parameters:
3896
+ * 1. {@link User} `user` - the user in question
3897
+ * @event
3898
+ */
3899
+ exports.Client.userSubscribed = 'userSubscribed';
3900
+ /**
3901
+ * Fired when the client has unsubscribed from a user.
3902
+ *
3903
+ * Parameters:
3904
+ * 1. {@link User} `user` - the user in question
3905
+ * @event
3906
+ */
3907
+ exports.Client.userUnsubscribed = 'userUnsubscribed';
3908
+ /**
3909
+ * Fired when the properties or the reachability status of a user have been updated.
3910
+ *
3911
+ * Parameters:
3912
+ * 1. object `data` - info object provided with the event. It has the following properties:
3913
+ * * {@link User} `user` - the user in question
3914
+ * * {@link UserUpdateReason}[] `updateReasons` - array of reasons for the update
3915
+ * @event
3916
+ */
3917
+ exports.Client.userUpdated = 'userUpdated';
3918
+ /**
3919
+ * Fired when the state of the client has been changed.
3920
+ *
3921
+ * Parameters:
3922
+ * 1. {@link State} `state` - the new client state
3923
+ * @event
3924
+ */
3925
+ exports.Client.stateChanged = 'stateChanged';
3926
+ /**
3927
+ * Fired when the connection state of the client has been changed.
3928
+ *
3929
+ * Paremeters:
3930
+ * 1. {@link ConnectionState} `state` - the new connection state
3931
+ * @event
3932
+ */
3933
+ exports.Client.connectionStateChanged = 'connectionStateChanged';
3934
+ /**
3935
+ * Fired when the connection is interrupted for an unexpected reason.
3936
+ *
3937
+ * Parameters:
3938
+ * 1. object `data` - info object provided with the event. It has the following properties:
3939
+ * * boolean `terminal` - Twilsock will stop connection attempts if true
3940
+ * * string `message` - the error message of the root cause
3941
+ * * number? `httpStatusCode` - http status code if available
3942
+ * * number? `errorCode` - Twilio public error code if available
3943
+ * @event
3944
+ */
3945
+ exports.Client.connectionError = 'connectionError';
3946
+ __decorate([
3947
+ declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString),
3948
+ __metadata("design:type", Function),
3949
+ __metadata("design:paramtypes", [String]),
3950
+ __metadata("design:returntype", Promise)
3951
+ ], exports.Client.prototype, "updateToken", null);
3952
+ __decorate([
3953
+ declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString),
3954
+ __metadata("design:type", Function),
3955
+ __metadata("design:paramtypes", [String]),
3956
+ __metadata("design:returntype", Promise)
3957
+ ], exports.Client.prototype, "getConversationBySid", null);
3958
+ __decorate([
3959
+ declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString),
3960
+ __metadata("design:type", Function),
3961
+ __metadata("design:paramtypes", [String]),
3962
+ __metadata("design:returntype", Promise)
3963
+ ], exports.Client.prototype, "getConversationByUniqueName", null);
3964
+ __decorate([
3965
+ declarativeTypeValidator.validateTypesAsync([
3966
+ 'undefined',
3967
+ declarativeTypeValidator.objectSchema('conversation options', {
3968
+ friendlyName: ['string', 'undefined'],
3969
+ isPrivate: ['boolean', 'undefined'],
3970
+ uniqueName: ['string', 'undefined']
3971
+ })
3972
+ ]),
3973
+ __metadata("design:type", Function),
3974
+ __metadata("design:paramtypes", [Object]),
3975
+ __metadata("design:returntype", Promise)
3976
+ ], exports.Client.prototype, "createConversation", null);
3977
+ __decorate([
3978
+ declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.literal('fcm', 'apn'), 'string'),
3979
+ __metadata("design:type", Function),
3980
+ __metadata("design:paramtypes", [String, String]),
3981
+ __metadata("design:returntype", Promise)
3982
+ ], exports.Client.prototype, "setPushRegistrationId", null);
3983
+ __decorate([
3984
+ declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.literal('fcm', 'apn')),
3985
+ __metadata("design:type", Function),
3986
+ __metadata("design:paramtypes", [String]),
3987
+ __metadata("design:returntype", Promise)
3988
+ ], exports.Client.prototype, "unsetPushRegistrationId", null);
3989
+ __decorate([
3990
+ declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.literal('fcm', 'apn'), declarativeTypeValidator.nonEmptyString),
3991
+ __metadata("design:type", Function),
3992
+ __metadata("design:paramtypes", [String, String]),
3993
+ __metadata("design:returntype", Promise)
3994
+ ], exports.Client.prototype, "removePushRegistrations", null);
3995
+ __decorate([
3996
+ declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.pureObject),
3997
+ __metadata("design:type", Function),
3998
+ __metadata("design:paramtypes", [Object]),
3999
+ __metadata("design:returntype", Promise)
4000
+ ], exports.Client.prototype, "handlePushNotification", null);
4001
+ __decorate([
4002
+ declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString),
4003
+ __metadata("design:type", Function),
4004
+ __metadata("design:paramtypes", [String]),
4005
+ __metadata("design:returntype", Promise)
4006
+ ], exports.Client.prototype, "getUser", null);
4007
+ __decorate([
4008
+ declarativeTypeValidator.validateTypesAsync('string', ['undefined', declarativeTypeValidator.pureObject]),
4009
+ __metadata("design:type", Function),
4010
+ __metadata("design:paramtypes", [String, Object]),
4011
+ __metadata("design:returntype", Promise)
4012
+ ], exports.Client, "create", null);
4013
+ __decorate([
4014
+ declarativeTypeValidator.validateTypes(declarativeTypeValidator.pureObject),
4015
+ __metadata("design:type", Function),
4016
+ __metadata("design:paramtypes", [Object]),
4017
+ __metadata("design:returntype", PushNotification)
4018
+ ], exports.Client, "parsePushNotification", null);
4019
+ exports.Client = Client_1 = __decorate([
4020
+ declarativeTypeValidator.validateConstructorTypes(declarativeTypeValidator.nonEmptyString, [
4021
+ declarativeTypeValidator.pureObject,
4022
+ 'undefined'
4023
+ ]),
4024
+ __metadata("design:paramtypes", [String, Object])
4025
+ ], exports.Client);
4026
+
4027
+ exports.AggregatedDeliveryReceipt = AggregatedDeliveryReceipt;
4028
+ exports.Conversation = Conversation;
4029
+ exports.DetailedDeliveryReceipt = DetailedDeliveryReceipt;
4030
+ exports.Media = Media;
4031
+ exports.Message = Message;
4032
+ exports.MessageBuilder = MessageBuilder;
4033
+ exports.Participant = Participant;
4034
+ exports.PushNotification = PushNotification;
4035
+ exports.RestPaginator = RestPaginator;
4036
+ exports.UnsentMessage = UnsentMessage;
4037
+ exports.User = User;
4038
+ //# sourceMappingURL=react-native.js.map