@livechatta/sdk 0.0.0-stage → 1.0.0

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 (246) hide show
  1. package/CHANGELOG.md +218 -0
  2. package/LICENSE +21 -0
  3. package/README.md +2558 -2
  4. package/bin/chatta.mjs +7 -0
  5. package/bin/lib/cli.d.mts +46 -0
  6. package/bin/lib/cli.mjs +2088 -0
  7. package/dist/cjs/livechatta.cjs.js +7258 -0
  8. package/dist/cjs/livechatta.cjs.js.map +1 -0
  9. package/dist/cjs/livechatta.cjs.min.js +2 -0
  10. package/dist/cjs/livechatta.cjs.min.js.map +1 -0
  11. package/dist/esm/livechatta.esm.js +7077 -0
  12. package/dist/esm/livechatta.esm.js.map +1 -0
  13. package/dist/esm/livechatta.esm.min.js +2 -0
  14. package/dist/esm/livechatta.esm.min.js.map +1 -0
  15. package/dist/platforms/android/LiveChattaClient.kt +367 -0
  16. package/dist/platforms/android/LiveChattaHttpAPI.kt +2630 -0
  17. package/dist/platforms/android/LiveChattaJson.kt +83 -0
  18. package/dist/platforms/android/LiveChattaModels.kt +22805 -0
  19. package/dist/platforms/android/LiveChattaSentFrom.kt +30 -0
  20. package/dist/platforms/android/LiveChattaSocketAPI.kt +2113 -0
  21. package/dist/platforms/android/LiveChattaTyped.kt +239 -0
  22. package/dist/platforms/android/LiveChattaWebView.kt +158 -0
  23. package/dist/platforms/angular/livechatta-bridge.service.d.ts +35 -0
  24. package/dist/platforms/angular/livechatta-bridge.service.js +1 -0
  25. package/dist/platforms/angular/livechatta-bridge.service.js.map +1 -0
  26. package/dist/platforms/angular/livechatta-embed.component.d.ts +46 -0
  27. package/dist/platforms/angular/livechatta-embed.component.js +1 -0
  28. package/dist/platforms/angular/livechatta-embed.component.js.map +1 -0
  29. package/dist/platforms/angular/livechatta.service.d.ts +66 -0
  30. package/dist/platforms/angular/livechatta.service.js +1 -0
  31. package/dist/platforms/angular/livechatta.service.js.map +1 -0
  32. package/dist/platforms/capacitor/CapacitorBridge.d.ts +27 -0
  33. package/dist/platforms/capacitor/CapacitorBridge.js +1 -0
  34. package/dist/platforms/capacitor/CapacitorBridge.js.map +1 -0
  35. package/dist/platforms/capacitor/CapacitorDeepLinks.d.ts +23 -0
  36. package/dist/platforms/capacitor/CapacitorDeepLinks.js +1 -0
  37. package/dist/platforms/capacitor/CapacitorDeepLinks.js.map +1 -0
  38. package/dist/platforms/capacitor/CapacitorPermissions.d.ts +29 -0
  39. package/dist/platforms/capacitor/CapacitorPermissions.js +1 -0
  40. package/dist/platforms/capacitor/CapacitorPermissions.js.map +1 -0
  41. package/dist/platforms/capacitor/CapacitorPush.d.ts +33 -0
  42. package/dist/platforms/capacitor/CapacitorPush.js +1 -0
  43. package/dist/platforms/capacitor/CapacitorPush.js.map +1 -0
  44. package/dist/platforms/capacitor/index.d.ts +24 -0
  45. package/dist/platforms/capacitor/index.js +1 -0
  46. package/dist/platforms/capacitor/index.js.map +1 -0
  47. package/dist/platforms/flutter/livechatta_client.dart +359 -0
  48. package/dist/platforms/flutter/livechatta_http_api.dart +1942 -0
  49. package/dist/platforms/flutter/livechatta_json.dart +57 -0
  50. package/dist/platforms/flutter/livechatta_models.dart +23531 -0
  51. package/dist/platforms/flutter/livechatta_sent_from.dart +35 -0
  52. package/dist/platforms/flutter/livechatta_socket_api.dart +1504 -0
  53. package/dist/platforms/flutter/livechatta_typed.dart +234 -0
  54. package/dist/platforms/flutter/livechatta_webview.dart +190 -0
  55. package/dist/platforms/ios/LiveChattaClient.swift +374 -0
  56. package/dist/platforms/ios/LiveChattaHttpAPI.swift +2431 -0
  57. package/dist/platforms/ios/LiveChattaJSON.swift +84 -0
  58. package/dist/platforms/ios/LiveChattaModels.swift +27050 -0
  59. package/dist/platforms/ios/LiveChattaSentFrom.swift +32 -0
  60. package/dist/platforms/ios/LiveChattaSocketAPI.swift +1446 -0
  61. package/dist/platforms/ios/LiveChattaTyped.swift +268 -0
  62. package/dist/platforms/ios/LiveChattaWebView.swift +191 -0
  63. package/dist/platforms/nuxt/LiveChattaView.d.ts +1 -0
  64. package/dist/platforms/nuxt/LiveChattaView.js +1 -0
  65. package/dist/platforms/nuxt/LiveChattaView.js.map +1 -0
  66. package/dist/platforms/nuxt/useChattaBridge.d.ts +9 -0
  67. package/dist/platforms/nuxt/useChattaBridge.js +1 -0
  68. package/dist/platforms/nuxt/useChattaBridge.js.map +1 -0
  69. package/dist/platforms/nuxt/useLiveChatta.d.ts +63 -0
  70. package/dist/platforms/nuxt/useLiveChatta.js +1 -0
  71. package/dist/platforms/nuxt/useLiveChatta.js.map +1 -0
  72. package/dist/platforms/react/LiveChattaView.d.ts +58 -0
  73. package/dist/platforms/react/LiveChattaView.js +1 -0
  74. package/dist/platforms/react/LiveChattaView.js.map +1 -0
  75. package/dist/platforms/react/useChattaBridge.d.ts +1 -0
  76. package/dist/platforms/react/useChattaBridge.js +1 -0
  77. package/dist/platforms/react/useChattaBridge.js.map +1 -0
  78. package/dist/platforms/react/useChattaDeepLink.d.ts +2 -0
  79. package/dist/platforms/react/useChattaDeepLink.js +1 -0
  80. package/dist/platforms/react/useChattaDeepLink.js.map +1 -0
  81. package/dist/platforms/react/useChattaPermissions.d.ts +9 -0
  82. package/dist/platforms/react/useChattaPermissions.js +1 -0
  83. package/dist/platforms/react/useChattaPermissions.js.map +1 -0
  84. package/dist/platforms/react/useChattaUnread.d.ts +1 -0
  85. package/dist/platforms/react/useChattaUnread.js +1 -0
  86. package/dist/platforms/react/useChattaUnread.js.map +1 -0
  87. package/dist/platforms/react/useLiveChatta.d.ts +29 -0
  88. package/dist/platforms/react/useLiveChatta.js +1 -0
  89. package/dist/platforms/react/useLiveChatta.js.map +1 -0
  90. package/dist/platforms/react-native/LiveChattaView.d.ts +52 -0
  91. package/dist/platforms/react-native/LiveChattaView.js +1 -0
  92. package/dist/platforms/react-native/LiveChattaView.js.map +1 -0
  93. package/dist/platforms/react-native/useChattaBridge.d.ts +12 -0
  94. package/dist/platforms/react-native/useChattaBridge.js +1 -0
  95. package/dist/platforms/react-native/useChattaBridge.js.map +1 -0
  96. package/dist/platforms/react-native/useLiveChatta.d.ts +29 -0
  97. package/dist/platforms/react-native/useLiveChatta.js +1 -0
  98. package/dist/platforms/react-native/useLiveChatta.js.map +1 -0
  99. package/dist/platforms/svelte/LiveChattaEmbed.d.ts +54 -0
  100. package/dist/platforms/svelte/LiveChattaEmbed.js +1 -0
  101. package/dist/platforms/svelte/LiveChattaEmbed.js.map +1 -0
  102. package/dist/platforms/svelte/chattaBridgeStore.d.ts +19 -0
  103. package/dist/platforms/svelte/chattaBridgeStore.js +1 -0
  104. package/dist/platforms/svelte/chattaBridgeStore.js.map +1 -0
  105. package/dist/platforms/svelte/useLiveChatta.d.ts +61 -0
  106. package/dist/platforms/svelte/useLiveChatta.js +1 -0
  107. package/dist/platforms/svelte/useLiveChatta.js.map +1 -0
  108. package/dist/platforms/tauri/TauriBridge.d.ts +34 -0
  109. package/dist/platforms/tauri/TauriBridge.js +1 -0
  110. package/dist/platforms/tauri/TauriBridge.js.map +1 -0
  111. package/dist/platforms/tauri/TauriDeepLinks.d.ts +29 -0
  112. package/dist/platforms/tauri/TauriDeepLinks.js +1 -0
  113. package/dist/platforms/tauri/TauriDeepLinks.js.map +1 -0
  114. package/dist/platforms/tauri/TauriPermissions.d.ts +21 -0
  115. package/dist/platforms/tauri/TauriPermissions.js +1 -0
  116. package/dist/platforms/tauri/TauriPermissions.js.map +1 -0
  117. package/dist/platforms/tauri/TauriUpdater.d.ts +31 -0
  118. package/dist/platforms/tauri/TauriUpdater.js +1 -0
  119. package/dist/platforms/tauri/TauriUpdater.js.map +1 -0
  120. package/dist/platforms/tauri/index.d.ts +22 -0
  121. package/dist/platforms/tauri/index.js +1 -0
  122. package/dist/platforms/tauri/index.js.map +1 -0
  123. package/dist/platforms/vue/LiveChattaView.d.ts +1 -0
  124. package/dist/platforms/vue/LiveChattaView.js +1 -0
  125. package/dist/platforms/vue/LiveChattaView.js.map +1 -0
  126. package/dist/platforms/vue/useChattaBridge.d.ts +11 -0
  127. package/dist/platforms/vue/useChattaBridge.js +1 -0
  128. package/dist/platforms/vue/useChattaBridge.js.map +1 -0
  129. package/dist/platforms/vue/useChattaDeepLink.d.ts +2 -0
  130. package/dist/platforms/vue/useChattaDeepLink.js +1 -0
  131. package/dist/platforms/vue/useChattaDeepLink.js.map +1 -0
  132. package/dist/platforms/vue/useChattaPermissions.d.ts +9 -0
  133. package/dist/platforms/vue/useChattaPermissions.js +1 -0
  134. package/dist/platforms/vue/useChattaPermissions.js.map +1 -0
  135. package/dist/platforms/vue/useChattaUnread.d.ts +8 -0
  136. package/dist/platforms/vue/useChattaUnread.js +1 -0
  137. package/dist/platforms/vue/useChattaUnread.js.map +1 -0
  138. package/dist/platforms/vue/useLiveChatta.d.ts +58 -0
  139. package/dist/platforms/vue/useLiveChatta.js +1 -0
  140. package/dist/platforms/vue/useLiveChatta.js.map +1 -0
  141. package/dist/platforms/web/LiveChattaEmbed.d.ts +94 -0
  142. package/dist/platforms/web/LiveChattaEmbed.js +1 -0
  143. package/dist/platforms/web/LiveChattaEmbed.js.map +1 -0
  144. package/dist/platforms/web/bridge.d.ts +8 -0
  145. package/dist/platforms/web/bridge.js +1 -0
  146. package/dist/platforms/web/bridge.js.map +1 -0
  147. package/dist/platforms/web/permissions.d.ts +8 -0
  148. package/dist/platforms/web/permissions.js +1 -0
  149. package/dist/platforms/web/permissions.js.map +1 -0
  150. package/dist/types/billing.d.ts +355 -0
  151. package/dist/types/billing.js +53 -0
  152. package/dist/types/billing.js.map +1 -0
  153. package/dist/types/calendar.d.ts +132 -0
  154. package/dist/types/calendar.js +15 -0
  155. package/dist/types/calendar.js.map +1 -0
  156. package/dist/types/chat-core.d.ts +901 -0
  157. package/dist/types/chat-core.js +98 -0
  158. package/dist/types/chat-core.js.map +1 -0
  159. package/dist/types/chat-features.d.ts +775 -0
  160. package/dist/types/chat-features.js +50 -0
  161. package/dist/types/chat-features.js.map +1 -0
  162. package/dist/types/content.d.ts +138 -0
  163. package/dist/types/content.js +2 -0
  164. package/dist/types/content.js.map +1 -0
  165. package/dist/types/core/AutoRefresh.d.ts +68 -0
  166. package/dist/types/core/Bridge.d.ts +124 -0
  167. package/dist/types/core/Config.d.ts +26 -0
  168. package/dist/types/core/DeepLinks.d.ts +38 -0
  169. package/dist/types/core/EventBus.d.ts +15 -0
  170. package/dist/types/core/GrantStore.d.ts +29 -0
  171. package/dist/types/core/LiveChatta.d.ts +128 -0
  172. package/dist/types/core/Permissions.d.ts +34 -0
  173. package/dist/types/core/TokenManager.d.ts +25 -0
  174. package/dist/types/core/events.d.ts +140 -0
  175. package/dist/types/csat.d.ts +110 -0
  176. package/dist/types/csat.js +12 -0
  177. package/dist/types/csat.js.map +1 -0
  178. package/dist/types/events.d.ts +242 -0
  179. package/dist/types/events.js +275 -0
  180. package/dist/types/events.js.map +1 -0
  181. package/dist/types/extras.d.ts +353 -0
  182. package/dist/types/extras.js +31 -0
  183. package/dist/types/extras.js.map +1 -0
  184. package/dist/types/http/HttpAPI.d.ts +944 -0
  185. package/dist/types/http/HttpTransport.d.ts +66 -0
  186. package/dist/types/http/incomingWebhook.d.ts +17 -0
  187. package/dist/types/incoming-webhooks.d.ts +78 -0
  188. package/dist/types/incoming-webhooks.js +16 -0
  189. package/dist/types/incoming-webhooks.js.map +1 -0
  190. package/dist/types/index.d.ts +15 -0
  191. package/dist/types/index.js +16 -0
  192. package/dist/types/index.js.map +1 -0
  193. package/dist/types/liveflex.d.ts +578 -0
  194. package/dist/types/liveflex.js +7 -0
  195. package/dist/types/liveflex.js.map +1 -0
  196. package/dist/types/models.d.ts +1753 -0
  197. package/dist/types/models.js +148 -0
  198. package/dist/types/models.js.map +1 -0
  199. package/dist/types/options.d.ts +190 -0
  200. package/dist/types/options.js +43 -0
  201. package/dist/types/options.js.map +1 -0
  202. package/dist/types/shared-channels.d.ts +236 -0
  203. package/dist/types/shared-channels.js +50 -0
  204. package/dist/types/shared-channels.js.map +1 -0
  205. package/dist/types/socket/SocketAPI.d.ts +1026 -0
  206. package/dist/types/socket/SocketTransport.d.ts +44 -0
  207. package/dist/types/types/billing.d.ts +355 -0
  208. package/dist/types/types/calendar.d.ts +132 -0
  209. package/dist/types/types/chat-core.d.ts +901 -0
  210. package/dist/types/types/chat-features.d.ts +775 -0
  211. package/dist/types/types/content.d.ts +138 -0
  212. package/dist/types/types/csat.d.ts +110 -0
  213. package/dist/types/types/events.d.ts +242 -0
  214. package/dist/types/types/extras.d.ts +353 -0
  215. package/dist/types/types/incoming-webhooks.d.ts +78 -0
  216. package/dist/types/types/index.d.ts +15 -0
  217. package/dist/types/types/liveflex.d.ts +578 -0
  218. package/dist/types/types/models.d.ts +1753 -0
  219. package/dist/types/types/options.d.ts +190 -0
  220. package/dist/types/types/shared-channels.d.ts +236 -0
  221. package/dist/types/types/workspace-gifs.d.ts +95 -0
  222. package/dist/types/types/workspace.d.ts +390 -0
  223. package/dist/types/ui/EmbedConfig.d.ts +38 -0
  224. package/dist/types/ui/EmbedUI.d.ts +44 -0
  225. package/dist/types/ui/Launcher.d.ts +122 -0
  226. package/dist/types/ui/brand.d.ts +27 -0
  227. package/dist/types/ui/embedMessages.d.ts +23 -0
  228. package/dist/types/ui/hours.d.ts +35 -0
  229. package/dist/types/ui/prechat.d.ts +35 -0
  230. package/dist/types/ui/widgetConfig.d.ts +4 -0
  231. package/dist/types/utils/crypto.d.ts +6 -0
  232. package/dist/types/utils/hmac.d.ts +40 -0
  233. package/dist/types/utils/permissions.d.ts +5 -0
  234. package/dist/types/utils/platform.d.ts +18 -0
  235. package/dist/types/utils/visitor.d.ts +2 -0
  236. package/dist/types/workspace-gifs.d.ts +95 -0
  237. package/dist/types/workspace-gifs.js +3 -0
  238. package/dist/types/workspace-gifs.js.map +1 -0
  239. package/dist/types/workspace.d.ts +390 -0
  240. package/dist/types/workspace.js +13 -0
  241. package/dist/types/workspace.js.map +1 -0
  242. package/dist/umd/livechatta.umd.js +7262 -0
  243. package/dist/umd/livechatta.umd.js.map +1 -0
  244. package/dist/umd/livechatta.umd.min.js +2 -0
  245. package/dist/umd/livechatta.umd.min.js.map +1 -0
  246. package/package.json +278 -4
package/README.md CHANGED
@@ -1,3 +1,2559 @@
1
- # Temporary Holding Version
1
+ # LiveChatta SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Official SDK for the [LiveChatta](https://livechatta.com) chat platform. Provides dual-transport (WebSocket + HTTP), headless or embedded UI modes, and cross-platform support (Web, React, React Native, Flutter, Android, iOS, Angular, Vue 3, Nuxt 3, Svelte).
4
+
5
+ > **New here?** The task-based guides (quick start, embed a chat, custom UI, webhooks, FlexCoin, calls, the CLI and each platform) are in [docs/site](docs/site/index.html). Server samples for Node, PHP and Python are in [samples](samples/README.md). What the SDK can do, release by release: [docs/features.md](docs/features.md).
6
+
7
+ > **Versions:** 1.0.0 is the first public release. Version numbers in brackets in these docs, such as "(1.7.0)", are internal pre-release builds that were never published; everything in them is in 1.0.0. See [docs/HISTORY.md](docs/HISTORY.md).
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install @livechatta/sdk
13
+ ```
14
+
15
+ Socket support requires `socket.io-client` (optional peer dependency):
16
+
17
+ ```bash
18
+ npm install socket.io-client
19
+ ```
20
+
21
+ ### Browser via CDN
22
+
23
+ ```html
24
+ <script src="https://unpkg.com/@livechatta/sdk/dist/umd/livechatta.umd.min.js"></script>
25
+ <script>
26
+ const { LiveChatta } = window.LiveChatta;
27
+ </script>
28
+ ```
29
+
30
+ ## Quick Start
31
+
32
+ ```typescript
33
+ import { LiveChatta } from '@livechatta/sdk';
34
+
35
+ // 1. Initialize
36
+ LiveChatta.init({
37
+ linkCode: 'your-link-code',
38
+ apiKey: 'your-api-key',
39
+ publicKey: '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----',
40
+ chatUsername: 'john_doe', // required for embed mode, optional for headless
41
+ enableSocket: true,
42
+ enableHttp: true,
43
+ });
44
+
45
+ // 2. Connect WebSocket
46
+ await LiveChatta.connect();
47
+
48
+ // 3. Use Socket API for real-time features
49
+ LiveChatta.sock().onMessage((msg) => {
50
+ console.log('New message:', msg);
51
+ });
52
+
53
+ // 4. Use HTTP API for REST operations
54
+ const members = await LiveChatta.api().listMembers({ linkCode: 'your-link-code' });
55
+ ```
56
+
57
+ ## Initialization Options
58
+
59
+ | Option | Type | Default | Description |
60
+ |--------|------|---------|-------------|
61
+ | `linkCode` | `string` | *required* | Identifies the business/workspace |
62
+ | `apiKey` | `string` | *required* | Authenticates the SDK consumer |
63
+ | `publicKey` | `string` | *required* | RSA public key (PEM) for encrypting embed tokens |
64
+ | `baseUrl` | `string` | `https://api.livechatta.com` | API server URL |
65
+ | `chatUsername` | `string` | — | Username for the individual user. **Required for embed mode** (per-user), optional for headless. |
66
+ | `enableSocket` | `boolean` | `true` | Enable WebSocket transport |
67
+ | `enableHttp` | `boolean` | `true` | Enable HTTP transport |
68
+ | `debug` | `boolean` | `false` | Enable debug logging to console |
69
+ | `memberToken` | `string` | — | Chat-member access token (JWT) for member REST routes in **Chat features** (mute, quiet hours, reminders, huddles). Also settable with `LiveChatta.api().setMemberToken()`. Not needed for the socket. |
70
+ | `ownerToken` | `string` | — | Owner account access token (JWT) for the owner-console methods below (emoji packs, post scheduling, promo analytics). Also settable with `LiveChatta.api().setOwnerToken()`. |
71
+
72
+ ## Token Encryption (Embed Mode)
73
+
74
+ When embedding the chat UI, credentials are encrypted using RSA-OAEP (SHA-256) with the provided `publicKey`. The embed URL uses an encrypted token instead of raw API keys:
75
+
76
+ ```
77
+ /in/:linkCode/embed/chat?token=<encrypted({apiKey, linkCode, chatUsername})>&primaryColor=...
78
+ ```
79
+
80
+ The server decrypts the token using the matching private key. This ensures API keys are never exposed in the browser URL bar or network requests.
81
+
82
+ ## Socket API — `LiveChatta.sock()`
83
+
84
+ Real-time messaging via WebSocket.
85
+
86
+ ### Emitters (Actions)
87
+
88
+ All emitters return `Promise<T>` and accept an optional callback.
89
+
90
+ ```typescript
91
+ const sock = LiveChatta.sock();
92
+
93
+ // Conversations
94
+ await sock.getConversations(query?, cb?); // 40 per page (max 40); first page carries unreadTotals
95
+ await sock.getUnreadTotals({ excludeConversationIds? }, cb?); // { unreadTotals } for the rows you have not loaded
96
+ await sock.startConversation({ senderId, type, name?, participantIds?, newParticipants?, chatLinkCode?, isPrivate? }, cb?); // GROUP defaults to private; isPrivate: false = public
97
+ await sock.enterConversation(conversationId, cb?);
98
+ await sock.joinConversation({ conversationId, senderId, participantIds?, newParticipants?, chatLinkCode? }, cb?);
99
+ await sock.editConversation({ conversationId, senderId, name?, caption?, disappearAfter?, isPrivate? }, cb?); // isPrivate: conversation admins; plain groups and channels only
100
+ await sock.toggleLock({ conversationId, senderId }, cb?);
101
+ await sock.changeConversationStatus({ conversationId, senderId, status }, cb?);
102
+
103
+ // Members
104
+ await sock.makeAdmin({ conversationId, senderId, participantIds, role?, action? }, cb?);
105
+ await sock.changeMemberStatus({ conversationId, memberId, status }, cb?); // status: 'DISABLE' to remove member
106
+
107
+ // Messages
108
+ await sock.getMessages(query, cb?);
109
+ // attachments: AttachmentInput[] = { name, link, type }[] (see HTTP section)
110
+ await sock.sendMessage({
111
+ conversationId, senderId, referenceId, message?,
112
+ attachments?, replyTo?, scheduledAt?, codeLang?,
113
+ parentMessageId?, // thread reply
114
+ messageKind?, // 'poll' for poll messages
115
+ question?, options?, multiSelect?, // poll fields
116
+ }, cb?);
117
+ await sock.typing({ conversationId, isTyping }, cb?);
118
+ await sock.changeMessageStatus({ conversationId, memberId, messageId, status }, cb?);
119
+ // status: MessageChangeStatus.DELETE | .STARRED | .UNSTARRED (PIN/UNPIN for admins)
120
+ // Admins and moderators can DELETE any user's messages (not just their own)
121
+ await sock.reactToMessage({ conversationId, messageId, emoji }, cb?);
122
+ await sock.editMessage({ conversationId, messageId, message }, cb?); // senderId is filled from the connection (or pass it)
123
+ // Edits are allowed for 24 h after sending; after that it rejects with code EDIT_WINDOW_CLOSED:
124
+ // catch (err) { if (isEditWindowClosed(err)) showToast(err.message); }
125
+ await sock.forwardMessage({ conversationId, messageId, targetConversationId }, cb?);
126
+ await sock.markMessagesRead({ conversationId, messageIds }, cb?);
127
+ await sock.searchMessages({ conversationId, query }, cb?);
128
+
129
+ // Chat Users
130
+ await sock.searchChatUsers({ chatUserSearch, limit? }, cb?);
131
+
132
+ // Threads
133
+ await sock.getThreadMessages({ parentMessageId, conversationId }, cb?);
134
+
135
+ // Bookmarks
136
+ await sock.toggleBookmark({ conversationId, messageId }, cb?);
137
+ await sock.getBookmarks({ conversationId }, cb?);
138
+ await sock.getAllBookmarks({ cursor?, limit? }, cb?); // across conversations → { messages, nextCursor }
139
+
140
+ // Membership revoked (kick / ban / leave): drop the conversation locally
141
+ sock.onMembershipRevoked(({ conversationId, memberId, status }) => {});
142
+
143
+ // Polls
144
+ await sock.votePoll({ conversationId, messageId, optionIndex }, cb?);
145
+
146
+ // Auth
147
+ await sock.validatePassword({ password }, cb?);
148
+ await sock.forgotPassword({ identifier, chatLinkCode }, cb?); // chatLinkCode required (1.2.2)
149
+ await sock.resetPassword({ token, newPassword, confirmPassword }, cb?); // → ResetPasswordResult
150
+ await sock.changePassword({ current, new: newPw }, cb?);
151
+ await sock.refreshToken({ refreshToken }, cb?);
152
+ await sock.revokeToken({}, cb?);
153
+
154
+ // Posts / Stories / Promotions
155
+ await sock.createPost({ type, content?, caption?, attachments?, memberId, ctaLabel?, ctaUrl?, expiresAt? }, cb?);
156
+ await sock.getPosts({ nextCursor?, limit?, type? }, cb?);
157
+ await sock.getStories({ nextCursor?, limit? }, cb?);
158
+ await sock.viewPost({ postId, memberId }, cb?);
159
+ await sock.reactToPost({ postId, emoji, memberId }, cb?);
160
+ await sock.replyToPost({ postId, message, attachments?, memberId }, cb?);
161
+ await sock.updatePost({ postId, content?, caption?, attachments? }, cb?);
162
+ await sock.deletePost({ postId }, cb?);
163
+ await sock.getPostMessages({ postId, limit?, nextCursor? }, cb?);
164
+
165
+ // Conversation Members
166
+ await sock.getConversationMembers({ conversationId }, cb?);
167
+
168
+ // Translation
169
+ await sock.translateMessage({ messageId, targetLanguage }, cb?);
170
+ await sock.setLanguage({ language }, cb?);
171
+
172
+ // Presence
173
+ await sock.getOnlineUsers({ memberIds }, cb?); // → { onlineUserIds }
174
+ await sock.heartbeat(); // web client: heartbeat({ visible: false }) while hidden, { visible: true } on every beat while on screen
175
+
176
+ // Webinar (Orbit plan — host controls)
177
+ await sock.startWebinar({ conversationId, maxAttendees? }, cb?); // → { conversationId, isWebinar }
178
+ sock.raiseHandWebinar({ conversationId }); // attendee — no ack
179
+ sock.lowerHand({ conversationId }); // attendee — no ack
180
+ await sock.submitWebinarQa({ conversationId, question }, cb?); // → { conversationId, qa }
181
+ await sock.answerWebinarQa({ conversationId, qaId, answer }, cb?); // → { conversationId, qaId, answered, answer, qa }
182
+ await sock.promoteAttendeeAudio({ conversationId, attendeeId }, cb?); // → { conversationId, attendeeId, promoted }
183
+
184
+ // Link Automations (socket emitters) — trigger/action are string enums,
185
+ // params go in triggerConfig/actionConfig. Automations are scoped to a chat link.
186
+ await sock.createAutomation({ chatLinkId, name, trigger, triggerConfig?, action, actionConfig? }, cb?); // → Automation
187
+ await sock.updateAutomation({ automationId, name?, trigger?, action?, isActive? }, cb?); // → Automation
188
+ await sock.deleteAutomation({ automationId }, cb?); // → { deleted }
189
+ await sock.getAutomations({ chatLinkId }, cb?); // → { automations }
190
+ await sock.getConversationStats(conversationId, cb?); // → { conversationId, messageCount, messagesPerDay, avgResponseTimeMinutes, peakHour }
191
+ ```
192
+
193
+ ### Listeners
194
+
195
+ All listeners are chainable (return `this`).
196
+
197
+ ```typescript
198
+ // Messages
199
+ sock.onMessage((data) => { ... });
200
+ sock.onEditMessage((data) => { ... });
201
+ sock.onForwardMessage((data) => { ... });
202
+ sock.onMessageFailed((data) => { ... });
203
+ sock.onMessageRead((data) => { ... });
204
+ sock.onScheduledMessage((data) => { ... });
205
+ sock.onMessageStatusChange((data) => { ... });
206
+ sock.onMessageReaction((data) => { ... });
207
+
208
+ // Conversations
209
+ sock.onConversation((data) => { ... });
210
+ sock.onEditConversation((data) => { ... });
211
+ sock.onMakeAdmin((data) => { ... });
212
+ sock.onJoinConversation((data) => { ... });
213
+ sock.onMemberStatusChange((data) => { ... });
214
+ sock.onToggleConversation((data) => { ... });
215
+ sock.onStatusChangeConversation((data) => { ... });
216
+ sock.onPinConversation((data) => { ... });
217
+ sock.onUnreadCountUpdate((data) => { ... });
218
+
219
+ // Presence & typing
220
+ sock.onTyping((data) => { ... });
221
+ sock.onOnline((data) => { ... });
222
+ sock.onOffline((data) => { ... });
223
+
224
+ // Polls
225
+ sock.onVotePoll((data) => { ... });
226
+
227
+ // Posts / Stories
228
+ sock.onCreatePost((data) => { ... });
229
+ sock.onNewStory((data) => { ... });
230
+ sock.onUpdatePost((data) => { ... });
231
+ sock.onDeletePost((data) => { ... });
232
+ sock.onReactToPost((data) => { ... });
233
+ sock.onReplyToPost((data) => { ... });
234
+
235
+ // Translation
236
+ sock.onTranslateMessage((data) => { ... });
237
+
238
+ // AI Credits
239
+ sock.onAiCreditsUpdated((data) => { ... });
240
+ sock.onAiCreditsExhausted((data) => { ... });
241
+
242
+ // Webinar events (Orbit plan — listen as host or attendee)
243
+ sock.onWebinarStarted((data) => { ... }); // host broadcast started
244
+ sock.onWebinarRaisedHand((data) => { ... }); // attendee raised hand
245
+ sock.onWebinarHandLowered((data) => { ... }); // attendee lowered hand
246
+ sock.onWebinarAttendeePromoted((data) => { ... }); // attendee unmuted/promoted
247
+ sock.onWebinarQaSubmitted((data) => { ... }); // Q&A answered or status changed (WEBINAR_QA_UPDATED)
248
+
249
+ // Misc
250
+ sock.onNotification((data) => { ... });
251
+ sock.onError((data) => { ... });
252
+
253
+ // A denied emit rejects (the server also sends chat-error, so onError still fires)
254
+ try {
255
+ await sock.sendMessage(payload);
256
+ } catch (err) {
257
+ if (isSocketError(err)) showToast(err.message); // err.code is 'SOCKET_ERROR' or the server's code; err.transport === 'socket'; err.statusCode, err.details
258
+ }
259
+
260
+ // Lifecycle
261
+ sock.onConnect(() => { ... });
262
+ sock.onDisconnect(({ reason }) => { ... });
263
+ sock.onReconnect(({ attempt }) => { ... });
264
+ sock.onReconnecting(({ attempt }) => { ... });
265
+
266
+ // Remove a listener
267
+ sock.off('message', handler);
268
+ ```
269
+
270
+ ### Role-Based Moderation
271
+
272
+ Conversations support four roles: `SUPER_ADMIN`, `ADMIN`, `MODERATOR`, `MEMBER`. Admins and moderators can delete **any** user's messages (not just their own). Use `ConversationUser.role` from `getConversations()` to determine what actions to show in your UI.
273
+
274
+ ```typescript
275
+ import { UserConversationRole, MessageChangeStatus } from '@livechatta/sdk';
276
+
277
+ // getConversations() returns ConversationUser records with a role field
278
+ const convs = await sock.getConversations();
279
+ const myRole = convs.results[0]?.role; // 'ADMIN' | 'MODERATOR' | 'MEMBER' | 'SUPER_ADMIN'
280
+
281
+ // Check if user can moderate
282
+ const canModerate = myRole === UserConversationRole.ADMIN
283
+ || myRole === UserConversationRole.SUPER_ADMIN
284
+ || myRole === UserConversationRole.MODERATOR;
285
+
286
+ // Moderator/admin deleting another user's message
287
+ if (canModerate) {
288
+ await sock.changeMessageStatus({
289
+ conversationId: 'conv_id',
290
+ memberId: 'my_member_id',
291
+ messageId: 'target_message_id',
292
+ status: MessageChangeStatus.DELETE,
293
+ });
294
+ }
295
+
296
+ // Promote a member to moderator
297
+ await sock.makeAdmin({
298
+ conversationId: 'conv_id',
299
+ senderId: 'my_member_id',
300
+ participantIds: ['user_to_promote'],
301
+ role: 'MODERATOR',
302
+ });
303
+ ```
304
+
305
+ **Moderator permissions:** `delete_message`, `pin_message`, `mute_member`. These are enforced server-side — the backend validates the caller's role before allowing the action.
306
+
307
+ ## HTTP API — `LiveChatta.api()`
308
+
309
+ RESTful operations. All methods are async.
310
+
311
+ ```typescript
312
+ const api = LiveChatta.api();
313
+
314
+ // Members
315
+ // Participant shape (backend ChatLinkParticipantDto): displayName, email and
316
+ // country (ISO code, e.g. "NG") are REQUIRED; photo, chatLinkCode, phone,
317
+ // deviceToken, webToken, handle and password (min 8) are optional.
318
+ await api.registerMember({ displayName, email, country, photo?, chatLinkCode?, phone?, password?, handle? });
319
+ // A taken handle (or email local part) gets the next free -2, -3, ...; the returned member shows the final handle.
320
+ await api.registerMembers({ participants: [...] }); // 1-100 participants
321
+ await api.listMembers(query?);
322
+ await api.getMember(memberIdOrUsername);
323
+
324
+ // Chat Links
325
+ await api.createChatLink({ name, caption?, profilePhoto?, conversationType?, expiresAt?, maxMembers?, allowAttachments?, allowMemberInvite?, welcomeMessage?, theme?, settings?, participants? });
326
+ await api.listChatLinks(query?);
327
+ await api.getChatLink(linkId);
328
+ await api.updateChatLink(linkId, { name?, caption?, profilePhoto?, expiresAt?, maxMembers?, allowAttachments?, allowMemberInvite?, welcomeMessage?, theme?, settings?, status? });
329
+
330
+ // Conversations
331
+ // memberId (the creating member) and conversationType are REQUIRED.
332
+ await api.createConversation(linkId, { memberId, conversationType, name?, participants?, includeSelf?, isPrivate? });
333
+ // A new GROUP is private (not listed, no self-join) unless isPrivate: false; CHANNEL stays public unless isPrivate: true.
334
+ // Existing groups are unchanged. Switch later with updateConversationPermissions(id, { isPrivate }): admins/owner, groups and channels only.
335
+ // NOTE: these two return a { main, other, conversation } envelope — the page
336
+ // of conversation-users lives at `.main.results`, not `.results`.
337
+ await api.getMemberConversations(memberId, query?); // → ConversationUsersPage
338
+ await api.getConversationUsers(conversationId, query?); // → ConversationUsersPage
339
+
340
+ // Messages
341
+ await api.getMessages(memberId, conversationId, query?);
342
+ // attachments use the backend DocLinkType shape: { name, link, type } where
343
+ // `link` is a base64 data-URI or URL and `type` is an AttachmentType
344
+ // (PHOTO | VIDEO | AUDIO | WORD | PDF | EXCEL | ZIP | OTHER).
345
+ await api.sendMessage({ conversationId, senderId, referenceId, message?, attachments?, scheduledAt?, replyTo?, codeLang? });
346
+ // List messages SENT BY the API key's owner account (bot / owner messages),
347
+ // cursor-paginated, newest-first — GET /external/chats/messages. The page
348
+ // hard-excludes scheduled messages and thread children. `conversationId` is
349
+ // serialized as the backend `chatMessageByConversationIds` filter key.
350
+ await api.listSentMessages({ conversationId?, nextCursor?, prevCursor?, limit? }); // → PaginatedResult<Message>
351
+ // Scheduled-message management. The SDK's api-key external routes are
352
+ // owner-scoped and REQUIRE conversationId on both mutating routes. (The
353
+ // sender-scoped scheduled-list route is JWT-dashboard only.)
354
+ await api.rescheduleMessage(messageId, conversationId, scheduledAt); // → Message
355
+ await api.cancelScheduledMessage(messageId, conversationId); // → MessageMutationResult
356
+
357
+ // Push Notifications
358
+ await api.sendPushNotification({ deviceToken, body, title?, imageUrl?, topic?, metaData? });
359
+
360
+ // Exports — conversationId is REQUIRED; email defaults to the key owner's
361
+ // username; format is CSV (default) or PDF.
362
+ await api.exportChat({ conversationId, email?, format? });
363
+ await api.getExports(query?);
364
+
365
+ // Canned Responses
366
+ await api.getCannedResponses();
367
+ await api.createCannedResponse({ title, body, shortcut? });
368
+ await api.updateCannedResponse(id, { title?, body?, shortcut? });
369
+ await api.deleteCannedResponse(id);
370
+
371
+ // Webhooks
372
+ await api.getWebhooks(query?);
373
+ await api.getWebhook(webhookId);
374
+ await api.createWebhook({ name, url, events, secret? }); // name is REQUIRED; url must be HTTPS
375
+ await api.updateWebhook(webhookId, { url?, events?, secret?, name?, status? });
376
+ await api.deleteWebhook(webhookId);
377
+
378
+ // Webinar (only the registrations list is exposed over HTTP)
379
+ await api.getWebinarRegistrations(conversationId); // owner only
380
+
381
+ // Analytics & Automations are SOCKET events, not HTTP methods — use the
382
+ // socket API: `sock.getConversationStats(conversationId, cb)`,
383
+ // `sock.getAutomations(chatLinkId, cb)`, `sock.createAutomation(...)`, etc.
384
+ // (There is no `api.getLinkAnalytics` / `api.listAutomations` on HttpAPI.)
385
+
386
+ // Translation
387
+ await api.translateMessage(messageId, targetLanguage);
388
+
389
+ // Chat User Profile
390
+ await api.updateChatUserProfile({ displayName?, handle?, photo?, caption?, country?, phone?, preferences? });
391
+ await api.getHandleEditInfo();
392
+
393
+ // Admin Reply (no attachments on this route — parentMessageId threads the reply)
394
+ await api.sendAdminReply({ conversationId, message, parentMessageId? });
395
+ ```
396
+
397
+ ### Content features — emoji packs, scheduled posts, promo analytics
398
+
399
+ Three link-level features. Most methods are **owner-console** routes: they need the link owner's account token, not just the API key.
400
+
401
+ ```typescript
402
+ LiveChatta.init({
403
+ linkCode: 'acme-help',
404
+ apiKey: 'your-api-key',
405
+ publicKey: '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----',
406
+ enableSocket: false,
407
+ ownerToken: process.env.LIVECHATTA_OWNER_TOKEN, // owner account JWT — server-side only
408
+ });
409
+ const api = LiveChatta.api();
410
+ // or later / after a token refresh: api.setOwnerToken(newToken); api.setOwnerToken(null) to clear
411
+ ```
412
+
413
+ | Auth | Methods | Route base |
414
+ |---|---|---|
415
+ | Owner token (Bearer) | `createLinkEmoji`, `listLinkEmojis`, `updateLinkEmoji`, `enableLinkEmoji`, `disableLinkEmoji`, `deleteLinkEmoji`, `createPost`, `listPosts`, `schedulePost`, `publishPost`, `cancelPostSchedule`, `getPromoAnalytics` | `/api/v1` |
416
+ | None (public) | `getLinkEmojiPack(linkCode)` | `/in/:linkCode/emoji-pack` |
417
+ | None (public) | `trackPromoClick(postId, visitorId?)` | `/api/v1/promos/:postId/click` |
418
+
419
+ > **Keep the owner token on your server.** It is a full owner-account credential (not scoped like an API key). Call the owner methods from Node (or a native app's secure storage), never from a public web page. Chat-member tokens get `403`. Without a token, owner methods throw `LiveChattaError` with code `OWNER_TOKEN_REQUIRED` before any request is sent; `401`/`403` from these routes surface with code `OWNER_AUTH`.
420
+
421
+ **Custom emoji & sticker packs** (plan gate `allowCustomEmoji`, cap `maxCustomEmojiPerLink`):
422
+
423
+ ```typescript
424
+ // Owner: upload (PNG/GIF/WebP as a data URI). Emoji 16–128 px ≤256 KB, sticker 64–512 px ≤512 KB.
425
+ const item = await api.createLinkEmoji(linkId, {
426
+ kind: 'emoji', // or 'sticker'
427
+ shortcode: ':party_parrot:', // stored as party_parrot ([a-z0-9_]{2,32}, unique per link)
428
+ image: 'data:image/gif;base64,R0lGOD…',
429
+ });
430
+ await api.listLinkEmojis(linkId, { kind: 'sticker', enabled: '1', limit: '50' }); // cursor page
431
+ await api.updateLinkEmoji(linkId, item._id, { shortcode: 'parrot' });
432
+ await api.disableLinkEmoji(linkId, item._id); // enableLinkEmoji(...) to restore
433
+ await api.deleteLinkEmoji(linkId, item._id); // { deleted: true, id }
434
+
435
+ // Members / your UI: public pack, enabled items only — fetch once per chat load.
436
+ const pack = await api.getLinkEmojiPack('acme-help'); // { linkId, emojis: [...], stickers: [...] }
437
+ const byCode = new Map([...pack.emojis, ...pack.stickers].map((e) => [e.shortcode, e]));
438
+ // Render `:shortcode:` tokens in message text from byCode (shortcodes stay plain text in messages).
439
+ ```
440
+
441
+ **Drafts and scheduled posts** (`DRAFT` → `SCHEDULED` → `ACTIVE` → `ARCHIVED`):
442
+
443
+ ```typescript
444
+ const draft = await api.createPost({ type: PostType.PROMOTION, content: 'Winter sale',
445
+ cta: { label: 'Shop now', url: 'https://acme.com/sale' }, asDraft: true });
446
+ await api.schedulePost(draft._id, { scheduledAt: '2026-12-01T09:00:00Z', expiresAt: '2026-12-08T09:00:00Z' });
447
+ await api.listPosts({ postByStatuses: 'SCHEDULED' }); // the queue (or 'DRAFT')
448
+ await api.cancelPostSchedule(draft._id); // back to DRAFT
449
+ await api.publishPost(draft._id); // go live now
450
+ // Or schedule at creation: createPost({ ..., scheduledAt }) — 1 minute to 1 year ahead.
451
+ ```
452
+
453
+ Publishing (cron or `publishPost`) is not pushed over the socket yet; members see new posts on their next `getPosts()`.
454
+
455
+ **Promo analytics:**
456
+
457
+ ```typescript
458
+ import { getPromoVisitorId } from '@livechatta/sdk';
459
+
460
+ // On a CTA tap: record the click first, then open the returned url.
461
+ const { url } = await api.trackPromoClick(post._id, getPromoVisitorId());
462
+ window.open(url, '_blank', 'noopener');
463
+
464
+ // Owner: 30-day window + lifetime totals (PROMOTION posts only).
465
+ const stats = await api.getPromoAnalytics(post._id);
466
+ console.log(`${(stats.totals.ctr * 100).toFixed(1)}% CTR`, stats.days); // ctr = uniqueClicks / impressions
467
+ ```
468
+
469
+ `getPromoVisitorId()` creates a random id (`v_` + 32 hex) on first use and keeps it in `localStorage` under `livechatta:visitor-id`; unique clicks are counted once per visitor per UTC day. If storage is blocked it lasts for the page. Malformed ids are not sent (the server falls back to IP + user agent). Click calls are never retried, so a flaky network can't double-count. Impressions are counted by the server when members fetch the feed.
470
+
471
+ All shapes are typed: `CustomEmoji`, `EmojiPack`, `CreateOwnerPostPayload`, `SchedulePostPayload`, `PostScheduleResult`, `PromoClickResult`, `PromoAnalytics` (from `@livechatta/sdk`). `Post` now carries optional `scheduledAt`, `publishedAt`, `impressionCount`, `ctaClickCount`, `ctaUniqueClickCount`.
472
+
473
+ ### Chat features — seen-by, mute, quiet hours, reminders, permissions, huddles, transcripts, inbox
474
+
475
+ Every feature has a **socket** form that runs as the connected chat user (the embed token from `init()`), so most member apps need nothing beyond `connect()`. The **REST** forms live under `/api/v1` and take a user token, not the API key:
476
+
477
+ | Credential | Socket | REST |
478
+ |---|---|---|
479
+ | None beyond `connect()` (socket identity = `chatUsername`) | all emitters and listeners below | — |
480
+ | `memberToken` (chat member JWT) | — | `exportConversationAsAdmin`, `muteConversation`, `getQuietHours` / `setQuietHours`, `createReminder` / `listReminders` / `cancelReminder` / `completeReminder`, `startHuddle` / `getHuddle` / `endHuddle` |
481
+ | `memberToken`, else `ownerToken` (routes open to both) | — | `getMessageInfo`, `getConversationPermissions` / `updateConversationPermissions`, `getTranscribeAvailability`, `transcribeMessage`, `getTranscript`, `summarizeTranscript`, `translateTranscript` |
482
+ | `ownerToken` only (`@OwnerOnly`) | `onInboxUpdated` (owner/agent dashboard sockets) | `setLinkAutoTranscribe`, `setLinkAgentInbox`, `listInbox`, `assignInbox`, `setInboxStatus` |
483
+
484
+ Mute, quiet hours and reminders always act on the caller's own rows, so they need the **member** token; an owner token gets `400 User does not belong to this conversation` from the server, and the SDK refuses up front (`MEMBER_TOKEN_REQUIRED`). Missing tokens on the other routes throw `USER_TOKEN_REQUIRED` / `OWNER_TOKEN_REQUIRED` before any request; server 401/403 surface as `USER_AUTH` / `OWNER_AUTH` with the server message.
485
+
486
+ Getting a member token in an embed:
487
+
488
+ ```typescript
489
+ LiveChatta.bridge?.onLoginSuccess(({ accessToken }) => LiveChatta.api().setMemberToken(accessToken));
490
+ LiveChatta.bridge?.onLogout(() => LiveChatta.api().setMemberToken(null));
491
+ ```
492
+
493
+ **Seen-by and delivery ticks**
494
+
495
+ ```typescript
496
+ const sock = LiveChatta.sock();
497
+ // Batch-ack messages you didn't send (≤ 100 ids per call) when they arrive.
498
+ sock.onMessage((m) => { if (m.senderId !== myMemberId) queueDelivered(m.conversationId!, m._id!); });
499
+ await sock.messageDelivered({ conversationId, messageIds }); // others get onMessageDelivered
500
+ const info = await sock.messageInfo({ conversationId, messageId }); // sender or conversation admin
501
+ // info.totals = { members, delivered, read }; info.results[i] = { member, deliveredAt, readAt }
502
+ ```
503
+
504
+ Ticks: sent → delivered (any `deliveredTo`) → read. Read implies delivered.
505
+
506
+ **Mute and quiet hours**
507
+
508
+ ```typescript
509
+ await sock.muteConversation({ conversationId, duration: '8h' }); // '1h' | '8h' | '1w' | 'forever' | 'off'
510
+ sock.onConversationMuted((s) => updateRow(s.conversationId, s.isMuted, s.mutedUntil)); // all your devices
511
+ await sock.updateQuietHours({ enabled: true, start: '22:00', end: '07:00', timezone: 'Africa/Lagos' });
512
+ ```
513
+
514
+ Muted: no push or toast, unread still counts, @mentions still notify. Quiet hours suppress push only (it still appears in the in-app list); calls always ring. `end < start` crosses midnight.
515
+
516
+ **Reminders and read later**
517
+
518
+ ```typescript
519
+ await sock.setMessageReminder({ conversationId, messageId, kind: 'remind', preset: 'tomorrow' });
520
+ await sock.setMessageReminder({ conversationId, messageId, kind: 'remind', preset: 'custom', remindAt: '2026-11-20T09:00:00Z' });
521
+ await sock.setMessageReminder({ conversationId, messageId, kind: 'read_later' });
522
+ sock.onMessageReminderDue((r) => showReminder(r.messagePreview, r.conversationId, r.messageId));
523
+ sock.onMessageRemindersChanged(({ action, reminder }) => syncList(action, reminder));
524
+ const page = await LiveChatta.api().listReminders({ kind: 'read_later' }); // REST (member token)
525
+ await LiveChatta.api().completeReminder(page.results[0]._id);
526
+ ```
527
+
528
+ Presets: `20m`, `1h`, `3h`, `tomorrow` (09:00 next day, your timezone), `custom` (1 minute to 365 days ahead). Setting the same reminder again reschedules it; 200 pending per user.
529
+
530
+ **Conversation permissions and slow mode**
531
+
532
+ ```typescript
533
+ import { parsePermissionDenial, DEFAULT_CONVERSATION_PERMISSIONS } from '@livechatta/sdk';
534
+
535
+ const perms = await LiveChatta.api().getConversationPermissions(conversationId);
536
+ composer.disabled = !perms.membersCanSend && !iAmAdmin;
537
+ await sock.updateConversationPermissions({ conversationId, slowModeSeconds: 30, membersCanShareMedia: false });
538
+ sock.onConversationPermissionsUpdated(applyPermissions);
539
+
540
+ // Denials arrive as socket chat-error frames, rejected emits (LiveChattaError) and REST 400/403. Same parser for all:
541
+ sock.onError((err) => {
542
+ const denial = parsePermissionDenial(err);
543
+ if (denial?.action === 'slowMode') startCountdown(denial.retryAfterSeconds);
544
+ else if (denial) showToast(denial.message); // action: send | shareMedia | addPeople | startCall | pin
545
+ });
546
+ ```
547
+
548
+ Older conversations have no `permissions`; treat missing values as `DEFAULT_CONVERSATION_PERMISSIONS`. Admins, moderators and bots are exempt. The update key is `allowScreenshots`; the response key is `allowScreenshot`. The server is authoritative; use the flags to disable UI.
549
+
550
+ **Export a conversation (conversation admins)** (member token, owner plan `allowChatExport`)
551
+
552
+ ```typescript
553
+ const res = await LiveChatta.api().exportConversationAsAdmin(conversationId, 'PDF'); // or 'CSV' (default)
554
+ showToast(`Export started. We'll email ${res.email}.`); // always the caller's own account email
555
+ ```
556
+
557
+ Non-admins, former members and other orgs' conversations get `403` (`code: 'USER_AUTH'`). Owners keep using the owner export routes. `getChatUserProfile()` returns the signed-in chat user with `hasBusinessAccount` (show a "Business dashboard" link when true).
558
+
559
+ **Huddles** (CHANNEL / GROUP, plan `allowHopCircle`, no ring)
560
+
561
+ ```typescript
562
+ const huddle = await sock.huddleStart({ conversationId, initialMediaKind: 'audio' }); // start or join
563
+ await sock.joinHop({ conversationId }); // media signalling is the normal Hop flow
564
+ sock.onHuddleUpdated((h) => renderHuddleBar(h)); // active:false = ended; participantCount 0 + emptySince = 5-min idle grace
565
+ await sock.leaveHop({ sessionId: huddle.sessionId! });
566
+ ```
567
+
568
+ `membersCanStartCalls` only gates starting; members can always join a running huddle. `huddle-start` can answer with `hop-redirect` like `hop-start`.
569
+
570
+ **Voice / video note transcripts** (billed to the link owner)
571
+
572
+ ```typescript
573
+ import type { TranscribeErrorCode } from '@livechatta/sdk';
574
+ const TRANSCRIPT_COPY: Record<TranscribeErrorCode, string> = {
575
+ OUT_OF_AI_CREDITS: 'Out of AI credits', NOT_AVAILABLE: 'Not available', NO_MEDIA: 'No audio found',
576
+ TOO_LONG: 'Too long to transcribe', PROVIDER_FAILED: 'Transcription failed',
577
+ };
578
+ const avail = await LiveChatta.api().getTranscribeAvailability(); // hide "Transcribe" when !avail.enabled
579
+ const { transcript } = await sock.transcribeMessage({ conversationId, messageId }); // pending, or existing result
580
+ sock.onMessageTranscriptUpdated(({ messageId, transcript }) => {
581
+ if (transcript.status === 'done') render(messageId, transcript.text);
582
+ if (transcript.status === 'failed') render(messageId, TRANSCRIPT_COPY[transcript.errorCode!]);
583
+ });
584
+ const { summary } = await LiveChatta.api().summarizeTranscript(conversationId, messageId);
585
+ const { translation } = await LiveChatta.api().translateTranscript(conversationId, messageId, 'fr');
586
+ ```
587
+
588
+ Failures are data, never HTTP errors: `transcript.errorCode` is `OUT_OF_AI_CREDITS` ("Out of AI credits"), `NOT_AVAILABLE` ("Not available"), `NO_MEDIA`, `TOO_LONG` ("Too long to transcribe") or `PROVIDER_FAILED`. Summary and translate return `errorCode` the same way.
589
+
590
+ **Agent inbox and per-link toggles** (Business, owner token)
591
+
592
+ ```typescript
593
+ await api.setLinkAgentInbox(linkId, true); // { linkId, agentInbox }
594
+ await api.setLinkAutoTranscribe(linkId, true); // auto-transcribe notes on send
595
+ const mine = await api.listInbox({ lane: 'mine', limit: '20' }); // waiting | mine | unassigned | resolved
596
+ await api.assignInbox(conversationId, teammateUserId); // null unassigns
597
+ await api.setInboxStatus(conversationId, 'resolved'); // open | waiting | resolved
598
+ sock.onInboxUpdated(({ conversationId, inbox }) => moveCard(conversationId, inbox.status));
599
+ ```
600
+
601
+ Customer messages set `open` (and reopen resolved threads); agent replies set `waiting`, stamp `firstResponseMs` once, and auto-assign an unassigned thread to the replying dashboard agent.
602
+
603
+ ### Support inbox from the chat UI (agents)
604
+
605
+ Agents are chat users whose email matches the workspace owner or an active teammate. These routes take the **member** token (business-console tokens are refused); the server re-checks team and conversation membership on every call.
606
+
607
+ ```typescript
608
+ const api = LiveChatta.api();
609
+ const me = await api.getInboxAgentProfile(); // { agent, teamRole?, team }
610
+ if (me.agent) {
611
+ await api.createInternalNote(conversationId, { message: 'VIP: refund approved' }); // customers never see it
612
+ const state = await api.getAgentInboxState(conversationId); // inbox, sla { state, ratio }, topic, tag
613
+ await api.agentAssignConversation(conversationId, me.userId!); // null unassigns
614
+ await api.agentSetInboxStatus(conversationId, 'resolved');
615
+ await api.createConversationNote(conversationId, 'Prefers email'); // follows the customer
616
+ const { summary, errorCode } = await api.getConversationSummary(conversationId);
617
+ const { draft } = await api.getDraftReply(conversationId); // editable AI draft; state.customer has country, city, page, device
618
+ const mine = await api.draftConversationReply(conversationId, 'say yes at 5'); // any member: private draft, never posted
619
+ }
620
+ const catchUp = await api.getConversationCatchUp(conversationId, unread); // unread >= 8
621
+ await api.setConversationTopic(conversationId, 'billing'); // first pick wins for customers
622
+ await api.setLinkInboxSettings(linkId, { slaTargetMinutes: 30, topics: [{ label: 'Billing', tag: 'support' }] }); // owner token
623
+ const stats = await api.getPresenceStats(linkCode); // public: { enabled, agentsOnline, typicalReplyMinutes }
624
+
625
+ sock.onInternalNote(({ conversationId, note }) => renderNote(conversationId, note));
626
+ sock.onInternalNoteDeleted(({ noteId }) => removeNote(noteId));
627
+ sock.onConversationNotesUpdated(({ action, note, noteId }) => syncNotes(action, note, noteId));
628
+ ```
629
+
630
+ ### Support satisfaction ratings (CSAT)
631
+
632
+ After a support conversation is resolved the customer gets a rating card (`messageKind: 'CSAT'`, `message.csat`) and rates it 1–5 once within 7 days. Support links ask by default; `setLinkInboxSettings(linkId, { csatEnabled, csatQuestion })` turns it on or off and sets the question (null restores the default).
633
+
634
+ ```typescript
635
+ await api.submitCsat(conversationId, { score: 5, comment: 'Quick and kind', ratingId: msg.csat!.ratingId }); // member token, the customer; never retried
636
+ const page = await api.listCsatRatings({ chatLinkId, limit: 20 }); // API key: rated requests, newest first
637
+ const sum = await api.getCsatSummary({ from: '2026-11-01T00:00:00Z' }); // average, satisfiedPct, responseRatePct, agents, teams
638
+ // listCsatRatingsAsOwner / getCsatSummaryAsOwner take the owner token
639
+ sock.onCsatUpdated(({ messageId, csat, rating }) => updateCard(messageId, csat, rating)); // rating (with the comment) reaches agents only
640
+ ```
641
+
642
+ `inbox.csatScore` holds the latest score and `getAgentInboxState(...).csat` the latest request. Webhook event: `csat:submit` (alias `csat.submitted`, `CsatWebhookPayload`). CLI: `chatta csat list | summary`.
643
+
644
+ Summary, draft and catch-up failures are data (`errorCode`: `OUT_OF_AI_CREDITS`, `NOT_ENOUGH_MESSAGES`, `PROVIDER_FAILED`). Messages with `visibility: 'internal'` only ever reach agents.
645
+
646
+ ### Chat core: read sync, my links, delete, search, widget, gifts
647
+
648
+ ```typescript
649
+ await sock.conversationRead(conversationId); // zero your unread count
650
+ sock.onConversationRead(({ conversationId }) => clearBadge(conversationId)); // every device of yours
651
+ sock.onUnreadCountUpdate((u) => { if (u.senderId !== myMemberId) bump(u.conversationId); });
652
+ sock.onThreadUpdate(({ parentMessageId, replier }) => addReplierAvatar(parentMessageId, replier));
653
+
654
+ const links = await api.listMyChatLinks({ status: 'ACTIVE', search: 'sup' }); // member token, live unreadCount
655
+ // each row also has memberCount ("42 members") and role: 'owner' | 'admin' | 'agent' | 'member'
656
+
657
+ await sock.deleteMessage({ conversationId, messageId, scope: 'everyone' }); // or 'me'
658
+ sock.onMessageDeleted((e) => e.scope === 'everyone' ? showDeleted(e.messageId) : removeRow(e.messageId));
659
+
660
+ const hits = await sock.searchAll({ q: 'invoice', scope: 'all' }); // messages (paged), conversations, people
661
+
662
+ await api.setWidgetConfig(linkId, { preChat, businessHours }); // owner token; returns the normalised config
663
+ const open = await api.getLinkAvailability(linkCode); // public: { open, nextOpenLabel, awayMessage }
664
+ await sock.submitPreChat({ conversationId, name, email });
665
+ sock.onPreChatSubmitted((p) => showContext(p.conversationId, p));
666
+ await api.setLinkDiscoverable(linkId, true); // offer in "Did you mean" suggestions
667
+
668
+ await api.announceGift(conversationId, paystackReference, 'Enjoy!'); // after a verified gift checkout
669
+
670
+ LiveChatta.bridge?.onLinkUnavailable(({ state }) => showLinkGone(state)); // expired | disabled | archived (410)
671
+ ```
672
+
673
+ `toLinkWidgetConfig(widgetConfig, topicLabels?)` turns the server config into the launcher's `preChat` / `businessHours` options. Delete for everyone: senders within 48 h (`DELETE_FOR_EVERYONE_WINDOW_MS`), conversation admins and moderators any time.
674
+
675
+ ### Blocked members and server error codes
676
+
677
+ When an owner blocks a member (owner → Members → Block), `POST /in/:code/join-exist` answers `403` with `code: 'LINK_MEMBER_BLOCKED'` and no token, and the unfiltered first page of `all-conversations` (no cursor, no search) carries `linkAccess: 'blocked'` so a restored session can tell too. Any client error (<500) whose body has an UPPER_SNAKE `code` now surfaces it on `LiveChattaError.code` (it wins over the generic `USER_AUTH` / `OWNER_AUTH`), and the raw body is on `err.details`.
678
+
679
+ ```typescript
680
+ import { LiveChattaError, LINK_MEMBER_BLOCKED, serverErrorCode } from '@livechatta/sdk';
681
+
682
+ // Any SDK call: the server code lands on err.code.
683
+ const isBlocked = (err: unknown) => err instanceof LiveChattaError && err.code === LINK_MEMBER_BLOCKED;
684
+
685
+ // Your own login form calling POST /in/:code/join-exist (the SDK has no wrapper for it):
686
+ const res = await fetch(`${rootUrl}/in/${linkCode}/join-exist`, { method: 'POST', headers, body });
687
+ if (!res.ok) {
688
+ const body = await res.json();
689
+ if (res.status === 403 && serverErrorCode(body) === LINK_MEMBER_BLOCKED) showBlockedCard(body.message);
690
+ }
691
+
692
+ const page = await sock.getConversations();
693
+ if (page.linkAccess === 'blocked') showBlockedCard(); // 'ok' | 'blocked' | undefined (filtered pages)
694
+ ```
695
+
696
+ The `403` message names the link: "An admin of Acme Support removed your access. If you think this is a mistake, contact them." Show it as is.
697
+
698
+ **Invite-only links.** Anyone not on the invite list gets `403 INVITE_ONLY` on join, sign-in and join-via-link, and their socket gets no link room: the first conversation page has `linkAccess: 'invite-only'`. The owner lists the invited people who have not joined with `getLinkMemberList(linkId, { status: 'invited' })` and removes one with `revokeLinkInvite(linkId, memberId)` (`{ status: true, blocked }`: someone who already joined is blocked too).
699
+
700
+ **Sending too fast.** A burst of sends fails with `RATE_LIMITED` (429) on `chat-error` and the ack: keep the message as not sent and offer Retry (`isRateLimited(err)`). **Handles.** Bot and broadcast names such as `@chatta`, `@all`, `@admin` or `@support` are reserved: the profile update answers 400 with "@all is reserved. Please choose another." (no code; show the message).
701
+
702
+ ### Signed-in devices and quiet hours
703
+
704
+ Each login is a revocable session. Business accounts use the **owner** token, chat users the **member** token; both return `{ results: AuthSessionView[], currentId }` with `browser`, `os`, `deviceType` (`desktop | mobile | tablet`), `client` (`web | desktop-app | mobile-app`), approximate `country` / `city` (or null), `createdAt`, `lastActiveAt` and `current`.
705
+
706
+ | Owner token (`/users/…`) | Member token (`/chat-users/me/…`) | Result |
707
+ |---|---|---|
708
+ | `listAccountSessions()` | `listMySessions()` | `AuthSessionList` |
709
+ | `revokeAccountSession(id)` | `revokeMySession(id)` | `{ revoked: 1 }`; `400` for the calling session (use sign-out), `404` if not yours |
710
+ | `revokeOtherAccountSessions()` | `revokeMyOtherSessions()` | `{ revoked: number }` |
711
+
712
+ ```typescript
713
+ const { results, currentId } = await LiveChatta.api().listMySessions();
714
+ for (const s of results.filter((r) => !r.current)) await LiveChatta.api().revokeMySession(s.id);
715
+ ```
716
+
717
+ Business quiet hours: `getAccountQuietHours()` / `setAccountQuietHours({ enabled, start: 'HH:mm', end: 'HH:mm', timezone })` (owner token, `PUT /users/me/quiet-hours`; a chat token gets `400`). The account window also silences the chat identity with the same e-mail, so the member `getQuietHours()` now returns `QuietHoursView`: the member's own window plus `account` (the linked business window when it is on, else `null`).
718
+
719
+ ### Business sign-in code (passwordless login)
720
+
721
+ Owners and teammates can log in with a 6-digit code emailed to them instead of a password. The request always answers the same way, so it never reveals whether an email has an account.
722
+
723
+ ```typescript
724
+ const api = LiveChatta.api();
725
+ await api.requestBusinessSignInCode('ada@acme.com'); // { expiresInSeconds: 600, resendInSeconds: 60 }
726
+ let res = await api.verifyBusinessSignInCode('ada@acme.com', '481920');
727
+ if ('require2fa' in res) res = await api.verifyBusinessTotp(res.pendingToken, authenticatorCode);
728
+ // The access token is now the owner token, so owner-console calls work straight away.
729
+ ```
730
+
731
+ Codes last 10 minutes and work once. Errors carry `code`: `SIGN_IN_CODE_INVALID` (the message says how many tries are left), `SIGN_IN_CODE_EXPIRED`, `SIGN_IN_CODE_LOCKED` (after 5 wrong tries — ask for a new code), `SIGN_IN_CODE_COOLDOWN` (wait 60 s between codes) and `SIGN_IN_CODE_RATE_LIMITED`. Android, iOS and Flutter have the same three methods.
732
+
733
+ ### Forgot and reset password
734
+
735
+ Every login door has the same pair (chatta #413). All public, never retried; the forgot call answers the same whether or not
736
+ the account exists. Codes are 8 characters (spaces and dashes ignored), last 30 minutes and work once; a reset signs out every
737
+ session of that account.
738
+
739
+ ```typescript
740
+ import { newPasswordProblem } from '@livechatta/sdk';
741
+
742
+ await api.requestBusinessPasswordReset('ada@acme.com'); // business / admin: POST users/forgot-password
743
+ await api.requestChatPasswordReset({ identifier: 'ada@acme.com', chatLinkCode }); // chat user: chatLinkCode is required
744
+ await api.requestLinkPasswordReset(linkCode, 'ada'); // the chat page's door, link from the path
745
+
746
+ const st = await api.getPasswordResetStatus(code); // { state: 'valid' | 'used' | 'expired' | 'invalid', audience?, purpose?, linkCode?, email? }
747
+ if (newPasswordProblem(pw, pw2)) showError(); // 'too-short' | 'too-long' | 'mismatch' (8–200 chars, must match)
748
+ const r = await api.resetChatPassword({ token: code, newPassword: pw, confirmPassword: pw2 }); // or resetBusinessPassword / resetLinkPassword
749
+ location.href = r.loginUrl; // { status, message, audience: 'business' | 'admin' | 'chat', loginUrl, signedOut }
750
+ ```
751
+
752
+ On the socket, `forgotPassword({ identifier, chatLinkCode })` (5/min per IP) and `resetPassword({ token, newPassword, confirmPassword })`
753
+ (10/min per IP) do the chat-user flow. Android, iOS and Flutter have the same seven REST methods with the fields as arguments.
754
+
755
+ ### Link and conversation modes
756
+
757
+ A **link mode** (`standard | support | creator | school | community | tech | public | private | webinar`) presets the link type, join rules, discovery and default conversations. A **conversation mode** (`standard | broadcast | announcement | qa | voice | support`) presets who posts in one group or channel; in `broadcast`, members reply in threads only.
758
+
759
+ ```typescript
760
+ import { EMAIL_REQUIRED, INVITE_ONLY, LiveChattaError } from '@livechatta/sdk';
761
+
762
+ const r = await api.setLinkMode(linkId, { mode: 'support', applyDefaults: true }); // owner: { linkType, joinPolicy, created }
763
+ await api.setConversationMode(conversationId, { mode: 'broadcast' }); // conversation admin or owner
764
+ sock.onConversationPermissionsUpdated((p) => setComposer(p.mode, p.membersCanSend));
765
+ await sock.startConversation({ senderId, type: ChatConversationType.CHANNEL, name: 'help', mode: 'qa', category: 'Text' });
766
+
767
+ const info = await api.getPublicLinkInfo(linkCode); // public: mode, joinPolicy
768
+ if (info.joinPolicy.inviteOnly) showSignIn();
769
+ try {
770
+ await api.joinLinkAsGuest(linkCode, { displayName, email: info.joinPolicy.emailRequired ? email : undefined });
771
+ } catch (err) {
772
+ if (err instanceof LiveChattaError && err.code === EMAIL_REQUIRED) askForEmail(); // 400
773
+ else if (err instanceof LiveChattaError && err.code === INVITE_ONLY) showSignIn(); // 403 (also join-new / join-exist)
774
+ }
775
+ ```
776
+
777
+ `createChatLink({ ..., mode })` (API key) and `createAccountChatLink({ ..., mode, modeOptions })` (owner token, `POST chats/links`) both apply the preset and return the link with `modeResult` (`LinkModeCreateResult`). When the preset fails the link is still created, with `modeResult.applied: false` and a `warning`: retry with `setLinkMode(linkId, { mode, applyDefaults: true })`. `modeOptions` (`LinkModeOptions`, the New link step 2 switches: support `topics` / `agentInbox` / `preChatEmail`, creator `threadReplies` / `communitySlowMode`, school `signInRequired`, community `membersCanCreate`, private `joinApproval`, webinar `registrationEmail`) is honoured on the owner route, and on the API-key route once chatta #412 merges (older servers ignore it there). Groups and channels started by members are refused on staff-only modes (`support`, `creator`, `school`, `private`, `webinar`) and when `settings.staffOnlyCreate` is on (`STAFF_ONLY_CREATE_MESSAGE`). Conversations carry `mode`, `category` (sidebar section such as "Text" / "Voice") and `audience: 'followers'` for a creator's followers-only room; joining a creator link follows the creator, and follow / unfollow adds you to or removes you from those rooms.
778
+
779
+ Link writes (`setLinkMode`, `setLinkEmbedDomains`, widget, discoverable, join policy, join requests) are for the owner and admin teammates: chat-member tokens and agents get **403**. `setConversationMode` answers 403 for non-admins, 400 when the conversation type can't use the mode and 404 for an unknown conversation. Team routes with a chat token and follow routes with a business token are 403 too.
780
+
781
+ ### Ask to join, channel preview, support teams and webhook deliveries
782
+
783
+ ```typescript
784
+ import { APPROVAL_OFF, LiveChattaError } from '@livechatta/sdk';
785
+
786
+ // Join card (public)
787
+ const { members, online, channels } = await api.getLinkChannels(linkCode); // ≤ 12 public channels, `live` voice rooms
788
+ const info = await api.getPublicLinkInfo(linkCode);
789
+ if (info.joinPolicy.inviteOnly && info.joinPolicy.approval) {
790
+ try {
791
+ const { status } = await api.requestToJoinLink(linkCode, { name, email, message }); // 'pending' | 'approved' | 'member'
792
+ if (status === 'member') showSignIn(); else if (status === 'approved') showJoinAsNew(email);
793
+ } catch (err) {
794
+ if (err instanceof LiveChattaError && err.code === APPROVAL_OFF) showInviteOnly(); // 403
795
+ }
796
+ }
797
+
798
+ // Owner console (owner token; chat tokens get 403)
799
+ await api.setLinkJoinPolicy(linkId, { approval: true }); // the resolved JoinPolicy
800
+ const page = await api.listJoinRequests(linkId, { status: 'pending', limit: 20 }); // { results, nextCursor, hasMore, pending }
801
+ await api.approveJoinRequest(linkId, page.results[0]._id); // or denyJoinRequest; they get an email
802
+
803
+ // Support group → named team (member token of a staff admin of the group)
804
+ const routing = await api.getSupportGroupTeam(conversationId); // { teamId, teams: [{ _id, name, memberCount }] }
805
+ await api.setSupportGroupTeam(conversationId, routing.teams[0]._id); // null stops routing
806
+ await api.setLinkInboxSettings(linkId, { topics: [{ label: 'Billing', teamId }] }); // topic-level routing, wins over assigneeId
807
+
808
+ // Webhook upkeep (owner token)
809
+ const rows = await api.getWebhookDeliveries(webhookId, { limit: 20 }); // [{ id, event, code, at, attempt, ok, canRetry }]
810
+ for (const r of rows) if (r.canRetry && r.id) await api.retryWebhookDelivery(webhookId, r.id); // { queued: true }
811
+ const { secret, hint } = await api.rotateWebhookSecret(webhookId); // shown once; queued retries use it
812
+
813
+ // Public gift store: public plans only; `currentPlanId` replaces the removed `ownerSubscription`
814
+ const store = await api.getGiftStoreData(linkCode);
815
+ ```
816
+
817
+ `getPublicLinkInfo().settings` is the public allowlist (`PublicLinkSettings`): join policy, agent inbox, pre-chat, business hours, topics as `{ id, label }`, SLA, layout, `allow*`, `maxMembers`, welcome message. Read `embedDomains`, `autoJoinConversationIds`, `discoverable`, `autoTranscribe` and `staffOnlyCreate` with the owner token. `settings.hideRunsOn: true` on `updateChatLink` hides "Runs on livechatta" on the join card while the plan has `allowWhiteLabel`.
818
+
819
+ Join error codes: `EMAIL_REQUIRED` (400), `SIGN_IN_REQUIRED` (403, guests off but members may sign in or join as new), `INVITE_ONLY` (403), `APPROVAL_OFF` (403, join-request), `LINK_FULL` (400), `ACCOUNT_EXISTS` (400), `HANDLE_TAKEN` (400, join-new with a used @handle). Admin console pages answer `ADMIN_NO_ACCESS` (403).
820
+
821
+ **1.2.1 (chatta #408, #409).** Link `settings` on create / update are an allowlist (`CHAT_LINK_SETTINGS_KEYS`: `maxMembers`, `allowAttachments`, `allowVoiceMessages`, `allowVideoMessages`, `allowMemberInvite`, `welcomeMessage`, `defaultLayout`, `hideRunsOn`; type `ChatLinkSettingsPatch`), and `updateChatLink` merges them key by key, so send only what changes. `listPublicConversations` returns public channels and groups only (no DMs, private or support groups, meetings) and answers 400 for an expired or disabled link. The console reads `GET chats/links`, `/:linkId`, `/:linkId/analytics`, `/:linkId/conversations` and `/:linkId/export/:exportId` are owner-only (403 for chat tokens). `inviteToHop(sessionId, chatUserIds)` (member token) rings people into a call over the socket and by incoming-call push and returns `{ ok, invited }`. Reactions, votes, raised hands and poll votes are rate-limited per user per session over 10 s (`HOP_RATE_LIMITS`: 20 / 20 / 6 / 10). Over the cap nothing is broadcast: `sendHopReaction`, `sendHopVote` and `raiseHand` resolve with `{ ok: false, error: 'RATE_LIMITED' }` (`HopRelayAck`, `HOP_RATE_LIMITED`); `hopPollVote` does not wait for the ack, so a capped vote is simply dropped. Co-hosts and inherited hosts now get `hop-lobby-waiting` too, including a burst for everyone already waiting when they become host.
822
+
823
+ ### Teams, followers, gifts, meeting guests and webinar recordings
824
+
825
+ ```typescript
826
+ // Owner console (owner token)
827
+ const { results: teams } = await api.listWorkspaceTeams();
828
+ const refunds = await api.createWorkspaceTeam({ name: 'Refunds', memberIds: [agentUserId] });
829
+ await api.updateWorkspaceTeam(refunds._id, { chatLinkId: null }); // null clears the link scope
830
+ await sock.createAutomation({ chatLinkId, name: 'Refunds', trigger: 'MESSAGE_CONTAINS',
831
+ triggerConfig: { keywords: ['refund'] }, action: 'ASSIGN_TEAM', actionConfig: { teamId: refunds._id } }); // round-robin
832
+ await api.inviteTeamMember({ firstName: 'Ada', username: 'ada@example.com', teamRole: 'AGENT', answerLinks: [linkId] });
833
+ await api.inviteChatUser({ firstName: 'Bo', email: 'bo@example.com', chatLinkId: linkId }); // { existed, emailed }
834
+
835
+ // Followers (member token); FOLLOWERS posts reach only the author's followers in that link
836
+ const f = await api.followMember(linkId, memberId); // { followers, isFollowing, followsYou, … }
837
+ await sock.createPost({ type: PostType.POST, memberId, content: 'Behind the scenes', visibility: 'FOLLOWERS' });
838
+
839
+ // Person-to-person gifts (minor units, USD cents)
840
+ const catalog = await api.getGiftCatalog(); // Coffee 300, Confetti 100
841
+ const checkout = await api.sendPeerGift({ conversationId, recipientId, giftKey: 'coffee', note: 'Thanks!' });
842
+ openBrowser(checkout.authorizationUrl);
843
+ const done = await api.verifyPeerGift(checkout.reference); // 'success' | 'pending'
844
+ const { balance, results } = await api.listReceivedGifts();
845
+ if (balance.availableMinor >= GIFT_PAYOUT_MIN_MINOR) await api.requestGiftPayout();
846
+
847
+ // Meetings: "Where" channel + email guests
848
+ const m = await sock.scheduleHopMeeting({ title: 'Kick-off', startAt, endAt, participantIds: [],
849
+ locationConversationId: channelId, guestEmails: ['guest@example.com'] }); // m.guestsInvited
850
+ await api.redeemMeetingGuestPass(code, guestToken); // ?guest= from the invite email
851
+ await api.joinMeetingFromChannel(message.hopMeeting!.meetingConversationId); // HOP_MEETING card "Join"
852
+ sock.onHopLobbyWaiting(({ userId, displayName }) => showAdmit(userId, displayName));
853
+
854
+ // Webinar recordings
855
+ if ((await api.getWebinarInfo(id)).hasRecording) await api.requestWebinarRecordingLink(id, email); // always { sent: true }
856
+ const rec = await api.getWebinarRecording(id, tokenFromEmail); // public; owners: getWebinarRecordingsAsOwner(id)
857
+
858
+ // Android inline Reply (public; the push's single-use token authorises it)
859
+ const r = await api.sendPushReply(push.replyToken, typedText, 'android-app'); // r.replyToken for a follow-up; 'ios-app' on iOS
860
+ ```
861
+
862
+ Messages can carry `peerGift` (`MessagePeerGift`) and, with `messageKind: 'HOP_MEETING'`, `hopMeeting` (`HopMeetingCard`). The inbox state gains `assignedTeam` / `assignedTeamName`. `UploadFileResult` types the per-file rows of `POST commons/upload/form/files?detailed=1` (the SDK does not wrap uploads). Signing in with a business sign-in code now also marks the email verified.
863
+
864
+ ### Where a message was sent from (`sentFrom`, 1.6.10)
865
+
866
+ Every new message carries `sentFrom`, the device class it was sent from. `sendPushReply(token, text, deviceHint?)` takes an optional `'ios-app'` or `'android-app'` hint (Kotlin, Swift and Dart take the same string); send it with a user agent that says Android or iPhone, or the reply is labelled `web`. It is reported by the client and checked against its user agent; informational only, not for authorization or audit. `api`, `bot` and `automation` are set by the server, and a client cannot claim them. Messages sent before it existed have none.
867
+
868
+ ```typescript
869
+ import { sentFromLabel, SENT_FROM_VALUES, type SentFrom } from '@livechatta/sdk';
870
+
871
+ const page = await api.getMessages(memberId, conversationId);
872
+ page.results.forEach((m) => console.log(m.sentFrom, sentFromLabel(m.sentFrom))); // 'ios-app' 'iPhone app'
873
+ const info = await api.getMessageInfo(conversationId, messageId); // info.sentFrom too
874
+ ```
875
+
876
+ | Value | Meaning |
877
+ |---|---|
878
+ | `ios-app`, `android-app`, `desktop-app` | The LiveChatta app on that device |
879
+ | `mobile-web` | A phone or tablet browser |
880
+ | `web` | A desktop browser (also the default when the device is unclear) |
881
+ | `api` | Sent with an API key (`chats/messages/send`, the SDK HTTP API or an SDK socket); only API-key auth can set it |
882
+ | `bot`, `automation` | Posted by @chatta or another bot, or by an automation rule |
883
+
884
+ Sends made with an API key (`chats/messages/send`) are `api` automatically, so there is nothing to pass. A login-based client send (socket or REST) is classed from its device hint and user agent and is never `api`. On Kotlin, Swift and Dart read it from the message with `LiveChattaSentFrom.of(message)` and show it with `LiveChattaSentFrom.label(value)`. The message webhook (`message:send`) payload carries `sentFrom` too, and conversation exports include it (a `sentFrom` field in JSON and a `sentFrom` CSV column). It is never a raw user agent, IP address or device id.
885
+
886
+ ### Plans, custom plan requests and the feature store
887
+
888
+ ```typescript
889
+ import { planAccessError, SIGN_IN_REQUIRED, LiveChattaError } from '@livechatta/sdk';
890
+
891
+ // Public
892
+ const plans = await api.listPlans(); // public tiers (+ your CUSTOM plan with an owner token)
893
+ const store = await api.listStoreFeatures(); // add-ons and AI credit packs, USD per day
894
+ await api.requestCustomPlan({ contactName: 'Ada', contactEmail: 'ada@acme.com', company: 'Acme',
895
+ expectedChatLinks: 40, membersPerLink: 500, features: ['SSO', 'WHITE_LABEL'] }); // { id, status: 'NEW' }
896
+
897
+ // Owner token
898
+ await api.requestCustomPlanAsOwner({ contactName: 'Ada', contactEmail: 'ada@acme.com' });
899
+ const { request } = await api.getMyLatestPlanRequest(); // NEW | CONTACTED | QUOTED | ASSIGNED | CLOSED
900
+ try {
901
+ const checkout = await api.subscribeToPlan({ planId, billingCycle: 'MONTHLY' });
902
+ openBrowser(checkout.authorizationUrl);
903
+ await api.verifySubscription(checkout.reference); // or { status: 'pending' } for bank transfers
904
+ } catch (err) {
905
+ const why = planAccessError(err); // 'not-found' (404 on getPlan) | 'not-available' | 'team-activated' | null
906
+ if (why === 'team-activated') showContactSupport();
907
+ }
908
+ const [sub] = await api.listMySubscriptions();
909
+ const change = await api.changePlan(sub._id, { planId: cheaperId, billingCycle: 'MONTHLY', scheduleForPeriodEnd: true });
910
+ if ('scheduled' in change) showBanner(change.message); else openBrowser(change.authorizationUrl);
911
+ await api.purchaseFeature({ featurePricingId: store[0]._id, durationDays: 30 }); // then verifyFeaturePurchase(reference)
912
+ await api.setLinkEmbedDomains(linkId, ['https://acme.com', 'https://*.acme.com']); // [] = any site may frame the chat
913
+
914
+ // Member token (or owner): gifts to the workspace, and what it owns
915
+ await api.giftWorkspaceFeature({ featurePricingId, durationDays: 7 }); // then verifyWorkspaceFeatureGift(reference)
916
+ await api.giftPlan({ planId, billingCycle: 'MONTHLY' }); // then verifyPlanGift(reference)
917
+ const owned = await api.listMyFeaturePurchases();
918
+ ```
919
+
920
+ The plan-access guard (chatta #363) refuses hidden, inactive, template and other clients' plans. Since chatta #396 the bodies are
921
+ `{ message, code }`: `404 PLAN_NOT_FOUND` (a missing plan, or any plan you may not see), `400 PLAN_NOT_AVAILABLE` and
922
+ `400 PLAN_TEAM_ACTIVATED` (the plan costs $0 for that cycle). `planAccessError()` reads the code (constants `PLAN_NOT_FOUND`,
923
+ `PLAN_NOT_AVAILABLE`, `PLAN_TEAM_ACTIVATED`) and falls back to the messages older servers send. `listPlans` / `getPlan` send the
924
+ owner token when one is set, so you see your own CUSTOM plan. `PlanSubscription.scheduledChange` is a typed sub-document.
925
+ Only a downgrade between public tiers may use `scheduleForPeriodEnd`. Checkouts and plan requests are never retried on 5xx.
926
+ Android, iOS and Flutter have the same methods; their error-code objects add the three messages as constants.
927
+
928
+ Messages from `sock.getMessages({ ..., compactReceipts: '1' })` carry only your own `readBy` / `deliveredTo` entry plus
929
+ `readCount` / `deliveredCount` (chatta DB-10); use `getMessageInfo` for the full "seen by" list.
930
+
931
+ Shipped in chatta #385: guest joins refused for sign-in links answer `403 SIGN_IN_REQUIRED`; `getWebinarRecording` sends the
932
+ token as `X-Recording-Token`; `getPublicLinkInfo().settings` holds the public allowlist only. Mention lanes and search
933
+ (`handles: ['admin', 'support']`, `q`) work on `getAdminMentionsAsOwner` (owner token) and, since chatta #408, on the API-key `getAdminMentions`.
934
+ `inviteTeamMember` returns the allowlisted teammate row (`TeamMemberView`: `_id, firstName, lastName, username, handle, teamRole,
935
+ answerLinks, invitePending, invitedAt, createdAt`).
936
+
937
+ ```typescript
938
+ try { await api.joinLinkAsGuest(code, { displayName }); }
939
+ catch (err) { if (err instanceof LiveChattaError && err.code === SIGN_IN_REQUIRED) showSignIn(); }
940
+ ```
941
+
942
+ ### LiveFlex, stickers, @chatta money, missed calls and support access (1.5.0)
943
+
944
+ LiveFlex is the USD balance members and businesses hold (routes still say `/wallet`). A member token reaches the member's own LiveFlex; an owner token reaches the business's. Amounts are US cents.
945
+
946
+ ```typescript
947
+ const lf = await api.getLiveFlex(); // balance, masked payout details, limits, hold, frozen
948
+ await api.listLiveFlexTransactions({ kind: 'fund' });
949
+ const top = await api.fundLiveFlex({ amountMinor: 2000 }); // open top.authorizationUrl, then verifyLiveFlexFunding(top.reference)
950
+ await api.sendLiveFlex({ recipientId, amountMinor: 400, note: 'Lunch', idempotencyKey: crypto.randomUUID() });
951
+ await api.setLiveFlexPayoutBank({ bankCode: '058', accountNumber: '0123456789' }); // a 6-digit code is emailed
952
+ await api.confirmLiveFlexPayout('123456'); // then withdrawals wait out the hold (24 h by default)
953
+ await api.withdrawLiveFlex({ amountMinor: 1500, method: 'bank', expectedTotalMinor: 1523 }); // $10 minimum; the bank gets 15.00, the 1.5% fee (max $2) goes on top, so 15.23 leaves your LiveFlex (to a crypto address add the flat network/provider fee, `providerFeeMinor`, 3.00 by default)
954
+ // Owner: let LiveChatta support in for a while (view or act), or turn it off
955
+ await api.setStaffAccessGrant({ mode: 'view', hours: 24 }); await api.revokeStaffAccessGrant();
956
+
957
+ // Socket: platform stickers (anyone uploads, everyone can search and send)
958
+ const { results } = await sock.stickersSearch({ q: 'party' });
959
+ await sock.stickerUpload({ image: dataUri, name: 'happy dance' });
960
+ sock.sendMessage({ conversationId, senderId, referenceId, sticker: { id: results[0].id } });
961
+ // @chatta money: typing "@chatta send $4 to @ada" gets a private card; press its buttons with chattaMoneyConfirm
962
+ sock.onChattaMoneyCard((card) => render(card));
963
+ await sock.chattaMoneyConfirm({ intentId: card.intentId, actionId: 'confirm', conversationId });
964
+ sock.onCallLogged((e) => { if (e.missed) badgeMissedCall(e); });
965
+ sock.onLinkSettingsUpdated((link) => applyLinkSettings(link));
966
+ ```
967
+
968
+ Money events (send, receive, top-up, withdrawal, gifts) also arrive as in-app notifications with `data.kind: 'liveflex' | 'gift'` (`LiveFlexNoticeData`). Kotlin, Swift and Dart use the same names. The CLI gains `liveflex [history|fund|send|withdraw|request|split|standing|pots|refund|paylink|receipt|statement]` and `security grant [on|off]`.
969
+
970
+ Requests, splits, standing payments, group pots, refunds, pay links and PDF receipts (1.7.0, chatta P-N9) use the same LiveFlex routes. A request never moves money; the payer taps Pay and their own PIN, holds and limits apply. Money is not available in channels shared with another workspace. `api.blockLiveFlexRequester(id)` declines a waiting request and stops new ones from that person (also `chatta liveflex request block <id>`). Receipt and statement links work once, for 10 minutes, and only for the member they were made for; the CLI prints them only with `--show-url`, and takes secrets with `--member-token-stdin` and `--pin-stdin`.
971
+
972
+ ```ts
973
+ const asked = await api.createLiveFlexRequest({ conversationId, handle: 'bola', amountMinor: 500000, note: 'lunch' }); // a live card appears in the chat
974
+ await api.payLiveFlexRequest(asked.id, { pin: '482915' }); // the payer's own call, as a member
975
+ await api.createLiveFlexSplit({ conversationId, totalMinor: 24000, payers: [{ handle: 'bola' }, { tag: 'kaka' }], includeMe: true });
976
+ await api.createLiveFlexStanding({ handle: 'bola', amountMinor: 1000, interval: 'month', maxRuns: 6, pin: '482915' }); // confirmed once
977
+ await api.refundLiveFlexTransaction(txnId, { amountMinor: 500, key: crypto.randomUUID() });
978
+ const { pdfUrl } = await api.getLiveFlexStatementLinks('2026-10'); // signed, 10 minutes, opens only for the signed-in person (send your bearer token)
979
+ socket.onMoneyCardUpdate((card) => render(card));
980
+ ```
981
+
982
+ ### Links, notes, starred people, flags and call history (1.4.0)
983
+
984
+ ```typescript
985
+ const chk = await api.checkLinkCode('acme-help'); // { code, available, reason?, suggestions? }
986
+ await api.createChatLink({ name: 'Acme', code: 'acme-help' }); // LINK_CODE_* errors: isLinkCodeError(err)
987
+ await api.updateLinkTheme(linkId, { welcomeImageUrl, footerText });
988
+ await api.setLinkWhoCanJoin(linkId, 'anyone');
989
+ await api.setLinkCustomDomain(linkId, 'chat.acme.com'); await api.verifyLinkCustomDomain(linkId);
990
+ await api.getLinkOverview(linkId); await api.wipeLinkMessages(linkId);
991
+ // Member token
992
+ await api.setMyNote(conversationId, 'Renewal in March'); await api.setConversationPinned(conversationId, true);
993
+ await api.starPerson(memberId); const { ids } = await api.listStarredIds();
994
+ const calls = await api.listCallHistory({ limit: 20 }); // every call, rows carry declined + participantCount
995
+ const missed = await api.listCallHistory({ view: 'missed' }); // or 'history' (calls you made or joined)
996
+ // Account and billing
997
+ const me = await api.getAccountProfile(); // includes flags
998
+ await api.createApiKey({ name: 'Site', allowedOrigins: ['https://acme.com'] }); // other origins: 403 (isApiKeyOriginError)
999
+ const fresh = await api.rotateApiKey(keyId); // 1.5.7: new secret in fresh.key (shown once); the old key stops
1000
+ await api.revokeApiKey(keyId); const usage = await api.getApiKeyUsage(keyId, '30d'); // { labels, requests, errors }
1001
+ await api.listPendingTransfers(); await api.purchaseExtraSeats({ seats: 2, paymentMethod: 'card' });
1002
+ ```
1003
+
1004
+ Kotlin, Swift and Dart use the same method names (Swift labeled arguments, Dart a named `query:`). The `chatta` CLI gains `links code|modes|who-can-join|domain|theme|overview|wipe`, `billing pending|storage-renew` and `keys list|create|update`.
1005
+
1006
+ ### Trials, renewals, bank transfer, storage, gift earnings and staff access (1.3.0)
1007
+
1008
+ ```typescript
1009
+ import { STORAGE_LIMIT, LiveChattaError } from '@livechatta/sdk';
1010
+
1011
+ // Owner token
1012
+ const { eligible, trial } = await api.getTrialStatus(); // trial: { planName, daysLeft, hasCard, … } | null
1013
+ if (eligible) await api.startTrial({ planId, billingCycle: 'MONTHLY' }); // Plan.trialDays > 0, one per account, no card
1014
+ await api.subscribeToPlan({ planId, billingCycle: 'MONTHLY', paymentMethod: 'bank_transfer' }); // or 'card' (default)
1015
+ const { renewal } = await api.getRenewalStatus(); // { state: current | due-soon | due | grace | lapsed, … } | null
1016
+ if (renewal && renewal.state !== 'current') {
1017
+ const pay = await api.renewSubscription(renewal.subscriptionId, { paymentMethod: 'bank_transfer' });
1018
+ openBrowser(pay.authorizationUrl); // then verifySubscription(pay.reference)
1019
+ }
1020
+ await api.useBankTransferRenewals(); // stop auto-charging the card for every active plan
1021
+ const earnings = await api.getOwnerGifts({ limit: 20 }); // totals + per-gift platformFeeBps / feeMinor / netMinor
1022
+ const access = await api.listStaffAccess(); // when LiveChatta staff viewed ('view') or acted ('act')
1023
+
1024
+ // Member or owner token
1025
+ const usage = await api.getStorageUsage(); // { monthBytes, capGB, pct, remainingBytes, state, resetsAt, … }
1026
+ try { await sock.sendMessage({ ...payload, attachments }); }
1027
+ catch (err) { if (err instanceof LiveChattaError && err.code === STORAGE_LIMIT) showFull((err.details as { resetsAt: string }).resetsAt); }
1028
+ ```
1029
+
1030
+ Storage (chatta #420): plan `maxStorageGB` is a **monthly** upload allowance for the whole workspace (0 unlimited, -1 no uploads), plus active `STORAGE` add-ons from the feature store. It starts fresh on the subscription's billing day; deleting files does not free this month's allowance. Uploads past it answer `400 { code: 'STORAGE_LIMIT', resetsAt }` (the socket ack carries the same message).
1031
+
1032
+ Subscriptions carry `paymentChannel` (`card` | `bank_transfer`), `renewalNotices`, `lastChargeAttemptAt`, `isTrial`, `trialStartedAt`, `trialEndsAt` and `trialExtensions`; plans carry `trialDays`. Webhooks: `subscription:renewed` adds `channel` for renewal checkouts (`SubscriptionRenewedWebhookData`), and `subscription:failed` sends `reason: 'transfer_unpaid'` and `pausedAt` when a transfer plan pauses (`SubscriptionFailedWebhookData`).
1033
+
1034
+ Gifts (chatta #416): members never see the platform fee. `getGiftCatalog()` items are `{ id, key, name, emoji, description, priceMinor, currency }` and `listReceivedGifts()` rows have `amountMinor` and `netMinor` only; owners read fees on `getOwnerGifts()`.
1035
+
1036
+ Page caps (chatta #417, #427): the server caps `limit` at 100 for REST conversation lists (default 10) and at 40 for socket `all-conversations` (default 40, `SIDEBAR_PAGE_SIZE`), 50 for messages (REST and `all-messages`), 20 for stories and cursor lists such as staff access and gift earnings, and 100 for billing history, recent signups and gift purchases. A larger `limit` returns the capped page plus a cursor; 0, negative or junk falls back to the route default (`SERVER_PAGE_CAPS`).
1037
+
1038
+ ### Unread badges with 40-row pages
1039
+
1040
+ Since chatta #427 the socket list sends 40 rows per page, so adding up `unreadCount` over the rows you loaded undercounts. Use the server totals instead:
1041
+
1042
+ 1. The first All-lane page (no cursor, search, `chatConversationByTypes` or lookup filter) carries `unreadTotals: { total, active, archived, people, groups, channels, saved }` (`SidebarUnreadTotals`). It covers every conversation you have in the link.
1043
+ 2. Keep the count for the rows you have **not** loaded (`remainder`) apart from the live `unreadCount` of the rows you have. Badge = `remainder` + the sum over loaded rows. When a row loads, move its `unreadCount` out of the remainder.
1044
+ 3. Update loaded rows in place from `onUnreadCountUpdate` / `onConversationRead`. For an event on a row you have not loaded, ask `getUnreadTotals({ excludeConversationIds: loadedIds })` (max 1000 ids): the answer covers only the rest. Debounce it (the web app waits 800 ms).
1045
+ 4. If `unreadTotals` is missing (older server), fall back to summing loaded rows.
1046
+
1047
+ ```typescript
1048
+ const first = await sock.getConversations();
1049
+ const rows = new Map(first.conversations.results.map((r) => [r.conversation._id, r]));
1050
+ const loadedSum = () => [...rows.values()].reduce((n, r) => n + (r.unreadCount || 0), 0);
1051
+ let remainder = first.unreadTotals ? first.unreadTotals.total - loadedSum() : 0; // older server: 0
1052
+ const badge = () => remainder + loadedSum();
1053
+
1054
+ // An event for a row you have not loaded (debounce ~800 ms): re-ask for the rest only.
1055
+ const resync = async () => {
1056
+ const { unreadTotals } = await sock.getUnreadTotals({ excludeConversationIds: [...rows.keys()].slice(0, UNREAD_TOTALS_MAX_EXCLUDE) });
1057
+ remainder = unreadTotals.total;
1058
+ };
1059
+
1060
+ // Deep link: your own row for a conversation code, even when it is not on a loaded page.
1061
+ const hit = await sock.getConversations({ chatConversationByCodes: code, limit: '1' });
1062
+ ```
1063
+
1064
+ The hosted chat already does this: `CHATTA_APP:onUnreadChange` and `livechatta:unread` carry the full total.
1065
+
1066
+ ### Exports, leaving a link, polls, stories and locked chats
1067
+
1068
+ ```typescript
1069
+ // Member export: scope 'mine' (any member) or 'all' (default, admins); CSV (default) | PDF | JSON | ZIP.
1070
+ const job = await api.exportConversationAsMember(conversationId, {
1071
+ format: 'ZIP', scope: 'mine', includeMedia: false, from: '2026-11-01', to: '2026-11-10', emailMe: false,
1072
+ });
1073
+ const st = await api.getMemberExportStatus(conversationId, job.exportId); // poll until COMPLETED, then st.downloadUrl
1074
+ await api.exportConversationAsOwner(conversationId, { email: 'ops@example.com', format: 'ZIP', from: '2026-11-01' }); // owner
1075
+
1076
+ await api.leaveMyLink(linkId); // member: { left } conversations, history kept
1077
+ await api.claimGuest({ guestToken }); // member: fold the no-email guest this device held into your account
1078
+ await api.setMyLinkNotify(linkId, 'mentions'); // member: per-link push level (all / mentions / off)
1079
+ await api.listLinkMembers(chatLinkId, 3); // member: teammates on the link, online first
1080
+ // Stickers: sock.sendMessage({ conversationId, senderId, referenceId, sticker: { shortcode: 'party' } })
1081
+ await api.testAutomationKeywords(chatLinkId, ['refund']); // owner: { matched, scanned, total, capped, keywords }
1082
+
1083
+ await sock.sendMessage({ conversationId, senderId, referenceId, messageKind: 'POLL',
1084
+ question: 'Lunch?', options: [{ text: 'Jollof' }, { text: 'Suya' }], anonymous: true });
1085
+ // Anonymous polls arrive with poll.anonymous and options[].count; options[].votes holds only your id (or []).
1086
+
1087
+ await sock.createPost({ type: PostType.STORY, memberId, content: 'Back at 3', background: 'lagoon', allowReplies: false });
1088
+
1089
+ const denial = parsePermissionDenial(err); // a non-admin send to a locked conversation → { action: 'locked' }
1090
+ ```
1091
+
1092
+ Automations gain `REPLY_CANNED` (`actionConfig.cannedId`) and `ASSIGN_TEAM` (`actionConfig.assigneeId`) and read-only `runWeek` / `runWeekCount`. Webhooks carry read-only `recentDeliveries` (`{ ok, code, at }`, the last 40) and `statsHour` (`{ h, ok, fail }`, 24 h). Chat-user `notifyMatrix.<category>.email` switches the email digest. A reply to a post with replies off fails with `POST_REPLIES_OFF_MESSAGE`. The external `exportChat` accepts `format: 'ZIP' | 'JSON'`, but only the owner route (`exportConversationAsOwner`) takes `includeMedia` / `from` / `to`.
1093
+
1094
+ ### Guest join, online count and "account exists"
1095
+
1096
+ `POST /in/:code/join-guest` is the one-step guest join (name + optional email) and returns the same session as join-new. Both join-new and join-guest answer `400` with `code: 'ACCOUNT_EXISTS'` when the email already has an account on this business ("You already have an account with this email. Sign in to continue."): switch to your sign-in form, which calls join-exist (the SDK has no join-new / join-exist wrapper). A full link answers `400 LINK_FULL`.
1097
+
1098
+ ```typescript
1099
+ import { LiveChattaError, ACCOUNT_EXISTS, LINK_FULL } from '@livechatta/sdk';
1100
+
1101
+ const { online } = await api.getLinkOnlineCount(linkCode); // public: "Live now · 12 online"
1102
+ try {
1103
+ const session = await api.joinLinkAsGuest(linkCode, { displayName: 'Ada', email }); // 2–30 chars, email optional
1104
+ api.setMemberToken(session.accessToken);
1105
+ } catch (err) {
1106
+ if (err instanceof LiveChattaError && err.code === ACCOUNT_EXISTS) showSignIn(email); // then join-exist
1107
+ else if (err instanceof LiveChattaError && err.code === LINK_FULL) showSpaceFull();
1108
+ else throw err;
1109
+ }
1110
+ ```
1111
+
1112
+ ### Full and paused links, scheduled "Send now", status and webhook tests
1113
+
1114
+ A link at its member cap answers join / join-exist with `400` and `code: 'LINK_FULL'` (message: "Acme Support has reached its 50-member limit. Try again later or contact the host."); compare `err.code` (or `serverErrorCode(body)`) with `LINK_FULL` and show the "This space is full" state. A paused link (`410`, `state: 'disabled'`) can take an email for "Notify me when it reopens".
1115
+
1116
+ ```typescript
1117
+ import { LINK_FULL, WEBHOOK_TEST_EVENT } from '@livechatta/sdk';
1118
+
1119
+ await api.notifyWhenLinkReopens(linkCode, 'ada@example.com'); // public, 5/min; 400 if the link isn't paused
1120
+ await api.sendScheduledMessageNow(messageId); // member token; { queued: true }, delivered within a minute
1121
+ await api.subscribeToStatusUpdates('ops@example.com'); // public status page emails, { subscribed: true }
1122
+ await api.unsubscribeFromStatusUpdates(email, token); // token from the email's unsubscribe link
1123
+
1124
+ const r = await api.testWebhook(webhookId); // API key; { ok, status, durationMs, error }
1125
+ if (!r.ok) console.warn(`Webhook test failed: ${r.error}`); // your endpoint gets event WEBHOOK_TEST_EVENT ('webhook.test')
1126
+
1127
+ const info = await api.getWebinarInfo(conversationId); // public: state, registeredCount, maxAttendees, isFull, joinPath
1128
+ await api.registerForWebinar(conversationId, { name, email, company, wantsRecording: true, waitlist: info.isFull });
1129
+ ```
1130
+
1131
+ ### Owner console: link list, account preferences, automations
1132
+
1133
+ ```typescript
1134
+ const expiring = await api.listAccountChatLinks({ chatLinkExpiringDays: '7' }); // owner token; ACTIVE links expiring within 7 days
1135
+ await api.testWebhookAsOwner(webhookId); // owner twin of testWebhook()
1136
+
1137
+ await api.updateAccountProfile({ preferences: { // owner token, merged by key
1138
+ notifyTopics: { slaBreach: true, productNews: false },
1139
+ language: 'fr', translateIncomingTo: 'off', // 'off' turns translation off
1140
+ soundPreferences: { mention: 'chime', message: 'gentle' },
1141
+ } });
1142
+
1143
+ // Chat users: per-category push / sound (a missing value means on).
1144
+ await api.updateChatUserProfile({ preferences: { notifyMatrix: { dms: { push: true, sound: false }, system: { push: false } } } });
1145
+
1146
+ // Link default layout for group / channel views. Settings merge key by key (chatta #408): send only what changes.
1147
+ await api.updateChatLink(linkId, { settings: { defaultLayout: 'lines' } });
1148
+
1149
+ // Keyword chips and up to 3 more steps after the primary action.
1150
+ await sock.createAutomation({ chatLinkId, name: 'Refunds', trigger: 'MESSAGE_CONTAINS',
1151
+ triggerConfig: { keywords: ['refund', 'chargeback'] }, action: 'SEND_MESSAGE', actionConfig: { message: 'On it' },
1152
+ extraActions: [{ action: 'TAG_USER', actionConfig: { tag: 'billing' } }] });
1153
+ ```
1154
+
1155
+ ### GIF search
1156
+
1157
+ ```typescript
1158
+ // Member or owner token. With GIF search off, config says enabled: false and the other routes answer 404.
1159
+ const cfg = await api.getGifConfig(); // { enabled, providers, rating, providerLabel }
1160
+ const page = await api.searchGifs({ q: 'well done' }); // { results, nextCursor, hasMore, source, fallback, hasProviders, providerLabel, switched }
1161
+ const more = await api.searchGifs({ q: 'well done', nextCursor: page.nextCursor! });
1162
+ const hot = await api.trendingGifs();
1163
+ const ours = await api.searchGifs({ q: 'smile', source: 'livechatta' }); // the LiveChatta pack; switched: true when a provider answered instead
1164
+ const theirs = await api.trendingGifs({ source: 'provider' });
1165
+ // A provider that is off, down or has no match is covered by the LiveChatta GIFs (source: 'default').
1166
+ const gif = page.results[0]; // { id, provider, url, previewUrl, width, height, rating, attribution? }
1167
+ await sock.sendMessage({ conversationId, senderId, referenceId, gif: { provider: gif.provider, id: gif.id } });
1168
+ await api.registerGifShare({ provider: gif.provider, id: gif.id, q: 'well done' });
1169
+ await api.reportGif({ provider: gif.provider, id: gif.id, reason: 'spam' }); // sexual | violent | hateful | spam | other
1170
+ ```
1171
+
1172
+ `source` is `'livechatta'` (the 100+ LiveChatta GIFs) or `'provider'`; leave it out and the provider leads. Use `hasProviders` and `providerLabel` to draw a second tab, and `switched` to follow a pack search that handed over to the provider. Show `attribution` ("via GIPHY") when it is set. Kotlin, Swift and Dart have the same methods, with `searchGifsTyped`, `trendingGifsTyped`, `getGifConfigTyped`, `registerGifShareTyped` and `reportGifTyped` returning typed models. CLI: `chatta gifs search <query> | trending`.
1173
+
1174
+ ### Shared channels between workspaces
1175
+
1176
+ ```typescript
1177
+ // Member token only (a chat member's sign-in). Every call names `chatLinkId`, the workspace you are signed in to.
1178
+ // Needs the Flash Pro, Orbit or Custom plan on both sides. Changes are never retried.
1179
+ const { sharedChannel, inviteToken, inviteUrl } = await api.inviteSharedChannel({ chatLinkId, conversationId }); // host owner or admin; no partnerLinkCode = single-use link, shown once
1180
+ await api.inviteSharedChannel({ chatLinkId, conversationId, partnerLinkCode: 'beta-studio', expiresInHours: 48 }); // or invite a workspace by its link code
1181
+ const preview = await api.previewSharedChannelInvite(token); // { hostName, channelName, invitedByName, expiresAt }; does not use it up
1182
+ await api.acceptSharedChannel(sharedChannelId, { chatLinkId, audience: 'ALL' }); // partner owner or admin; works once
1183
+ await api.acceptSharedChannelByToken({ chatLinkId, audience: 'PICKED', memberIds, token }); // the single-use link
1184
+ const pick = await api.listSharedChannelMembers({ chatLinkId, q: 'ada' }); // your people to pick: name and handle only
1185
+ await api.updateSharedChannelMembers(sharedChannelId, { chatLinkId, audience: 'ALL' });
1186
+ const { results, nextCursor } = await api.listSharedChannels({ chatLinkId }); // live and ended in the last 30 days
1187
+ const shares = await api.getConversationSharedChannels(conversationId, { chatLinkId }); // the host's view of one channel
1188
+ const perms = await api.getSharedChannelPermissions(conversationId, { chatLinkId }); // { side, canRemoveMessages, canRemoveMembers, externalIds }
1189
+ await api.endSharedChannel(sharedChannelId, { chatLinkId }); // host removes the partner, partner leaves, or either cancels or declines
1190
+ const audit = await api.getSharedChannelAudit(sharedChannelId, { chatLinkId }); // your own workspace's activity log
1191
+ await api.removeSharedChannelMember({ chatLinkId, conversationId, memberId }); // host only; they stay out if the channel is shared again
1192
+ await api.removeSharedChannelMessage({ chatLinkId, conversationId, messageId });
1193
+ await api.openSharedDirect({ chatLinkId, conversationId, memberId }); // needs allowSharedDms on both links
1194
+ await ownerApi.linkChatUserToAccount({ accountId, chatUserId }); // owner token: bind a teammate so they count as staff
1195
+
1196
+ sock.onSharedChannelInvite((e) => {}); // owner and admins: another workspace invited yours
1197
+ sock.onSharedChannelUpdated((e) => { if (isSharedChannelBadgeEvent(e)) { /* e.sharedWith: names for the badge */ } });
1198
+ ```
1199
+
1200
+ People of another workspace are masked. A shared conversation never carries their `email`, `phone`, `mobile`, `accountId` or workspace owner id, and `username` is their @handle. Model them as `SharedParticipant`, label them with `sharedParticipantLabel(p)` (display name, then handle, then first and last name; any value shaped like an email or a phone number is skipped, and the label falls back to `Member`) and do not assume `username` is set. `Conversation.sharedWith` is the "shared with" badge (`isSharedConversation(c)`); an entry with `ended: true` is the read-only copy a partner keeps after the share ended (`isSharedArchive(c)`). Bots, LiveFlex and @chatta money are refused in shared channels, so hide those entries there. `ChatLinkSettingsPatch.allowSharedDms` turns on direct messages with partners.
1201
+
1202
+ Kotlin, Swift and Dart have the same methods (`inviteSharedChannel`, `listSharedChannels`, `acceptSharedChannel` and the rest), each with a `*Typed` twin, plus `onSharedChannelInvite` and `onSharedChannelUpdated`. A list the server sends bare (`getConversationSharedChannels`) arrives as `{ results }` there. CLI: `chatta shared list | invite | preview | accept | audience | members | leave | channel | permissions | audit | dm | remove-member | remove-message | link-account`.
1203
+
1204
+ Isolated workspace: the account owner turns it on per link, and no LiveFlex send, request, split, new shared channel, shared DM or account link crosses that link in either direction (your other links count as outside). It fails closed on the server; withdrawals still work, and shares that already exist stay until they end or expire.
1205
+
1206
+ ```typescript
1207
+ await ownerApi.updateChatLink(linkId, { settings: { isolated: true } }); // account owner only (a team admin or API key gets 403); default off
1208
+ // A blocked send, request or new shared channel fails with code WORKSPACE_ISOLATED (403); LiveFlexView.isolated says the link is isolated.
1209
+ ```
1210
+
1211
+ ### Incoming webhooks: post into a conversation from any tool
1212
+
1213
+ ```typescript
1214
+ // API key. A secret URL per group or channel posts a message as an app, like Slack.
1215
+ // Needs a plan with incoming webhooks (Pulse, Flash Pro, Orbit, Custom). Create and regenerate are never retried.
1216
+ const hook = await api.createIncomingWebhook(conversationId, { name: 'Deploys', botName: 'CI' });
1217
+ store(hook.url); // https://<host>/hooks/in/lhk_… shown ONCE: it is the only credential
1218
+ const { results } = await api.listIncomingWebhooks(conversationId, { status: 'all' }); // never the secret; tokenHint = last 4 characters
1219
+ await api.updateIncomingWebhook(conversationId, hook.id, { name: 'Prod deploys' });
1220
+ const fresh = await api.regenerateIncomingWebhook(conversationId, hook.id); // the old URL answers 404 at once; fresh.url is new
1221
+ await api.revokeIncomingWebhook(conversationId, hook.id); // the URL answers 404 for good; old messages stay
1222
+
1223
+ // Posting needs no key, only the URL. 150 a minute per URL (a sliding window, so a short burst works), more per address
1224
+ // and workspace on bigger plans, 64 KB per body. A 429 carries details.retryAfter.
1225
+ await postIncomingWebhook(hook.url, { text: 'Deploy *finished*', username: 'CI', icon_url: 'https://example.com/ci.png' });
1226
+ ```
1227
+
1228
+ Messages a hook posts arrive as normal messages with `sentFrom: 'api'` and `viaWebhook: { hookId, name, iconUrl }` (the `MessageViaWebhook` on `Message`): show that name and picture, not the app user's.
1229
+
1230
+ Only the account owner, team admins and conversation admins (or members, when the conversation allows it) can manage hooks; the API key acts as the account owner. Hooks work in groups and channels, not in 1:1 chats, meetings or shared channels, and a locked conversation or a disabled or expired link refuses posts (403 or 410). Messages go through the normal send path, so limits, unread counts, notifications and moderation apply. Kotlin, Swift and Dart have the five management methods with `*Typed` twins; post to the URL with your own HTTP client. CLI: `chatta hooks list | create | rename | regenerate | revoke | send`.
1231
+
1232
+ ### Calendar sync, activity and categories (1.7.2)
1233
+
1234
+ ```typescript
1235
+ // Member token (a chat user's own session). Native apps pass native: true and redeem the one-time code from livechatta://calendar-sync/done?code=
1236
+ const status = await api.getCalendarSyncStatus(); // { enabled, providers, connections }
1237
+ const { authUrl } = await api.connectCalendar('google', { native: true });
1238
+ try { await api.completeNativeCalendarConnect(code); }
1239
+ catch (e) { if (e.code === CALENDAR_ACCOUNT_MISMATCH || e.code === CALENDAR_SIGNIN_EXPIRED) { /* ask the user to try again */ } }
1240
+ await api.setCalendarShareBusy('google', true); // busy times only, never titles
1241
+ const busy = await api.getCalendarBusy({ userIds, from, to }); // up to 20 members, a window of at most 14 days
1242
+ socket.onHopMeetingUpdated(({ conversationId, startAt }) => { /* a connected calendar moved the meeting */ });
1243
+ ```
1244
+
1245
+ Kotlin, Swift and Dart have the same methods (`getCalendarSyncStatusTyped` and `getCalendarBusyTyped` return typed models). The CLI has no member credential, so these routes are SDK-only.
1246
+
1247
+ ### Meetings, webhook listening and typed models (1.7.0)
1248
+
1249
+ ```typescript
1250
+ // Owner token: schedule, list and cancel meetings on a link. Invitees (1 to 70 emails or member ids) are emailed.
1251
+ const made = await api.scheduleMeeting(
1252
+ { linkId, title: 'Standup', startAt: '2026-12-01T15:00:00.000Z', durationMinutes: 30, invitees: ['ada@acme.com'], timezone: 'Europe/London' },
1253
+ { idempotencyKey: crypto.randomUUID() }, // a retry replays the first result for 24 h
1254
+ );
1255
+ const page = await api.listMeetings({ linkId, status: 'upcoming', limit: 20 }); // only status 'all' lists cancelled
1256
+ await api.cancelMeeting(made.id, 'Moved to Friday'); // safe to repeat: { ok, id, status, alreadyCancelled }
1257
+
1258
+ // The same three with the API key instead (server side, /external/meetings):
1259
+ await api.listMeetingsWithKey({ linkId }); // scheduleMeetingWithKey, cancelMeetingWithKey
1260
+
1261
+ // Owner token: keep the last 50 deliveries of a webhook for 30 minutes (this is what `chatta webhooks listen` uses).
1262
+ await api.startWebhookCapture(webhookId);
1263
+ const { results, lastSeq } = await api.readWebhookCapture(webhookId, 0); // next call: readWebhookCapture(webhookId, lastSeq)
1264
+ await api.stopWebhookCapture(webhookId);
1265
+ ```
1266
+
1267
+ Every delivery carries `X-Webhook-Signature: t=<unix>,v1=<hex>`, an HMAC-SHA256 of `"<t>." + rawBody` with the webhook secret, and an `id` in the body (also `X-Webhook-Id`), which is stable across retries: dedupe on the signed body `id`, not the unsigned header, and record it only after your work succeeded. Verify the signature with the code in [samples](samples/README.md).
1268
+ The old `X-Webhook-Secret` header carries the secret itself. New webhooks never send it; older ones send it (with `X-Webhook-Deprecation`) only until **2027-02-17**, and `rotateWebhookSecret` turns it off. Retries are signed with the webhook's current secret when they are sent.
1269
+
1270
+ The native SDKs have typed models for every TypeScript model: Kotlin data classes, Swift structs, Dart classes, all generated from the TypeScript types (`yarn models:generate`; `yarn check:models` fails on drift). Use the typed twins, and treat the map-based `sendMessage` and `listSentMessages` as deprecated:
1271
+
1272
+ ```kotlin
1273
+ api.sendMessageTyped(LiveChattaSendMessagePayload(conversationId = id, message = "Hi")) { msg, err -> /* msg: LiveChattaMessage? */ }
1274
+ ```
1275
+
1276
+ ```swift
1277
+ api.sendMessageTyped(LiveChattaSendMessagePayload(conversationId: id, message: "Hi")) { msg, err in /* msg: LiveChattaMessage? */ }
1278
+ ```
1279
+
1280
+ ```dart
1281
+ final msg = await api.sendMessageTyped(LiveChattaSendMessagePayload(conversationId: id, message: 'Hi'));
1282
+ ```
1283
+
1284
+ ### Hop: calls on the lock screen, pin for everyone, new meeting switches
1285
+
1286
+ `hop-invite` now carries `participantCount`, `mode` (`NOW` = 1:1 "HopNow", `CIRCLE` = group) and `media` (`audio` | `video`), so the ring can say "HopNow · video call" and lead with Accept audio or Accept video (pass that media to `joinHop`). The incoming-call push has `data: IncomingCallPushData` (`type: 'HOP_INVITE'`, `category: 'INCOMING_CALL'`, `callId` = `sessionId`, `conversationId`, `invitedByName`, `participantCount` as a string, `linkCode`); iOS category `INCOMING_CALL_CATEGORY`, Android channel `INCOMING_CALL_ANDROID_CHANNEL`, rings `INCOMING_CALL_RING_SECONDS` (30 s). Lock-screen Decline has no socket, so use REST:
1287
+
1288
+ ```typescript
1289
+ await api.declineHopInvite(push.sessionId); // member token; the call gets hop-invite-declined
1290
+ sock.onHopInvite((inv) => ring(inv.mode, inv.media, inv.participantCount));
1291
+
1292
+ await sock.hopPinForAll({ sessionId, userId }); // host / co-host; omit userId to unpin
1293
+ sock.onHopPinnedForAll(({ userId }) => pinTile(userId)); // null = unpin
1294
+
1295
+ await sock.scheduleHopMeeting({ title, startAt, endAt, participantIds,
1296
+ requireAdmit: true, recordByDefault: true, runAsWebinar: true }); // waiting room, auto record, webinar (plan-gated)
1297
+
1298
+ sock.sendWhiteboardStroke({ conversationId, stroke: { tool: 'text', text: 'Q4 plan', points: [p, p] } }); // ≤ 200 chars
1299
+ ```
1300
+
1301
+ Calls audit (chatta #376): the `joinHop` ack has `canProduce` (`false` = webinar attendee, consume only until `webinar-attendee-promoted`).
1302
+ Joining the same call again from another tab or device drops the old socket with `hop-you-were-dropped { reason: 'moved' }` and sends
1303
+ `hop-invite-answered { sessionId, conversationId }` to your other devices so they stop ringing. Hosts can mute you but never unmute you:
1304
+ "unmute" sends you `hop-unmute-requested { sessionId, by }`. `hop-participant-muted` carries `self: true` when you toggled your own mic
1305
+ (`hop-media-change` now pauses your server producers). A `hop-invite-request` ring carries `conversationId`.
1306
+
1307
+ ```typescript
1308
+ const joined = await sock.joinHop({ conversationId, media: 'audio' });
1309
+ if (joined.canProduce === false) startListenOnly();
1310
+ sock.onHopInviteAnswered(({ sessionId }) => dismissRing(sessionId));
1311
+ sock.onHopUnmuteRequested(({ by }) => toast('The host asked you to unmute'));
1312
+ sock.onHopYouWereDropped(({ reason }) => (reason === 'moved' ? showMovedNotice() : leaveCall()));
1313
+ ```
1314
+
1315
+ **Native call UI (chatta #426, 1.3.1).** Register the device with `api.registerDevice({ deviceToken, voipToken, platform: 'mobile-ios' })` (member or owner token; `voipToken` is the hex PushKit token, so calls ring through CallKit even with the app closed). Call pushes carry `media` (`audio` | `video`) and, for calls of up to 50 people, `declineToken` + `declineUrl`: decline from CallKit or the Android ring screen with `api.pushDeclineCall(declineToken)` (public, single use, about 2 minutes; 401 used or expired, 403 call ended) → `{ ok, sessionId }`. When the ring ends elsewhere the phone gets `{ type: 'HOP_INVITE_CANCEL', callId, sessionId, reason: 'answered' | 'declined' | 'ended' }`; `parseCallPush(data)` tells the two apart. Inside the shell, send `bridge.sendInit({ nativeCallUi: true })` so the chat holds its own ring, forward the native UI with `bridge.sendNativeCall(action, sessionId)` (`ringing`, `cancel`, `end`, `mute`, `unmute`, `hold`, `unhold`), and mirror the in-call mic with `bridge.onHopMuteChanged(({ sessionId, muted }) => …)`.
1316
+
1317
+ Built from existing calls (no new wire surface): **Decline with a message** = `hopInviteDecline({ sessionId })` then `sendMessage` the note; **whiteboard Snapshot to chat** = upload the PNG and `sendMessage` it with `attachments`.
1318
+
1319
+ ### Threads, forwarding and channels
1320
+
1321
+ These Signal flows reuse existing events:
1322
+
1323
+ ```typescript
1324
+ // Thread reply with "Also send to #channel": the reply, then the same text in the conversation quoting the parent.
1325
+ await sock.sendMessage({ conversationId, senderId, referenceId: id1, message: text, parentMessageId });
1326
+ await sock.sendMessage({ conversationId, senderId, referenceId: id2, message: text,
1327
+ replyTo: { messageId: parentMessageId, senderName, text: parentText.slice(0, 280) } });
1328
+
1329
+ // Forward to several chats with a note: one forward per chat, then the note in each.
1330
+ for (const to of targets) {
1331
+ await sock.forwardMessage({ messageId, fromConversationId, toConversationId: to, senderId });
1332
+ if (note) await sock.sendMessage({ conversationId: to, senderId, referenceId: newId(), message: note });
1333
+ }
1334
+
1335
+ // Channel with a topic, invite-only, announcement-only (only admins post).
1336
+ const conv = await sock.startConversation({ senderId, type: ChatConversationType.CHANNEL, name: 'product',
1337
+ caption: 'Ideas and bugs from the community', isPrivate: true, chatLinkCode });
1338
+ await api.updateConversationPermissions(conv.conversationId, { membersCanSend: false });
1339
+ ```
1340
+
1341
+ ### Hop: polls, live captions, recordings
1342
+
1343
+ ```typescript
1344
+ const snap = await sock.hopCollabState(sessionId); // polls, hands, captions, recording on (re)join
1345
+ await sock.hopPollClose({ sessionId, pollId }); // host or poll starter
1346
+ await sock.hopCaptionsToggle({ sessionId, enabled: true }); // room gets onHopCaptionsState
1347
+ await sock.hopCaption({ sessionId, text, final: true, lang: 'en' });
1348
+ sock.onHopCaptionText((c) => showCaption(c.displayName, c.text, c.final));
1349
+ const recs = await sock.hopRecordingList({ conversationId, limit: 10 }); // each item has downloadable
1350
+ const dl = await api.getRecordingDownloadLink(recs.results[0].messageId); // { url, expiresAt, filename }, 10 minutes
1351
+ ```
1352
+
1353
+ Downloads need the link setting `allowRecordingDownload: true` (off by default; `RECORDING_DOWNLOAD_OFF` 403 otherwise, `RECORDING_DOWNLOAD_EXPIRED` for an old link). `url` is server-relative and needs no header. Recordings can't be forwarded. `getAppVersion()` now also returns `platforms.ios` / `platforms.android` (`{ latest, min, storeUrl }`, empty strings when not configured).
1354
+
1355
+ ### Breaking contract fixes (2026-07)
1356
+
1357
+ The following payload types were re-aligned to the backend DTOs (the old
1358
+ shapes were rejected or silently stripped by the server's whitelist
1359
+ `ValidationPipe`, so no working integration could have relied on them):
1360
+
1361
+ - `registerMembers` / `registerMember` — the body key is `participants` (not
1362
+ `members`) and each participant uses `displayName` / `email` / `country`
1363
+ (not `firstName` / `lastName` / `username`). The old shape always returned
1364
+ HTTP 400.
1365
+ - `createConversation` — requires `memberId` + `conversationType` (the old
1366
+ `type` / `participantIds` shape always returned HTTP 400).
1367
+ - `createWebhook` — `name` is now required (omitting it returned HTTP 400).
1368
+ - `bulkExportChat` — `email` is now required (omitting it returned HTTP 400).
1369
+ - `createChatLink` / `updateChatLink` — removed `linkType` / `maxVisitors`
1370
+ (never existed server-side); added the real fields (`maxMembers`,
1371
+ `profilePhoto`, `welcomeMessage`, `theme`, `settings`, …).
1372
+ - `exportChat` — `conversationId` is required; removed the ignored
1373
+ `chatLinkId`; added `format`.
1374
+ - `sendAdminReply` — removed `attachments` (not supported by the route);
1375
+ added `parentMessageId`.
1376
+ - `giftFeature` — removed `callbackUrl` (not supported by the route).
1377
+ - `forwardMessage` (2026-11) — the payload is `{ messageId, fromConversationId,
1378
+ toConversationId, senderId }` (backend `ForwardChatMessageDto`); the old
1379
+ `{ conversationId, targetConversationId }` keys always failed validation. They
1380
+ are still mapped at runtime for untyped callers.
1381
+
1382
+ ## Embedded UI Mode
1383
+
1384
+ Mount the LiveChatta chat with encrypted token authentication, either **inline** (an iframe inside your container — the default) or as a **floating launcher** (the Signal embed widget: launcher button, unread badge, greeting bubble, chat panel).
1385
+
1386
+ ### Floating launcher (Signal widget)
1387
+
1388
+ ```typescript
1389
+ import { LiveChatta } from '@livechatta/sdk';
1390
+
1391
+ LiveChatta.init({
1392
+ linkCode: 'acme-help',
1393
+ apiKey: 'your-api-key',
1394
+ publicKey: '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----',
1395
+ chatUsername: 'visitor_123', // required for embed mode
1396
+ enableSocket: false, // the widget talks to the chat iframe; no socket needed
1397
+ });
1398
+
1399
+ await LiveChatta.ui({
1400
+ floating: true, // no container needed — the launcher is added to <body>
1401
+ title: 'Acme Support',
1402
+ subtitle: 'Usually replies in 5 min',
1403
+ greeting: 'Hi 👋 Questions about your order?',
1404
+ // primaryColor: '#0B6E66', // omit to use the link's Appearance colour (else Signal #D2400B)
1405
+ });
1406
+
1407
+ LiveChatta.open(); // close(), toggle(), isOpen()
1408
+ LiveChatta.setUnread(2); // optional: drive the badge from your own sock() listeners
1409
+ ```
1410
+
1411
+ What the widget does:
1412
+
1413
+ | State | Behaviour |
1414
+ |---|---|
1415
+ | Closed | 60 px launcher, shape `border-radius: 20px 20px 5px 20px` (mirrored for `bottom-left`), filled with the brand colour; the icon is white or Signal ink (`#191715`), whichever contrasts more. |
1416
+ | Unread | Badge on the launcher (`99+` cap), label becomes "Open chat, 2 unread". Fed by the chat frame (see *Frame messages* below) or by `setUnread()`. |
1417
+ | Greeting | Optional bubble next to the closed launcher after `greetingDelay` (default 10 s). Dismissing it (✕, Escape, or opening the chat) is remembered per link in `localStorage`. |
1418
+ | Open | Panel (`role="dialog"`, 380 × 640 by default) with a brand header (logo or initials, title, subtitle, close). Focus moves to the close button; **Escape** or close returns focus to the launcher. |
1419
+ | Mobile web (≤ 640 px) | The panel goes full screen (safe areas respected), `aria-modal="true"`, and page scroll is locked while open. |
1420
+ | Pre-chat form (guest) | With `preChat`, the panel opens on a form (name, email, optional topic) the first time per link. Labels, inline errors (`aria-invalid` + `aria-describedby`), and focus on the first invalid field. `onPreChatSubmit(values)` runs first (register or route the guest; a throw keeps the form open with an alert), then the values go to the chat frame as `livechatta:prechat`. Only a "done" flag is stored, never the values. |
1421
+ | Away (outside business hours) | With `businessHours`, the panel opens on an info banner — "We're away · back Mon 9:00 WAT." plus your `awayMessage` — and the header subtitle becomes "Away · back …". With `onAwayMessage`, a message box and **Send** let the visitor leave a message; **Continue to chat** always uncovers the chat. Bad hours config fails open (chat stays available). |
1422
+
1423
+ The widget renders inside a shadow root, so your site's CSS cannot restyle it, and it follows `prefers-reduced-motion`. While focus is inside the cross-origin chat iframe the host page cannot see key presses, so Escape works from the panel header and launcher; the close button always works.
1424
+
1425
+ **Frame messages.** The launcher takes the link's brand colour, the effective light/dark mode and the unread count from the chat frame:
1426
+
1427
+ | Where | Message `type` | Payload |
1428
+ |---|---|---|
1429
+ | Native shells (`/app/embed/chat`) | `CHATTA_APP:onThemeLoaded` | `{ primaryColor, mode, themeMode }` (frozen contract) |
1430
+ | Native shells | `CHATTA_APP:onUnreadChange` | count (number or `{ count }`): the whole-list total since chatta #427, not only loaded rows |
1431
+ | Shell → frame (mobile shell 1.1.1) | `CHATTA_APP:shareFiles` | `{ files: File[], text? }`: stage shared files in the open chat's composer |
1432
+ | Shell → frame | `CHATTA_APP:init` | `{ shortcuts?, nativeCallUi? }`: `nativeCallUi: true` = the shell rings calls natively |
1433
+ | Shell → frame | `CHATTA_APP:nativeCall` | `{ action: ringing \| cancel \| end \| mute \| unmute \| hold \| unhold, sessionId }` |
1434
+ | Frame → shell | `CHATTA_APP:hopMuteChanged` | `{ sessionId, muted }`: mirror the mic on CallKit / Telecom |
1435
+ | Web embeds (`/embed/chat`) — **provisional** | `livechatta:brand` | `{ primaryColor, secondaryColor?, mode?, themeMode? }` |
1436
+ | Web embeds — **provisional** | `livechatta:unread` | `{ count }` or a number |
1437
+ | Host → frame — **provisional** | `livechatta:prechat` | `{ name, email, topic?, … }` after the pre-chat form |
1438
+ | Host → frame | `livechatta:hello` | `{ type }` only, sent on every iframe load, addressed to the iframe's own origin (never `'*'`) |
1439
+
1440
+ **Sharing files into the chat (app shells).** A shell that hosts the chat frame can hand it files the user shared into the app: `LiveChatta.bridge.shareFiles(files, text?)` posts `CHATTA_APP:shareFiles { files, text }` (at most 10 `File` objects, `text` trimmed to 4000 characters) to the frame's origin only, never to `*`. The chat stages them in the open conversation's composer under the link's upload rules and sends nothing until the user taps Send. Native SDK WebViews (Kotlin, Swift, Flutter) cannot build browser `File` objects, so this message comes from the official LiveChatta app shell or your own JavaScript in the page.
1441
+
1442
+ **The bridge never posts to `'*'`.** `LiveChatta.bridge` addresses the origin of the iframe's `src`, and only when it equals `baseUrl`'s origin; otherwise it sends nothing and logs one warning (`send()` returns `false`, `request()` rejects). Inbound `CHATTA_APP:*` events are accepted only from the attached iframe's window and that origin. If you construct `Bridge` yourself, pass `allowedOrigin`.
1443
+
1444
+ **The `livechatta:hello` handshake.** The chat page posts `livechatta:brand`, `livechatta:unread` and `close` to the embedding page's origin only, never to `'*'`. It learns that origin from `ancestorOrigins` or the referrer; where the browser gives neither (Firefox, pages with `no-referrer`) it waits for `livechatta:hello` from its parent. `LiveChattaEmbed` (the web launcher, and the React, Vue, Nuxt, Svelte and Angular wrappers, which all mount through it) and `LiveChatta.ui()` post it automatically each time the iframe loads, addressed to the origin of the iframe's `src`. If you build the iframe yourself, do the same: `iframe.addEventListener('load', () => iframe.contentWindow.postMessage({ type: 'livechatta:hello' }, new URL(iframe.src).origin))`, or call the exported `helloOnLoad(iframe)`. Never use `'*'`: until the hello arrives the page stays quiet rather than broadcast.
1445
+
1446
+ The two `livechatta:*` names above are provisional until the matching chat-page release ships; they are exported as `EMBED_MESSAGE_TYPES`. Messages are accepted only from the widget's own iframe and the configured `baseUrl` origin. Until the chat page sends them, web embeds show the Signal brand (or your `primaryColor`) and the badge updates through `setUnread()`.
1447
+
1448
+ **Launcher options** (all optional; existing inline options are unchanged):
1449
+
1450
+ | Option | Default | Description |
1451
+ |---|---|---|
1452
+ | `floating` | `false` | `true` renders the launcher + panel; `false` keeps the classic inline iframe (`container` required). |
1453
+ | `position` | `'bottom-right'` | `'bottom-right'` or `'bottom-left'`. |
1454
+ | `autoOpen` | `false` | Open the panel on mount. |
1455
+ | `greeting` | — | Proactive greeting text. |
1456
+ | `greetingDelay` | `10000` | Milliseconds before the greeting appears. |
1457
+ | `title` / `subtitle` | `'Chat'` / — | Panel header text; `title` is also the dialog's accessible name. |
1458
+ | `launcherLabel` | `'Open chat'` | Accessible label of the launcher button. |
1459
+ | `zIndex` | `2147483000` | Stacking order of the widget. |
1460
+ | `preload` | `true` | Load the chat on mount so the unread count and link brand arrive while closed. `false` loads it on first open. |
1461
+ | `width` / `height` | `380px` / `640px` | Panel size on desktop (inline defaults stay `100%` / `600px`). |
1462
+ | `onOpenChange` | — | `(open: boolean) => void`, called on every open/close. |
1463
+ | `preChat` | — | `true` for name + email, or `{ topics?, fields?, intro?, submitLabel?, note?, enabled? }`. Fields: `{ name, label, type?: 'text' \| 'email' \| 'tel' \| 'select' \| 'textarea', required?, options?, placeholder? }`. |
1464
+ | `onPreChatSubmit` | — | `(values) => void \| Promise<void>`; await your own registration (e.g. `api().registerMember`). |
1465
+ | `businessHours` | — | `{ timezone?: 'Africa/Lagos', timezoneLabel?: 'WAT', windows: [{ day: 1, open: '09:00', close: '17:00' }], awayMessage?, enabled? }`; `day` 0 = Sunday, overnight windows allowed. |
1466
+ | `onAwayMessage` | — | `(message, preChatValues \| null) => void \| Promise<void>`; enables "leave a message" while away. |
1467
+ | `linkConfig` | `true` | Read `preChat` / `businessHours` from the link's widget settings (`GET /external/chat-links/:code/info` → `widget`, **provisional**). Options you pass always win. |
1468
+
1469
+ ### Theming — two colours
1470
+
1471
+ Clients choose **Primary** and **Secondary**; everything else is derived by the chat so any brand stays readable in light and dark. SDK options override the link's **Chat link → Appearance** settings *for that embed only*.
1472
+
1473
+ | Property | Default | Description |
1474
+ |----------|---------|-------------|
1475
+ | `primaryColor` | link theme, else Signal `#D2400B` | Brand: launcher, panel header, outgoing bubbles, send button. `#6C5CE7` (the pre-Signal default) means "no brand". Text/icons on it are picked automatically (white or ink). |
1476
+ | `secondaryColor` | link theme, else Signal lagoon `#0B6E66` | Sender names, channel chips, second chart series (lifted in dark mode until ≥ 4.5:1). In the floating widget it fills the unread badge (default: the primary). |
1477
+ | `primaryLight` | auto | Brand tint (selected rows, reply bar). |
1478
+ | `primaryDark` | auto | Brand hover / pressed. |
1479
+ | `primaryBg` | auto | Legacy brand tint (light mode only). |
1480
+ | `bg` | Signal canvas | Chat background — **light mode only**; dark mode keeps Signal charcoal. |
1481
+ | `bgDark` | Signal charcoal | Chat background in dark mode, used only if it keeps ≥ 10:1 against text. |
1482
+ | `textColor` / `textLight` / `textMuted` | Signal text | Light-mode text colours; replaced if they fall under 4.5:1. |
1483
+ | `borderColor` / `borderLight` | Signal lines | Light-mode borders. |
1484
+ | `fontFamily` | Signal stack | Chat font (Signal stack as fallback). |
1485
+ | `logoUrl` | — | `https` logo for the chat header and the launcher panel. |
1486
+ | `theme` | `'light'` inline, `'system'` floating | `'light'`, `'dark'` or `'system'` (follows the OS live). Sent as `?theme=`. |
1487
+ | `layout` | link setting | `'bubbles'` or `'lines'`. |
1488
+
1489
+ Only colours you pass are sent to the chat; anything unset falls back to the link's own theme and then to Signal. Brand colours are the only values that cross into dark mode; surface and text overrides apply to light mode.
1490
+
1491
+ Runtime changes:
1492
+
1493
+ ```typescript
1494
+ await LiveChatta.updateTheme({ primaryColor: '#0B6E66', theme: 'dark' });
1495
+ ```
1496
+
1497
+ `updateTheme()` posts a `livechatta:theme` message (colours) and, when `theme` is given, the standard `CHATTA_APP:theme` `{ mode }` message, so the chat switches live without reloading. The launcher re-tints at the same time.
1498
+
1499
+ ### Inline embed (container)
1500
+
1501
+ ```typescript
1502
+ LiveChatta.init({
1503
+ linkCode: 'acme-help',
1504
+ apiKey: 'your-api-key',
1505
+ publicKey: '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----',
1506
+ chatUsername: 'john_doe',
1507
+ enableSocket: true,
1508
+ });
1509
+
1510
+ const iframe = await LiveChatta.ui({
1511
+ container: '#chat-container',
1512
+ primaryColor: '#D2400B',
1513
+ secondaryColor: '#0B6E66',
1514
+ theme: 'system',
1515
+ width: '400px',
1516
+ height: '600px',
1517
+ });
1518
+
1519
+ LiveChatta.unmountUI();
1520
+ ```
1521
+
1522
+ ### Standalone embed (no SDK init required)
1523
+
1524
+ ```typescript
1525
+ import { LiveChattaEmbed } from '@livechatta/sdk/platforms/web';
1526
+
1527
+ const chat = new LiveChattaEmbed({
1528
+ linkCode: 'acme-help',
1529
+ apiKey: 'your-api-key',
1530
+ publicKey: '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----',
1531
+ chatUsername: 'john_doe',
1532
+ floating: true, // or container: '#chat-container' for inline
1533
+ title: 'Acme Support',
1534
+ greeting: 'Hi 👋 Questions about your order?',
1535
+ });
1536
+
1537
+ await chat.mount();
1538
+ chat.onMessage((data) => console.log('Message:', data));
1539
+ chat.onError((err) => console.error('Error:', err));
1540
+ chat.open(); // close(), toggle(), isOpen(), setUnread(n)
1541
+ await chat.updateTheme({ primaryColor: '#0B6E66', theme: 'dark' });
1542
+ chat.unmount();
1543
+ ```
1544
+
1545
+ ### Plain iframe snippet
1546
+
1547
+ If you embed the hosted chat yourself, use the frameable `/embed/chat` route and give the iframe this `allow` list so voice/video, screen share and copy work:
1548
+
1549
+ ```html
1550
+ <iframe src="https://livechatta.com/in/acme-help/embed/chat?theme=system"
1551
+ allow="microphone; camera; display-capture; clipboard-write"
1552
+ style="width:100%;height:640px;border:0"></iframe>
1553
+ ```
1554
+
1555
+ `LiveChattaEmbed` sets exactly this list (exported as `EMBED_IFRAME_ALLOW`). `LiveChatta.ui()` sets it too and additionally delegates the Hop extras (autoplay, fullscreen, picture-in-picture, wake lock, …) and a sandbox — see `IFRAME_ALLOW` / `IFRAME_SANDBOX` exported from the package.
1556
+
1557
+ `?theme=` accepts `light`, `dark` or `system` and is applied before first paint; native shells keep using `CHATTA_APP:theme` and `CHATTA_APP:onThemeLoaded { primaryColor, mode, themeMode }` unchanged.
1558
+
1559
+ ### Browser script tag
1560
+
1561
+ ```html
1562
+ <script src="https://unpkg.com/@livechatta/sdk/dist/umd/livechatta.umd.min.js"></script>
1563
+ <script>
1564
+ const { LiveChatta } = window.LiveChatta;
1565
+ LiveChatta.init({
1566
+ linkCode: 'acme-help',
1567
+ apiKey: 'your-api-key',
1568
+ publicKey: '-----BEGIN PUBLIC KEY-----\n...',
1569
+ chatUsername: 'visitor123',
1570
+ enableSocket: false,
1571
+ });
1572
+ LiveChatta.ui({ floating: true, title: 'Acme Support', greeting: 'Hi 👋 Need help?' });
1573
+ </script>
1574
+ ```
1575
+
1576
+ ### Brand helpers
1577
+
1578
+ `resolveBrand()`, `hasCustomBrand()`, `onBrandColor()`, `brandTextOn()` and `contrastRatio()` are exported for headless builders who want the same rules: legacy `#6C5CE7` = no brand, icon colour = white or ink by contrast, brand-as-text darkened/lightened until ≥ 4.5:1.
1579
+
1580
+ ## Headless Mode (BYO UI)
1581
+
1582
+ Use the SDK purely as a data/transport layer — no embedded UI.
1583
+
1584
+ ```typescript
1585
+ LiveChatta.init({
1586
+ linkCode: 'abc',
1587
+ apiKey: 'key123',
1588
+ publicKey: '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----',
1589
+ enableSocket: true,
1590
+ enableHttp: true,
1591
+ });
1592
+
1593
+ await LiveChatta.connect();
1594
+
1595
+ // Build your own UI, wire events to your components
1596
+ LiveChatta.sock().onMessage((msg) => renderMessage(msg));
1597
+ LiveChatta.sock().onTyping((data) => showTypingIndicator(data));
1598
+
1599
+ const history = await LiveChatta.api().getMessages(conversationId, { limit: 50 });
1600
+ renderMessageList(history.data);
1601
+ ```
1602
+
1603
+ ## Platform-Specific Components
1604
+
1605
+ Each platform supports two modes:
1606
+ - **Embedded UI** — WebView that renders the LiveChatta chat interface
1607
+ - **Headless (BYO UI)** — Native `.sock()` and `.api()` access for building custom UIs
1608
+
1609
+ All platforms use encrypted token authentication (`token=encrypted({apiKey, linkCode, chatUsername})`).
1610
+
1611
+ ### Web/Browser
1612
+
1613
+ See the **Embedded UI Mode** section above. `LiveChatta.ui()` and `LiveChattaEmbed` (`@livechatta/sdk/platforms/web`) provide the inline embed and the floating launcher.
1614
+
1615
+ All web wrappers below (React, Angular, Vue, Nuxt, Svelte) accept the same props as `LiveChattaEmbed`: the theme properties, `layout`, and the launcher options (`floating`, `position`, `autoOpen`, `greeting`, `greetingDelay`, `title`, `subtitle`, `launcherLabel`, `zIndex`, `preload`, `preChat`, `onPreChatSubmit`, `businessHours`, `onAwayMessage`, `linkConfig`). Launcher options are read at mount; changing `floating`, `position` or `layout` remounts, colour/`theme` changes apply live.
1616
+
1617
+ ### React
1618
+
1619
+ #### Headless Mode (Hook)
1620
+
1621
+ ```tsx
1622
+ import { useLiveChatta } from '@livechatta/sdk/platforms/react';
1623
+
1624
+ function ChatScreen() {
1625
+ const { sock, api, connectionState, isConnected, connect } = useLiveChatta({
1626
+ linkCode: 'your-link-code',
1627
+ apiKey: 'your-api-key',
1628
+ publicKey: '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----',
1629
+ chatUsername: 'john_doe',
1630
+ });
1631
+
1632
+ useEffect(() => { connect(); }, []);
1633
+
1634
+ useEffect(() => {
1635
+ if (!sock) return;
1636
+ sock.onMessage((msg) => console.log('New message:', msg));
1637
+ sock.onTyping((data) => showTypingIndicator(data));
1638
+ }, [sock]);
1639
+
1640
+ const loadMembers = async () => {
1641
+ const members = await api.listMembers();
1642
+ console.log(members.results);
1643
+ };
1644
+ }
1645
+ ```
1646
+
1647
+ #### Embedded UI (Component)
1648
+
1649
+ ```tsx
1650
+ import { LiveChattaView } from '@livechatta/sdk/platforms/react/view';
1651
+
1652
+ <LiveChattaView
1653
+ linkCode="your-link-code"
1654
+ apiKey="your-api-key"
1655
+ publicKey="-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----"
1656
+ chatUsername="john_doe"
1657
+ primaryColor="#D2400B"
1658
+ secondaryColor="#0B6E66"
1659
+ theme="system"
1660
+ height="500px"
1661
+ onMessage={(data) => console.log(data)}
1662
+ onError={(err) => console.error(err)}
1663
+ />
1664
+
1665
+ // Floating launcher instead of an inline frame:
1666
+ <LiveChattaView
1667
+ linkCode="your-link-code"
1668
+ apiKey="your-api-key"
1669
+ publicKey="-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----"
1670
+ chatUsername="john_doe"
1671
+ floating
1672
+ title="Acme Support"
1673
+ greeting="Hi 👋 Questions about your order?"
1674
+ onOpenChange={(open) => console.log('open:', open)}
1675
+ />
1676
+ ```
1677
+
1678
+ Peer dependencies: `react ^17/18/19`. Hook auto-destroys on component unmount.
1679
+
1680
+ ### React Native
1681
+
1682
+ React Native runs JavaScript natively, so the core SDK works directly.
1683
+
1684
+ #### Headless Mode (Hook)
1685
+
1686
+ ```tsx
1687
+ import { useLiveChatta } from '@livechatta/sdk/platforms/react-native';
1688
+
1689
+ function ChatScreen() {
1690
+ const { sock, api, isConnected, connect } = useLiveChatta({
1691
+ linkCode: 'your-link-code',
1692
+ apiKey: 'your-api-key',
1693
+ publicKey: '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----',
1694
+ chatUsername: 'john_doe',
1695
+ });
1696
+
1697
+ useEffect(() => { connect(); }, []);
1698
+
1699
+ useEffect(() => {
1700
+ if (!sock) return;
1701
+ sock.onMessage((msg) => console.log('New message:', msg));
1702
+ sock.onTyping((data) => showTypingIndicator(data));
1703
+ }, [sock]);
1704
+
1705
+ const loadMembers = async () => {
1706
+ const members = await api.listMembers();
1707
+ console.log(members.results);
1708
+ };
1709
+ }
1710
+ ```
1711
+
1712
+ #### Embedded UI (WebView)
1713
+
1714
+ ```tsx
1715
+ import { LiveChattaView } from '@livechatta/sdk/platforms/react-native';
1716
+
1717
+ <LiveChattaView
1718
+ linkCode="your-link-code"
1719
+ apiKey="your-api-key"
1720
+ publicKey={"-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----"}
1721
+ chatUsername="john_doe"
1722
+ primaryColor="#D2400B" // omit to use the link's Appearance colour
1723
+ secondaryColor="#0B6E66"
1724
+ theme="system" // 'light' | 'dark' | 'system' (default 'light')
1725
+ onMessage={(data) => console.log(data)}
1726
+ onError={(err) => console.error(err)}
1727
+ />
1728
+ ```
1729
+
1730
+ The native view fills its container (no launcher; open it from your own button or screen). Colours are only sent when you set them, and `#6C5CE7` is treated as "no brand". Requires `react-native-webview` for embed. Hook mode requires `socket.io-client` (peer dep).
1731
+
1732
+ ### Android (Kotlin)
1733
+
1734
+ #### Headless Mode (Native SDK)
1735
+
1736
+ ```kotlin
1737
+ val client = LiveChattaClient()
1738
+ client.init(LiveChattaOptions(
1739
+ linkCode = "your-link-code",
1740
+ apiKey = "your-api-key",
1741
+ publicKey = "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----",
1742
+ chatUsername = "john_doe",
1743
+ ))
1744
+
1745
+ client.connect { success, error ->
1746
+ if (!success) { Log.e("Chat", "Error: $error"); return@connect }
1747
+
1748
+ // Real-time messaging
1749
+ client.sock().onMessage { data -> Log.d("Chat", "Message: $data") }
1750
+ client.sock().sendMessage(JSONObject().apply {
1751
+ put("conversationId", "conv123")
1752
+ put("senderId", "user456")
1753
+ put("referenceId", UUID.randomUUID().toString())
1754
+ put("message", "Hello from Android!")
1755
+ }) { response -> Log.d("Chat", "Sent: $response") }
1756
+ }
1757
+
1758
+ // REST operations
1759
+ client.api().listMembers { result, error ->
1760
+ Log.d("Chat", "Members: $result")
1761
+ }
1762
+ ```
1763
+
1764
+ Requires `io.socket:socket.io-client:2.1.0` in `build.gradle`.
1765
+
1766
+ Content features (owner methods need `LiveChattaOptions(ownerToken = …)` or `client.api().ownerToken = …`):
1767
+
1768
+ ```kotlin
1769
+ val api = client.api()
1770
+ api.getLinkEmojiPack("acme-help") { pack, err -> /* pack: { linkId, emojis, stickers } */ }
1771
+ api.createLinkEmoji(linkId, JSONObject().apply {
1772
+ put("kind", "emoji"); put("shortcode", "party_parrot"); put("image", "data:image/png;base64,…")
1773
+ }) { item, err -> }
1774
+ api.schedulePost(postId, JSONObject().put("scheduledAt", "2026-12-01T09:00:00Z")) { res, err -> }
1775
+ api.trackPromoClick(postId, visitorId = storedVisitorId) { res, err -> /* open res?.optString("url") */ }
1776
+ api.getPromoAnalytics(postId) { stats, err -> }
1777
+ ```
1778
+
1779
+ Also: `listLinkEmojis`, `updateLinkEmoji`, `enable/disable/deleteLinkEmoji`, `createPost`, `listPosts`, `publishPost`, `cancelPostSchedule`. Persist your own `visitorId` (`[A-Za-z0-9_-]{8,64}`, e.g. in SharedPreferences).
1780
+
1781
+ Chat features: socket emitters/listeners with the same names as the JS SDK (`messageDelivered`, `muteConversation`, `huddleStart`, `transcribeMessage`, `onHuddleUpdated`, …) take a `JSONObject` payload. REST twins on `api()` use `memberToken` / `ownerToken` per the auth table above (`LiveChattaOptions(memberToken = …)` or `client.api().memberToken = …`); pass `JSONObject.NULL` as `assigneeId` to unassign. A denied emit calls its callback with `null` and fires `client.sock().onAckError = { event, error -> … }`.
1782
+
1783
+ Support inbox and chat core use the same names as the JS SDK too. Agent routes on `api()` (`getInboxAgentProfile`, `createInternalNote`, `getAgentInboxState`, `agentAssignConversation`, `createConversationNote`, `getConversationSummary`, `getDraftReply`, `getConversationCatchUp`, `setConversationTopic`, …) and `listMyChatLinks` / `announceGift` need `memberToken`. `setLinkInboxSettings`, `setLinkDiscoverable` and `setWidgetConfig` need `ownerToken`. `getPresenceStats` / `getLinkAvailability` are public. On the socket: `conversationRead`, `deleteMessage`, `searchAll`, `submitPreChat`, `hopPollClose`, `hopCollabState`, `hopCaptionsToggle`, `hopCaption` and `hopRecordingList`, with listeners `onInternalNote`, `onInternalNoteDeleted`, `onConversationNotesUpdated`, `onConversationRead`, `onMessageDeleted`, `onPreChatSubmitted`, `onThreadUpdate`, `onHopCaptionsState` and `onHopCaptionText`. A 410 link page posts `CHATTA_APP:onLinkUnavailable { state, code }` to the WebView `onMessage` handler.
1784
+
1785
+ Blocked members: every 4xx reaches `client.api().onApiError = { e: LiveChattaApiError -> … }` (with `e.statusCode`, `e.code`, `e.path`) just before that call's `(null, message)` callback; compare `e.code` with `LiveChattaErrorCode.LINK_MEMBER_BLOCKED`. On the socket, `LiveChattaSocketAPI.LinkAccess.isBlocked(result)` reads `linkAccess` from the first `getConversations()` page.
1786
+
1787
+ Devices and quiet hours: `listAccountSessions`, `revokeAccountSession(sessionId)`, `revokeOtherAccountSessions`, `getAccountQuietHours`, `setAccountQuietHours(JSONObject)` need `ownerToken`; `listMySessions`, `revokeMySession(sessionId)`, `revokeMyOtherSessions` need `memberToken`. `getQuietHours` now carries `account` (a `JSONObject` or `JSONObject.NULL`).
1788
+
1789
+ Calls, links and status: `sendScheduledMessageNow(messageId)` and `declineHopInvite(sessionId)` need `memberToken`; `notifyWhenLinkReopens(linkCode, email)`, `subscribeToStatusUpdates(email)`, `unsubscribeFromStatusUpdates(email, token)`, `getWebinarInfo(conversationId)` and `registerForWebinar(conversationId, JSONObject)` are public; `testWebhook(webhookId)` uses the API key. `listMyChatLinks` rows carry `memberCount` and `role`. A full link's 400 has `e.code == LiveChattaErrorCode.LINK_FULL`. On the socket: `hopPinForAll(JSONObject)` and `onHopPinnedForAll`. In your `FirebaseMessagingService`, `LiveChattaIncomingCall.fromData(message.data)` reads an incoming-call push (post it on `LiveChattaIncomingCall.ANDROID_CHANNEL`; Decline → `api().declineHopInvite(call.sessionId)`).
1790
+
1791
+ Guest join: `getLinkOnlineCount(linkCode)` and `joinLinkAsGuest(linkCode, displayName, email)` are public; a 400 with `e.code == LiveChattaErrorCode.ACCOUNT_EXISTS` from join-guest or join-new means sign in through join-exist instead.
1792
+
1793
+ Exports and links: `exportConversationAsMember(conversationId, JSONObject)`, `getMemberExportStatus(conversationId, exportId)` `leaveMyLink(linkId)`, `setMyLinkNotify(linkId, level)` and `listLinkMembers(chatLinkId, limit)` need `memberToken`; `exportConversationAsOwner(conversationId, JSONObject)` and `testAutomationKeywords(chatLinkId, keywords)` need `ownerToken`. Polls take `anonymous`, posts take `allowReplies` and `background`, automations take `REPLY_CANNED` / `ASSIGN_TEAM`.
1794
+
1795
+ Teams, followers, gifts: `listWorkspaceTeams`, `createWorkspaceTeam(JSONObject)`, `updateWorkspaceTeam(teamId, JSONObject)`, `deleteWorkspaceTeam(teamId)`, `inviteTeamMember(JSONObject)`, `inviteChatUser(JSONObject)` and `getWebinarRecordingsAsOwner(conversationId)` need `ownerToken`; `getMemberFollowStatus` / `followMember` / `unfollowMember(linkId, memberId)`, `redeemMeetingGuestPass(code, token)`, `joinMeetingFromChannel(meetingConversationId)`, `sendPeerGift(JSONObject)`, `listReceivedGifts(query)`, `getGiftBalance`, `requestGiftPayout` need `memberToken` (`getGiftCatalog` takes either); `sendPushReply(token, message)`, `requestWebinarRecordingLink(conversationId, email)`, `getWebinarRecording(conversationId, token)` and `verifyPeerGift(reference)` are public.
1796
+
1797
+ Modes: `setLinkMode(linkId, JSONObject)` needs `ownerToken`; `setConversationMode(conversationId, mode)` takes the member or owner token; `getPublicLinkInfo(linkCode)` is public (`mode`, `joinPolicy`). Join refusals carry `LiveChattaErrorCode.EMAIL_REQUIRED` (400) or `LiveChattaErrorCode.INVITE_ONLY` (403); `startConversation` accepts `mode` and `category`.
1798
+
1799
+ Support CSAT, invite-only links and recordings: `submitCsat` (memberToken), `listCsatRatings` / `getCsatSummary` (API key; `*AsOwner` with ownerToken), `getLinkMemberList(linkId, mapOf("status" to "invited"))` and `revokeLinkInvite` (ownerToken), `getRecordingDownloadLink(messageId)` (memberToken), each with a `*Typed` twin, plus `getAppVersionTyped` and `onCsatUpdated`. `LiveChattaSocketAPI.LinkAccess.isInviteOnly(result)` reads `linkAccess: 'invite-only'`. Codes: `LiveChattaErrorCode.RATE_LIMITED` (429 send burst), `RECORDING_DOWNLOAD_OFF`, `RECORDING_DOWNLOAD_EXPIRED`.
1800
+
1801
+ Ask to join, channels, support teams, webhooks (1.2.0): `getLinkChannels(linkCode)`, `getGiftStoreData(linkCode)` and `requestToJoinLink(linkCode, name, email, message)` are public; `createAccountChatLink(JSONObject)` (with `modeOptions`), `setLinkJoinPolicy(linkId, JSONObject)`, `listJoinRequests(linkId, query)`, `approveJoinRequest` / `denyJoinRequest(linkId, requestId)`, `getWebhookDeliveries(webhookId, limit)`, `retryWebhookDelivery(webhookId, deliveryId)`, `rotateWebhookSecret(webhookId)` and `getAdminMentionsAsOwner(query)` (`handles`, `q`) need `ownerToken`; `getSupportGroupTeam(conversationId)` / `setSupportGroupTeam(conversationId, teamId?)` need `memberToken`. New codes: `LiveChattaErrorCode.APPROVAL_OFF`, `HANDLE_TAKEN`, `ADMIN_NO_ACCESS`, `PLAN_NOT_FOUND`, `PLAN_NOT_AVAILABLE`, `PLAN_TEAM_ACTIVATED`. Socket: `onHopInviteAnswered`, `onHopUnmuteRequested`; the `joinHop` ack has `canProduce`, `onHopYouWereDropped` may carry `reason: "moved"`.
1802
+
1803
+ 1.2.1: `inviteToHop(sessionId, chatUserIds)` (memberToken, socket ring + push), `getAdminMentions(query)` takes `handles` and `q` with the API key too, and hop reaction / vote / raise-hand / poll-vote acks may be `{ ok: false, error: LiveChattaErrorCode.HOP_RATE_LIMITED }`.
1804
+
1805
+ 1.2.2: `requestBusinessPasswordReset(identifier)`, `resetBusinessPassword(token, newPassword, confirmPassword)`, `getPasswordResetStatus(token)`, `requestChatPasswordReset(identifier, chatLinkCode)`, `resetChatPassword(…)`, `requestLinkPasswordReset(linkCode, identifier)`, `resetLinkPassword(linkCode, …)` are public. **Breaking:** socket `forgotPassword` needs `{ identifier, chatLinkCode }`; `resetPassword` takes `{ token, newPassword, confirmPassword }`.
1806
+
1807
+ 1.3.0 (ownerToken): `getTrialStatus`, `startTrial(planId, billingCycle)`, `getRenewalStatus`, `renewSubscription(subscriptionId, paymentMethod)`, `useBankTransferRenewals`, `listStaffAccess(query)`, `getOwnerGifts(query)`; `subscribeToPlan(planId, billingCycle, paymentMethod)`; `getStorageUsage` takes the member or owner token. Upload refusals carry `LiveChattaErrorCode.STORAGE_LIMIT`. Gift catalog and received rows no longer carry fee fields.
1808
+
1809
+ 1.3.1: `registerDevice(JSONObject)` (memberToken or ownerToken; `voipToken` for iOS only) and public `pushDeclineCall(declineToken)`. `LiveChattaIncomingCall` gains `media`, `declineToken`, `declineUrl`; `LiveChattaCallCancel.fromData(message.data)` reads `HOP_INVITE_CANCEL` (reason answered / declined / ended) so you can end the Telecom ring.
1810
+
1811
+ 1.3.2: `getConversations` pages hold 40 (`LiveChattaSocketAPI.Sidebar.PAGE_SIZE`). `getUnreadTotals(excludeConversationIds) { … }` acks `{ unreadTotals }`; `Sidebar.unreadTotal(result)` reads the total from it or from the first page. Deep links: `JSONObject().put("chatConversationByCodes", code)`.
1812
+
1813
+ Owner console and preferences: `testWebhookAsOwner(webhookId)`, `listAccountChatLinks(query)` (e.g. `mapOf("chatLinkExpiringDays" to "7")`) and `updateAccountProfile(JSONObject)` (preferences `notifyTopics`, `language`, `translateIncomingTo` with `"off"` to disable, `soundPreferences`) need `ownerToken`. `updateChatLink` takes `settings.defaultLayout` (`bubbles` | `lines`); settings merge key by key (allowlist: `maxMembers`, `allow*`, `welcomeMessage`, `defaultLayout`, `hideRunsOn`). `createAutomation` / `updateAutomation` take `triggerConfig.keywords` and up to 3 `extraActions`.
1814
+
1815
+ #### Embedded UI (WebView)
1816
+
1817
+ ```kotlin
1818
+ val chatView = LiveChattaWebView(context).apply {
1819
+ configure(
1820
+ linkCode = "your-link-code",
1821
+ apiKey = "your-api-key",
1822
+ publicKey = "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----",
1823
+ chatUsername = "john_doe",
1824
+ primaryColor = "D2400B", // optional: omit for the link's colour (else Signal)
1825
+ secondaryColor = "0B6E66", // optional
1826
+ theme = "system", // "light" (default) | "dark" | "system"
1827
+ )
1828
+ onMessageReceived = { data -> Log.d("Chat", data) }
1829
+ onErrorReceived = { error -> Log.e("Chat", error) }
1830
+ }
1831
+ container.addView(chatView)
1832
+ ```
1833
+
1834
+ `primaryColor` / `secondaryColor` are now nullable (`String? = null`); existing calls compile unchanged. `layout = "bubbles" | "lines"` is also accepted. For `theme = "system"` the page follows the WebView's `prefers-color-scheme` (Android 13+ follows the app's dark theme).
1835
+
1836
+ ### iOS (Swift)
1837
+
1838
+ #### Headless Mode (Native SDK)
1839
+
1840
+ ```swift
1841
+ let client = LiveChattaClient()
1842
+ client.initialize(options: LiveChattaOptions(
1843
+ linkCode: "your-link-code",
1844
+ apiKey: "your-api-key",
1845
+ publicKey: "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----",
1846
+ chatUsername: "john_doe"
1847
+ ))
1848
+
1849
+ client.connect { success, error in
1850
+ guard success else { print("Error: \(error ?? "unknown")"); return }
1851
+
1852
+ // Real-time messaging
1853
+ client.sock().onMessage { data in print("Message: \(data)") }
1854
+ client.sock().sendMessage([
1855
+ "conversationId": "conv123",
1856
+ "senderId": "user456",
1857
+ "referenceId": UUID().uuidString,
1858
+ "message": "Hello from iOS!"
1859
+ ]) { response in print("Sent: \(response ?? [:])") }
1860
+ }
1861
+
1862
+ // REST operations
1863
+ client.api().listMembers { result, error in
1864
+ print("Members: \(result ?? [:])")
1865
+ }
1866
+ ```
1867
+
1868
+ Requires `Socket.IO-Client-Swift` via Swift Package Manager.
1869
+
1870
+ Content features (owner methods need `LiveChattaOptions(…, ownerToken: …)` or `client.api().ownerToken = …`):
1871
+
1872
+ ```swift
1873
+ let api = client.api()
1874
+ api.getLinkEmojiPack(linkCode: "acme-help") { pack, error in }
1875
+ api.createLinkEmoji(linkId: linkId, payload: ["kind": "sticker", "shortcode": "hello_wave",
1876
+ "image": "data:image/webp;base64,…"]) { item, error in }
1877
+ api.schedulePost(postId: postId, payload: ["scheduledAt": "2026-12-01T09:00:00Z"]) { res, error in }
1878
+ api.trackPromoClick(postId: postId, visitorId: storedVisitorId) { res, error in /* open res?["url"] */ }
1879
+ api.getPromoAnalytics(postId: postId) { stats, error in }
1880
+ ```
1881
+
1882
+ Also: `listLinkEmojis`, `updateLinkEmoji`, `enable/disable/deleteLinkEmoji`, `createPost`, `listPosts`, `publishPost`, `cancelPostSchedule`. Keep the owner token in the Keychain; persist `visitorId` in `UserDefaults`.
1883
+
1884
+ Chat features: socket methods (`messageDelivered`, `muteConversation`, `huddleStart`, `transcribeMessage`, `onHuddleUpdated`, …) take `[String: Any]` payloads; REST twins on `api()` use `memberToken` / `ownerToken` per the auth table above (`LiveChattaOptions(…, memberToken: …)`); pass `NSNull()` as `assigneeId` to unassign. A denied emit calls its callback with `nil` and fires `sock.onAckError = { event, error in … }`.
1885
+
1886
+ Support inbox and chat core use the same names as the JS SDK too, with `[String: Any]` payloads. Agent routes on `api()` (`getInboxAgentProfile`, `createInternalNote`, `getAgentInboxState`, `agentAssignConversation`, `createConversationNote`, `getConversationSummary`, `getDraftReply`, `getConversationCatchUp`, `setConversationTopic`, …) and `listMyChatLinks` / `announceGift` need `memberToken`. `setLinkInboxSettings`, `setLinkDiscoverable` and `setWidgetConfig` need `ownerToken`. `getPresenceStats` / `getLinkAvailability` are public. On the socket: `conversationRead`, `deleteMessage`, `searchAll`, `submitPreChat`, `hopPollClose`, `hopCollabState`, `hopCaptionsToggle`, `hopCaption` and `hopRecordingList`, with listeners `onInternalNote`, `onInternalNoteDeleted`, `onConversationNotesUpdated`, `onConversationRead`, `onMessageDeleted`, `onPreChatSubmitted`, `onThreadUpdate`, `onHopCaptionsState` and `onHopCaptionText`. A 410 link page posts `CHATTA_APP:onLinkUnavailable { state, code }` through the `LiveChattaBridge` message handler.
1887
+
1888
+ Blocked members: every 4xx reaches `client.api().onApiError = { (e: LiveChattaAPIError) in … }` (with `e.statusCode`, `e.code`, `e.path`) just before that call's `(nil, message)` callback, and the async methods throw `LiveChattaAPIError` with `code` set. Compare with `LiveChattaErrorCode.linkMemberBlocked`. On the socket, `LiveChattaSocketAPI.LinkAccess.from(result) == .blocked` reads `linkAccess` from the first `getConversations()` page.
1889
+
1890
+ Devices and quiet hours: `listAccountSessions`, `revokeAccountSession(sessionId:)`, `revokeOtherAccountSessions`, `getAccountQuietHours`, `setAccountQuietHours(payload:)` need `ownerToken`; `listMySessions`, `revokeMySession(sessionId:)`, `revokeMyOtherSessions` need `memberToken`. `getQuietHours` now carries `account` (a dictionary or `NSNull`).
1891
+
1892
+ Calls, links and status: `sendScheduledMessageNow(messageId:)` and `declineHopInvite(sessionId:)` need `memberToken`; `notifyWhenLinkReopens(linkCode:email:)`, `subscribeToStatusUpdates(email:)`, `unsubscribeFromStatusUpdates(email:token:)`, `getWebinarInfo(conversationId:)` and `registerForWebinar(conversationId:payload:)` are public; `testWebhook(webhookId:)` uses the API key. `listMyChatLinks` rows carry `memberCount` and `role`. A full link's 400 has `e.code == LiveChattaErrorCode.linkFull`. On the socket: `hopPinForAll(_:)` and `onHopPinnedForAll`. `LiveChattaIncomingCall(userInfo:)` reads an incoming-call push (register the `LiveChattaIncomingCall.category` notification category; Decline → `api().declineHopInvite(sessionId: call.sessionId)`).
1893
+
1894
+ Guest join: `getLinkOnlineCount(linkCode:)` and `joinLinkAsGuest(linkCode:displayName:email:)` are public; a 400 with `code == LiveChattaErrorCode.accountExists` from join-guest or join-new means sign in through join-exist instead.
1895
+
1896
+ Exports and links: `exportConversationAsMember(conversationId:payload:)`, `getMemberExportStatus(conversationId:exportId:)` `leaveMyLink(linkId:)`, `setMyLinkNotify(linkId:level:)` and `listLinkMembers(chatLinkId:limit:)` need `memberToken`; `exportConversationAsOwner(conversationId:payload:)` and `testAutomationKeywords(chatLinkId:keywords:)` need `ownerToken`. Polls take `anonymous`, posts take `allowReplies` and `background`, automations take `REPLY_CANNED` / `ASSIGN_TEAM`.
1897
+
1898
+ Teams, followers, gifts: `listWorkspaceTeams`, `createWorkspaceTeam(payload:)`, `updateWorkspaceTeam(teamId:payload:)`, `deleteWorkspaceTeam(teamId:)`, `inviteTeamMember(payload:)`, `inviteChatUser(payload:)` and `getWebinarRecordingsAsOwner(conversationId:)` need `ownerToken`; `getMemberFollowStatus` / `followMember` / `unfollowMember(linkId:memberId:)`, `redeemMeetingGuestPass(code:token:)`, `joinMeetingFromChannel(meetingConversationId:)`, `sendPeerGift(payload:)`, `listReceivedGifts(query:)`, `getGiftBalance`, `requestGiftPayout` need `memberToken` (`getGiftCatalog` takes either); `sendPushReply(token:message:)`, `requestWebinarRecordingLink(conversationId:email:)`, `getWebinarRecording(conversationId:token:)` and `verifyPeerGift(reference:)` are public.
1899
+
1900
+ Modes: `setLinkMode(linkId:payload:)` needs `ownerToken`; `setConversationMode(conversationId:mode:)` takes the member or owner token; `getPublicLinkInfo(linkCode:)` is public (`mode`, `joinPolicy`). Join refusals carry `LiveChattaErrorCode.emailRequired` (400) or `LiveChattaErrorCode.inviteOnly` (403); `startConversation` accepts `mode` and `category`.
1901
+
1902
+ Support CSAT, invite-only links and recordings: `submitCsat` (memberToken), `listCsatRatings` / `getCsatSummary` (API key; `*AsOwner` with ownerToken), `getLinkMemberList(linkId:query:)` with `["status": "invited"]` and `revokeLinkInvite` (ownerToken), `getRecordingDownloadLink(messageId:)` (memberToken), each with a `*Typed` twin, plus `getAppVersionTyped` and `onCsatUpdated`. `LiveChattaSocketAPI.LinkAccess.from(result) == .inviteOnly` reads `linkAccess: 'invite-only'`. Codes: `LiveChattaErrorCode.rateLimited` (429 send burst), `.recordingDownloadOff`, `.recordingDownloadExpired`.
1903
+
1904
+ Ask to join, channels, support teams, webhooks (1.2.0): `getLinkChannels(linkCode:)`, `getGiftStoreData(linkCode:)` and `requestToJoinLink(linkCode:name:email:message:)` are public; `createAccountChatLink(payload:)` (with `modeOptions`), `setLinkJoinPolicy(linkId:payload:)`, `listJoinRequests(linkId:query:)`, `approveJoinRequest` / `denyJoinRequest(linkId:requestId:)`, `getWebhookDeliveries(webhookId:limit:)`, `retryWebhookDelivery(webhookId:deliveryId:)`, `rotateWebhookSecret(webhookId:)` and `getAdminMentionsAsOwner(query:)` (`handles`, `q`) need `ownerToken`; `getSupportGroupTeam(conversationId:)` / `setSupportGroupTeam(conversationId:teamId:)` (nil stops routing) need `memberToken`. New codes: `LiveChattaErrorCode.approvalOff`, `.handleTaken`, `.adminNoAccess`, `.planNotFound`, `.planNotAvailable`, `.planTeamActivated`. Socket: `onHopInviteAnswered`, `onHopUnmuteRequested`; the `joinHop` ack has `canProduce`, `onHopYouWereDropped` may carry `reason: "moved"`.
1905
+
1906
+ 1.2.1: `inviteToHop(sessionId:chatUserIds:)` (memberToken, socket ring + push), `getAdminMentions(query:)` takes `handles` and `q` with the API key too, and hop reaction / vote / raise-hand / poll-vote acks may be `["ok": false, "error": LiveChattaErrorCode.hopRateLimited]`.
1907
+
1908
+ 1.2.2: `requestBusinessPasswordReset(identifier:)`, `resetBusinessPassword(token:newPassword:confirmPassword:)`, `getPasswordResetStatus(token:)`, `requestChatPasswordReset(identifier:chatLinkCode:)`, `resetChatPassword(…)`, `requestLinkPasswordReset(linkCode:identifier:)`, `resetLinkPassword(linkCode:…)` are public. **Breaking:** socket `forgotPassword` needs `["identifier", "chatLinkCode"]`; `resetPassword` takes `token`, `newPassword`, `confirmPassword`.
1909
+
1910
+ 1.3.0 (ownerToken): `getTrialStatus`, `startTrial(planId:billingCycle:)`, `getRenewalStatus`, `renewSubscription(subscriptionId:paymentMethod:)`, `useBankTransferRenewals`, `listStaffAccess(query:)`, `getOwnerGifts(query:)`; `subscribeToPlan(planId:billingCycle:paymentMethod:)`; `getStorageUsage` takes the member or owner token. Upload refusals carry `LiveChattaErrorCode.storageLimit`. Gift catalog and received rows no longer carry fee fields.
1911
+
1912
+ 1.3.1: `registerDevice(payload:)` (pass the PushKit hex token as `voipToken` so calls ring through CallKit) and public `pushDeclineCall(token:)` for CallKit's Decline. `LiveChattaIncomingCall` gains `media`, `declineToken`, `declineUrl`; `LiveChattaCallCancel(userInfo:)` reads `HOP_INVITE_CANCEL` (also inside the VoIP payload) to end the CallKit call.
1913
+
1914
+ 1.3.2: `getConversations` pages hold 40 (`LiveChattaSocketAPI.Sidebar.pageSize`). `getUnreadTotals(excludeConversationIds:callback:)` acks `["unreadTotals": …]`; `Sidebar.unreadTotal(result)` reads the total from it or from the first page. Deep links: `["chatConversationByCodes": code]`.
1915
+
1916
+ Owner console and preferences: `testWebhookAsOwner(webhookId:)`, `listAccountChatLinks(query:)` (e.g. `["chatLinkExpiringDays": "7"]`) and `updateAccountProfile(payload:)` (preferences `notifyTopics`, `language`, `translateIncomingTo` with `"off"` to disable, `soundPreferences`) need `ownerToken`. `updateChatLink` takes `settings.defaultLayout` (`bubbles` | `lines`); settings merge key by key (allowlist: `maxMembers`, `allow*`, `welcomeMessage`, `defaultLayout`, `hideRunsOn`). `createAutomation` / `updateAutomation` take `triggerConfig.keywords` and up to 3 `extraActions`.
1917
+
1918
+ #### Embedded UI (WebView)
1919
+
1920
+ ```swift
1921
+ let chatView = LiveChattaWebView(frame: view.bounds)
1922
+ chatView.configure(
1923
+ linkCode: "your-link-code",
1924
+ apiKey: "your-api-key",
1925
+ publicKey: "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----",
1926
+ chatUsername: "john_doe",
1927
+ primaryColor: "D2400B", // optional: omit for the link's colour (else Signal)
1928
+ secondaryColor: "0B6E66", // optional
1929
+ theme: "system" // "light" (default) | "dark" | "system"
1930
+ )
1931
+ chatView.onMessage = { data in print(data) }
1932
+ view.addSubview(chatView)
1933
+ ```
1934
+
1935
+ `primaryColor` / `secondaryColor` are now `String?` (default `nil`); existing calls compile unchanged. `layout: "bubbles" | "lines"` is also accepted.
1936
+
1937
+ ### Flutter (Dart)
1938
+
1939
+ #### Headless Mode (Native SDK)
1940
+
1941
+ ```dart
1942
+ import 'package:livechatta/livechatta_client.dart';
1943
+
1944
+ final client = LiveChattaClient();
1945
+ client.initialize(LiveChattaOptions(
1946
+ linkCode: 'your-link-code',
1947
+ apiKey: 'your-api-key',
1948
+ publicKey: '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----',
1949
+ chatUsername: 'john_doe',
1950
+ ));
1951
+
1952
+ await client.connect();
1953
+
1954
+ // Real-time messaging
1955
+ client.sock().onMessage((data) => print('Message: $data'));
1956
+ client.sock().sendMessage({
1957
+ 'conversationId': 'conv123',
1958
+ 'senderId': 'user456',
1959
+ 'referenceId': uuid.v4(),
1960
+ 'message': 'Hello from Flutter!',
1961
+ }, callback: (response) => print('Sent: $response'));
1962
+
1963
+ // REST operations
1964
+ final members = await client.api().listMembers();
1965
+ print('Members: $members');
1966
+ ```
1967
+
1968
+ Requires in `pubspec.yaml`:
1969
+ - `socket_io_client: ^2.0.0`
1970
+ - `http: ^1.0.0`
1971
+ - `pointycastle: ^3.7.0` (optional — for RSA-OAEP token encryption)
1972
+
1973
+ Content features (owner methods need `LiveChattaOptions(ownerToken: …)` or `client.api().ownerToken = …`):
1974
+
1975
+ ```dart
1976
+ final api = client.api();
1977
+ final pack = await api.getLinkEmojiPack('acme-help'); // {linkId, emojis, stickers}
1978
+ await api.createLinkEmoji(linkId, {'kind': 'emoji', 'shortcode': 'party_parrot',
1979
+ 'image': 'data:image/png;base64,…'});
1980
+ await api.schedulePost(postId, {'scheduledAt': '2026-12-01T09:00:00Z'});
1981
+ final click = await api.trackPromoClick(postId, visitorId: storedVisitorId); // then open click['url']
1982
+ final stats = await api.getPromoAnalytics(postId);
1983
+ ```
1984
+
1985
+ Also: `listLinkEmojis`, `updateLinkEmoji`, `enable/disable/deleteLinkEmoji`, `createPost`, `listPosts`, `publishPost`, `cancelPostSchedule`. Persist `visitorId` with `shared_preferences`.
1986
+
1987
+ Chat features: socket methods (`messageDelivered`, `muteConversation`, `huddleStart`, `transcribeMessage`, `onHuddleUpdated`, …) take `Map<String, dynamic>` payloads; REST twins on `api()` use `memberToken` / `ownerToken` per the auth table above (`LiveChattaOptions(memberToken: …)`); pass `{'assigneeId': null}` to unassign. A denied emit calls its callback with `null` and fires `sock.onAckError = (event, error) { … }`.
1988
+
1989
+ Support inbox and chat core use the same names as the JS SDK too, with `Map<String, dynamic>` payloads. Agent routes on `api()` (`getInboxAgentProfile`, `createInternalNote`, `getAgentInboxState`, `agentAssignConversation`, `createConversationNote`, `getConversationSummary`, `getDraftReply`, `getConversationCatchUp`, `setConversationTopic`, …) and `listMyChatLinks` / `announceGift` need `memberToken`. `setLinkInboxSettings`, `setLinkDiscoverable` and `setWidgetConfig` need `ownerToken`. `getPresenceStats` / `getLinkAvailability` are public. On the socket: `conversationRead`, `deleteMessage`, `searchAll`, `submitPreChat`, `hopPollClose`, `hopCollabState`, `hopCaptionsToggle`, `hopCaption` and `hopRecordingList`, with listeners `onInternalNote`, `onInternalNoteDeleted`, `onConversationNotesUpdated`, `onConversationRead`, `onMessageDeleted`, `onPreChatSubmitted`, `onThreadUpdate`, `onHopCaptionsState` and `onHopCaptionText`. A 410 link page posts `CHATTA_APP:onLinkUnavailable { state, code }` to the WebView `onMessage` callback.
1990
+
1991
+ Blocked members: 4xx calls throw `LiveChattaApiError` with `statusCode`, `code` and `path`; compare `e.code` with `LiveChattaErrorCodes.linkMemberBlocked`. On the socket, `LiveChattaSocketAPI.isLinkBlocked(result)` reads `linkAccess` from the first `getConversations()` page.
1992
+
1993
+ Devices and quiet hours: `listAccountSessions()`, `revokeAccountSession(sessionId)`, `revokeOtherAccountSessions()`, `getAccountQuietHours()`, `setAccountQuietHours(payload)` need `ownerToken`; `listMySessions()`, `revokeMySession(sessionId)`, `revokeMyOtherSessions()` need `memberToken`. `getQuietHours()` now carries `account` (a map or `null`).
1994
+
1995
+ Calls, links and status: `sendScheduledMessageNow(messageId)` and `declineHopInvite(sessionId)` need `memberToken`; `notifyWhenLinkReopens(linkCode, email)`, `subscribeToStatusUpdates(email)`, `unsubscribeFromStatusUpdates(email, token)`, `getWebinarInfo(conversationId)` and `registerForWebinar(conversationId, payload)` are public; `testWebhook(webhookId)` uses the API key. `listMyChatLinks()` rows carry `memberCount` and `role`. A full link throws `LiveChattaApiError` with `code == LiveChattaErrorCodes.linkFull`. On the socket: `hopPinForAll(data)` and `onHopPinnedForAll`. `LiveChattaIncomingCall.fromData(message.data)` reads an incoming-call push (channel `LiveChattaIncomingCall.androidChannel`; Decline → `api().declineHopInvite(call.sessionId)`).
1996
+
1997
+ Guest join: `getLinkOnlineCount(linkCode)` and `joinLinkAsGuest(linkCode, displayName, email: …)` are public; a 400 with `code == LiveChattaErrorCodes.accountExists` from join-guest or join-new means sign in through join-exist instead.
1998
+
1999
+ Exports and links: `exportConversationAsMember(conversationId, payload)`, `getMemberExportStatus(conversationId, exportId)` `leaveMyLink(linkId)`, `setMyLinkNotify(linkId, level)` and `listLinkMembers(chatLinkId, limit)` need `memberToken`; `exportConversationAsOwner(conversationId, payload)` and `testAutomationKeywords(chatLinkId, keywords)` need `ownerToken`. Polls take `anonymous`, posts take `allowReplies` and `background`.
2000
+
2001
+ Teams, followers, gifts: `listWorkspaceTeams()`, `createWorkspaceTeam(payload)`, `updateWorkspaceTeam(teamId, payload)`, `deleteWorkspaceTeam(teamId)`, `inviteTeamMember(payload)`, `inviteChatUser(payload)` and `getWebinarRecordingsAsOwner(conversationId)` need `ownerToken`; `getMemberFollowStatus` / `followMember` / `unfollowMember(linkId, memberId)`, `redeemMeetingGuestPass(code, token)`, `joinMeetingFromChannel(meetingConversationId)`, `sendPeerGift(payload)`, `listReceivedGifts(query: …)`, `getGiftBalance()`, `requestGiftPayout()` need `memberToken` (`getGiftCatalog()` takes either); `sendPushReply(token, message)`, `requestWebinarRecordingLink(conversationId, email)`, `getWebinarRecording(conversationId, token)` and `verifyPeerGift(reference)` are public.
2002
+
2003
+ Modes: `setLinkMode(linkId, payload)` needs `ownerToken`; `setConversationMode(conversationId, mode)` takes the member or owner token; `getPublicLinkInfo(linkCode)` is public (`mode`, `joinPolicy`). Join refusals throw `LiveChattaApiError` with `LiveChattaErrorCodes.emailRequired` (400) or `LiveChattaErrorCodes.inviteOnly` (403); `startConversation` accepts `mode` and `category`.
2004
+
2005
+ Support CSAT, invite-only links and recordings: `submitCsat` (memberToken), `listCsatRatings` / `getCsatSummary` (API key; `*AsOwner` with ownerToken), `getLinkMemberList(linkId, query: {'status': 'invited'})` and `revokeLinkInvite` (ownerToken), `getRecordingDownloadLink(messageId)` (memberToken), each with a `*Typed` twin, plus `getAppVersionTyped` and `onCsatUpdated`. `LiveChattaSocketAPI.isLinkInviteOnly(result)` reads `linkAccess: 'invite-only'`. Codes: `LiveChattaErrorCodes.rateLimited` (429 send burst), `.recordingDownloadOff`, `.recordingDownloadExpired`.
2006
+
2007
+ Ask to join, channels, support teams, webhooks (1.2.0): `getLinkChannels(linkCode)`, `getGiftStoreData(linkCode)` and `requestToJoinLink(linkCode, name, email, message: …)` are public; `createAccountChatLink(payload)` (with `modeOptions`), `setLinkJoinPolicy(linkId, payload)`, `listJoinRequests(linkId, query: …)`, `approveJoinRequest` / `denyJoinRequest(linkId, requestId)`, `getWebhookDeliveries(webhookId, limit: …)`, `retryWebhookDelivery(webhookId, deliveryId)`, `rotateWebhookSecret(webhookId)` and `getAdminMentionsAsOwner(query: …)` (`handles`, `q`) need `ownerToken`; `getSupportGroupTeam(conversationId)` / `setSupportGroupTeam(conversationId, teamId)` (null stops routing) need `memberToken`. New codes: `LiveChattaErrorCodes.approvalOff`, `.handleTaken`, `.adminNoAccess`, `.planNotFound`, `.planNotAvailable`, `.planTeamActivated`. Socket: `onHopInviteAnswered`, `onHopUnmuteRequested`; the `joinHop` ack has `canProduce`, `onHopYouWereDropped` may carry `reason: 'moved'`.
2008
+
2009
+ 1.2.1: `inviteToHop(sessionId, chatUserIds)` (memberToken, socket ring + push), `getAdminMentions(query: …)` takes `handles` and `q` with the API key too, and hop reaction / vote / raise-hand / poll-vote acks may be `{ 'ok': false, 'error': LiveChattaErrorCodes.hopRateLimited }`.
2010
+
2011
+ 1.2.2: `requestBusinessPasswordReset(identifier)`, `resetBusinessPassword(token, newPassword, confirmPassword)`, `getPasswordResetStatus(token)`, `requestChatPasswordReset(identifier, chatLinkCode)`, `resetChatPassword(…)`, `requestLinkPasswordReset(linkCode, identifier)`, `resetLinkPassword(linkCode, …)` are public. **Breaking:** socket `forgotPassword` needs `{'identifier', 'chatLinkCode'}`; `resetPassword` takes `token`, `newPassword`, `confirmPassword`.
2012
+
2013
+ 1.3.0 (ownerToken): `getTrialStatus()`, `startTrial(planId, billingCycle: …)`, `getRenewalStatus()`, `renewSubscription(subscriptionId, paymentMethod: …)`, `useBankTransferRenewals()`, `listStaffAccess(query: …)`, `getOwnerGifts(query: …)`; `subscribeToPlan(planId, billingCycle, paymentMethod: …)`; `getStorageUsage()` takes the member or owner token. Upload refusals carry `LiveChattaErrorCodes.storageLimit`. Gift catalog and received rows no longer carry fee fields.
2014
+
2015
+ 1.3.1: `registerDevice(payload)` and public `pushDeclineCall(token)`. `LiveChattaIncomingCall` gains `media`, `declineToken`, `declineUrl`; `LiveChattaCallCancel.fromData(data)` reads `HOP_INVITE_CANCEL`.
2016
+
2017
+ 1.3.2: `getConversations` pages hold 40 (`LiveChattaSocketAPI.sidebarPageSize`). `getUnreadTotals(excludeConversationIds: …, callback: …)` acks `{ unreadTotals }`; `LiveChattaSocketAPI.unreadTotal(result)` reads the total from it or from the first page. Deep links: `{'chatConversationByCodes': code}`.
2018
+
2019
+ Owner console and preferences: `testWebhookAsOwner(webhookId)`, `listAccountChatLinks(query: {'chatLinkExpiringDays': '7'})` and `updateAccountProfile(payload)` (preferences `notifyTopics`, `language`, `translateIncomingTo` with `'off'` to disable, `soundPreferences`) need `ownerToken`. `updateChatLink` takes `settings.defaultLayout` (`bubbles` | `lines`); settings merge key by key (allowlist: `maxMembers`, `allow*`, `welcomeMessage`, `defaultLayout`, `hideRunsOn`). The Flutter SDK has no automation emitters.
2020
+
2021
+ #### Embedded UI (WebView)
2022
+
2023
+ ```dart
2024
+ import 'package:livechatta/livechatta_webview.dart';
2025
+
2026
+ LiveChattaWebView(
2027
+ linkCode: 'your-link-code',
2028
+ apiKey: 'your-api-key',
2029
+ publicKey: '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----',
2030
+ chatUsername: 'john_doe',
2031
+ primaryColor: 'D2400B', // optional: omit for the link's colour (else Signal)
2032
+ secondaryColor: '0B6E66', // optional
2033
+ theme: 'system', // 'light' (default) | 'dark' | 'system'
2034
+ onMessage: (data) => print('Message: $data'),
2035
+ onError: (error) => print('Error: $error'),
2036
+ )
2037
+ ```
2038
+
2039
+ Requires `webview_flutter: ^4.0.0`. `primaryColor` / `secondaryColor` are now nullable (`String?`); `layout: 'bubbles' | 'lines'` is also accepted.
2040
+
2041
+ RSA token encryption needs `pointycastle: ^3.7.0`; implement `_encryptRSA` in `livechatta_webview.dart` like this (until then the raw API key is sent):
2042
+
2043
+ ```dart
2044
+ import 'dart:typed_data';
2045
+ import 'package:pointycastle/export.dart';
2046
+ import 'package:pointycastle/asn1.dart';
2047
+
2048
+ String _encryptRSA(String pemPublicKey, String data) {
2049
+ final pem = pemPublicKey
2050
+ .replaceAll('-----BEGIN PUBLIC KEY-----', '')
2051
+ .replaceAll('-----END PUBLIC KEY-----', '')
2052
+ .replaceAll(RegExp(r'\s'), '');
2053
+ final top = ASN1Parser(base64Decode(pem)).nextObject() as ASN1Sequence;
2054
+ final bits = top.elements![1] as ASN1BitString;
2055
+ final key = ASN1Parser(Uint8List.fromList(bits.stringValues!)).nextObject() as ASN1Sequence;
2056
+ final modulus = (key.elements![0] as ASN1Integer).integer!;
2057
+ final exponent = (key.elements![1] as ASN1Integer).integer!;
2058
+ final cipher = OAEPEncoding.withSHA256(RSAEngine())
2059
+ ..init(true, PublicKeyParameter<RSAPublicKey>(RSAPublicKey(modulus, exponent)));
2060
+ final out = cipher.process(Uint8List.fromList(utf8.encode(data)));
2061
+ return base64Url.encode(out).replaceAll('=', '');
2062
+ }
2063
+ ```
2064
+
2065
+ ### Angular
2066
+
2067
+ The Angular wrapper is an `@Injectable` service with RxJS Observables for reactive state.
2068
+
2069
+ #### Headless Mode (Service)
2070
+
2071
+ ```typescript
2072
+ import { Component, OnInit, inject } from '@angular/core';
2073
+ import { LiveChattaService } from '@livechatta/sdk/platforms/angular';
2074
+ import { AsyncPipe } from '@angular/common';
2075
+
2076
+ @Component({
2077
+ selector: 'app-chat',
2078
+ standalone: true,
2079
+ imports: [AsyncPipe],
2080
+ template: `
2081
+ <p>Connected: {{ isConnected$ | async }}</p>
2082
+ <button (click)="sendMessage()">Send</button>
2083
+ `,
2084
+ })
2085
+ export class ChatComponent implements OnInit {
2086
+ private chatta = inject(LiveChattaService);
2087
+
2088
+ isConnected$ = this.chatta.isConnected$;
2089
+ connectionState$ = this.chatta.connectionState$;
2090
+
2091
+ ngOnInit() {
2092
+ this.chatta.init({
2093
+ linkCode: 'your-link-code',
2094
+ apiKey: 'your-api-key',
2095
+ publicKey: '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----',
2096
+ chatUsername: 'john_doe',
2097
+ });
2098
+ this.chatta.connect();
2099
+
2100
+ // Subscribe to messages
2101
+ this.chatta.sock()?.onMessage((msg) => console.log('New message:', msg));
2102
+ }
2103
+
2104
+ sendMessage() {
2105
+ this.chatta.sock()?.sendMessage({
2106
+ conversationId: 'conv_id',
2107
+ senderId: 'member_id',
2108
+ referenceId: crypto.randomUUID(),
2109
+ message: 'Hello from Angular!',
2110
+ });
2111
+ }
2112
+ }
2113
+ ```
2114
+
2115
+ #### Embedded UI (Component)
2116
+
2117
+ ```typescript
2118
+ import { LiveChattaEmbedComponent } from '@livechatta/sdk/platforms/angular/embed';
2119
+
2120
+ @Component({
2121
+ imports: [LiveChattaEmbedComponent],
2122
+ template: `
2123
+ <livechatta-embed
2124
+ linkCode="your-link-code"
2125
+ apiKey="your-api-key"
2126
+ chatUsername="john_doe"
2127
+ primaryColor="#D2400B"
2128
+ secondaryColor="#0B6E66"
2129
+ theme="system"
2130
+ height="500px"
2131
+ (embedMessage)="onMessage($event)"
2132
+ (embedError)="onError($event)"
2133
+ />
2134
+ <!-- or the floating launcher -->
2135
+ <livechatta-embed
2136
+ linkCode="your-link-code"
2137
+ apiKey="your-api-key"
2138
+ chatUsername="john_doe"
2139
+ [floating]="true"
2140
+ title="Acme Support"
2141
+ greeting="Hi 👋 Questions about your order?"
2142
+ (openChange)="onOpenChange($event)"
2143
+ />
2144
+ `,
2145
+ })
2146
+ export class ChatPage {
2147
+ onMessage(data: any) { console.log('Message:', data); }
2148
+ onError(err: any) { console.error('Error:', err); }
2149
+ onOpenChange(open: boolean) { console.log('open:', open); }
2150
+ }
2151
+ ```
2152
+
2153
+ Peer dependencies: `@angular/core`, `rxjs`. Service auto-destroys via `ngOnDestroy`.
2154
+
2155
+ ### Vue 3
2156
+
2157
+ The Vue composable uses `ref()`, `computed()`, and `onUnmounted()` for reactive state and auto-cleanup.
2158
+
2159
+ #### Headless Mode (Composable)
2160
+
2161
+ ```vue
2162
+ <script setup lang="ts">
2163
+ import { useLiveChatta } from '@livechatta/sdk/platforms/vue';
2164
+ import { watchEffect } from 'vue';
2165
+
2166
+ const { sock, api, connectionState, isConnected, connect } = useLiveChatta({
2167
+ linkCode: 'your-link-code',
2168
+ apiKey: 'your-api-key',
2169
+ publicKey: '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----',
2170
+ chatUsername: 'john_doe',
2171
+ });
2172
+
2173
+ connect();
2174
+
2175
+ watchEffect(() => {
2176
+ if (!sock.value) return;
2177
+ sock.value.onMessage((msg) => console.log('New message:', msg));
2178
+ sock.value.onTyping((data) => console.log('Typing:', data));
2179
+ });
2180
+
2181
+ const loadMembers = async () => {
2182
+ if (!api.value) return;
2183
+ const members = await api.value.listMembers();
2184
+ console.log(members.results);
2185
+ };
2186
+ </script>
2187
+
2188
+ <template>
2189
+ <p>State: {{ connectionState }}</p>
2190
+ <p>Connected: {{ isConnected }}</p>
2191
+ <button @click="loadMembers">Load Members</button>
2192
+ </template>
2193
+ ```
2194
+
2195
+ #### Embedded UI (Component)
2196
+
2197
+ ```vue
2198
+ <script setup lang="ts">
2199
+ import { LiveChattaView } from '@livechatta/sdk/platforms/vue/view';
2200
+ </script>
2201
+
2202
+ <template>
2203
+ <LiveChattaView
2204
+ linkCode="your-link-code"
2205
+ apiKey="your-api-key"
2206
+ chatUsername="john_doe"
2207
+ primaryColor="#D2400B"
2208
+ secondaryColor="#0B6E66"
2209
+ theme="system"
2210
+ height="500px"
2211
+ @message="(data) => console.log('Message:', data)"
2212
+ @error="(err) => console.error('Error:', err)"
2213
+ />
2214
+ <!-- or the floating launcher -->
2215
+ <LiveChattaView
2216
+ linkCode="your-link-code"
2217
+ apiKey="your-api-key"
2218
+ chatUsername="john_doe"
2219
+ floating
2220
+ title="Acme Support"
2221
+ greeting="Hi 👋 Questions about your order?"
2222
+ @open-change="(open) => console.log('open:', open)"
2223
+ />
2224
+ </template>
2225
+ ```
2226
+
2227
+ Peer dependency: `vue ^3.0.0`. Auto-destroys on component unmount via `onUnmounted`.
2228
+
2229
+ ### Nuxt 3
2230
+
2231
+ SSR-safe version of the Vue wrapper. Returns inert state on the server (null `sock`/`api`, `DISCONNECTED` state, no-op methods) and initializes the SDK only on the client.
2232
+
2233
+ #### Headless Mode (Composable)
2234
+
2235
+ ```vue
2236
+ <script setup lang="ts">
2237
+ import { useLiveChatta } from '@livechatta/sdk/platforms/nuxt';
2238
+ import { watchEffect, onMounted } from 'vue';
2239
+
2240
+ const { sock, api, connectionState, isConnected, connect } = useLiveChatta({
2241
+ linkCode: 'your-link-code',
2242
+ apiKey: 'your-api-key',
2243
+ publicKey: '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----',
2244
+ chatUsername: 'john_doe',
2245
+ });
2246
+
2247
+ // Connect only on client (onMounted never fires on server)
2248
+ onMounted(() => connect());
2249
+
2250
+ watchEffect(() => {
2251
+ if (!sock.value) return;
2252
+ sock.value.onMessage((msg) => console.log('New message:', msg));
2253
+ sock.value.onTyping((data) => console.log('Typing:', data));
2254
+ });
2255
+
2256
+ const loadMembers = async () => {
2257
+ if (!api.value) return;
2258
+ const members = await api.value.listMembers();
2259
+ console.log(members.results);
2260
+ };
2261
+ </script>
2262
+
2263
+ <template>
2264
+ <p>State: {{ connectionState }}</p>
2265
+ <p>Connected: {{ isConnected }}</p>
2266
+ <button @click="loadMembers">Load Members</button>
2267
+ </template>
2268
+ ```
2269
+
2270
+ #### Embedded UI (Component)
2271
+
2272
+ ```vue
2273
+ <script setup lang="ts">
2274
+ import { LiveChattaView } from '@livechatta/sdk/platforms/nuxt/view';
2275
+ </script>
2276
+
2277
+ <template>
2278
+ <ClientOnly>
2279
+ <LiveChattaView
2280
+ linkCode="your-link-code"
2281
+ apiKey="your-api-key"
2282
+ chatUsername="john_doe"
2283
+ primaryColor="#D2400B"
2284
+ secondaryColor="#0B6E66"
2285
+ theme="system"
2286
+ height="500px"
2287
+ @message="(data) => console.log('Message:', data)"
2288
+ @error="(err) => console.error('Error:', err)"
2289
+ />
2290
+ </ClientOnly>
2291
+ </template>
2292
+ ```
2293
+
2294
+ The floating launcher works the same way (`floating`, `title`, `greeting`, `@open-change`). Peer dependency: `nuxt ^3.0.0` (includes `vue ^3.0.0`). Wrap the embed component with `<ClientOnly>` for SSR safety. Auto-destroys on component unmount via `onUnmounted`.
2295
+
2296
+ ### Svelte
2297
+
2298
+ The Svelte wrapper is a store factory returning readable stores and SDK methods.
2299
+
2300
+ #### Headless Mode (Store Factory)
2301
+
2302
+ ```svelte
2303
+ <script>
2304
+ import { createLiveChatta } from '@livechatta/sdk/platforms/svelte';
2305
+ import { onDestroy } from 'svelte';
2306
+
2307
+ const chatta = createLiveChatta({
2308
+ linkCode: 'your-link-code',
2309
+ apiKey: 'your-api-key',
2310
+ publicKey: '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----',
2311
+ chatUsername: 'john_doe',
2312
+ });
2313
+
2314
+ chatta.connect();
2315
+ onDestroy(() => chatta.destroy());
2316
+
2317
+ $: if ($chatta.isConnected) {
2318
+ chatta.sock()?.onMessage((msg) => console.log('New message:', msg));
2319
+ }
2320
+ </script>
2321
+
2322
+ <p>State: {$chatta.connectionState}</p>
2323
+ <p>Connected: {$chatta.isConnected}</p>
2324
+ ```
2325
+
2326
+ #### Embedded UI (Action)
2327
+
2328
+ ```svelte
2329
+ <script>
2330
+ import { livechattaEmbed } from '@livechatta/sdk/platforms/svelte/embed';
2331
+ </script>
2332
+
2333
+ <div
2334
+ use:livechattaEmbed={{
2335
+ linkCode: 'your-link-code',
2336
+ apiKey: 'your-api-key',
2337
+ chatUsername: 'john_doe',
2338
+ primaryColor: '#D2400B',
2339
+ secondaryColor: '#0B6E66',
2340
+ theme: 'system',
2341
+ height: '500px',
2342
+ // floating: true, title: 'Acme Support', greeting: 'Hi 👋 Need help?',
2343
+ onMessage: (data) => console.log('Message:', data),
2344
+ onError: (err) => console.error('Error:', err),
2345
+ }}
2346
+ />
2347
+ ```
2348
+
2349
+ Peer dependency: `svelte ^3.0.0 || ^4.0.0 || ^5.0.0`. Call `destroy()` in `onDestroy` for cleanup.
2350
+
2351
+ ## Connection Lifecycle
2352
+
2353
+ ```typescript
2354
+ // Check status
2355
+ LiveChatta.isInitialized(); // boolean
2356
+ LiveChatta.isConnected(); // boolean
2357
+ LiveChatta.getConnectionState(); // 'DISCONNECTED' | 'CONNECTING' | 'CONNECTED' | 'RECONNECTING'
2358
+ LiveChatta.getConfig(); // Config | null
2359
+
2360
+ // SDK lifecycle events
2361
+ LiveChatta.on('sdk:connected', () => { ... });
2362
+ LiveChatta.on('sdk:disconnected', ({ reason }) => { ... });
2363
+ LiveChatta.on('sdk:reconnecting', ({ attempt }) => { ... });
2364
+ LiveChatta.on('sdk:reconnected', ({ attempt }) => { ... });
2365
+ LiveChatta.on('sdk:error', ({ error }) => { ... });
2366
+ LiveChatta.on('sdk:queue-flush', ({ count }) => { ... });
2367
+
2368
+ // Disconnect WebSocket
2369
+ LiveChatta.disconnect();
2370
+
2371
+ // Destroy everything — disconnect, unmount, cleanup
2372
+ LiveChatta.destroy();
2373
+ ```
2374
+
2375
+ ## Offline Message Queue
2376
+
2377
+ When the socket disconnects, emits are automatically queued and flushed on reconnect:
2378
+
2379
+ ```typescript
2380
+ // This will queue if disconnected, and auto-send when reconnected
2381
+ await LiveChatta.sock().sendMessage({
2382
+ conversationId: '...',
2383
+ senderId: '...',
2384
+ referenceId: crypto.randomUUID(),
2385
+ message: 'Hello!',
2386
+ });
2387
+
2388
+ // Listen for queue flush
2389
+ LiveChatta.on('sdk:queue-flush', ({ count }) => {
2390
+ console.log(`Flushed ${count} queued messages`);
2391
+ });
2392
+ ```
2393
+
2394
+ **Queue semantics:**
2395
+
2396
+ - Emits made while the socket is `CONNECTING` or `DISCONNECTED` are queued (up
2397
+ to 100; the 101st rejects with `queue full`).
2398
+ - The queue flushes on the **first successful connect** and on every
2399
+ subsequent reconnect — so emits made before the initial connection completes
2400
+ are delivered, not stranded.
2401
+ - Calling `LiveChatta.disconnect()` (or `destroy()`) while emits are still
2402
+ queued **rejects** those pending promises with a
2403
+ `Socket disconnected before flush` error, so awaited emits always settle
2404
+ instead of hanging.
2405
+
2406
+ ## CLI
2407
+
2408
+ The package ships a small `chatta` command for integrators (no extra dependencies):
2409
+
2410
+ ```bash
2411
+ chatta login --api-key-stdin < key.txt # verify + save (0600)
2412
+ chatta login --email ada@acme.com # owner sign-in code, then --code 123456
2413
+ chatta links list
2414
+ chatta links create --name "Acme Support" --type SINGLE
2415
+ chatta links mode get acme-help # public: mode + join rules
2416
+ chatta links mode set <linkId> support --apply-defaults
2417
+ chatta links join-policy <linkId> --approval on # Ask to join on a private link
2418
+ chatta links requests list <linkId> # then: links requests approve|deny <linkId> <requestId>
2419
+ chatta links channels acme-server # public channel preview
2420
+ chatta conversations mode set <conversationId> broadcast
2421
+ chatta conversations visibility set <conversationId> private # or public; get shows which (groups and channels, owner token)
2422
+ chatta teams list
2423
+ chatta teams create --name Refunds --members <userId>,<userId>
2424
+ chatta plan request --name "Ada" --email ada@acme.com --features SSO,WHITE_LABEL
2425
+ chatta store list
2426
+ chatta gifts catalog
2427
+ chatta gifts earnings # paid gifts, platform fee and net (owner)
2428
+ chatta gifs search well done # GIF search (the LiveChatta pack answers when no provider is set; --source livechatta|provider)
2429
+ chatta gifs trending
2430
+ chatta shared list --link <linkId> # channels shared with other workspaces (member token)
2431
+ chatta shared accept <id> --link <linkId> --audience all --yes
2432
+ chatta shared leave <id> --link <linkId> --yes
2433
+ chatta hooks create <conversationId> --name Deploys # secret post URL for a group or channel, printed once
2434
+ chatta hooks list <conversationId>
2435
+ LIVECHATTA_HOOK_URL=https://…/hooks/in/lhk_… chatta hooks send "Deploy finished" # or pipe the URL: … | chatta hooks send "Deploy finished" --url-stdin
2436
+ chatta billing storage # this month's uploads against the allowance
2437
+ chatta billing renewal # then: billing renew <subscriptionId> [--method card]
2438
+ chatta billing trial # then: billing trial start --plan <planId>
2439
+ chatta security staff-access # when LiveChatta staff viewed or acted in your account
2440
+ chatta security grant on --mode view --hours 24 # let LiveChatta support in; `security grant off` ends it
2441
+ chatta liveflex # business LiveFlex balance, payout details and limits
2442
+ chatta liveflex fund 50 [--crypto] # checkout link to add money
2443
+ chatta liveflex withdraw 25 --method bank --quote # fee and total, nothing sent; --yes locks the total it just quoted (FEES_CHANGED stops it if fees moved)
2444
+ chatta liveflex withdraw 25 --method bank --yes
2445
+ chatta embed snippet --link acme-help --greeting "Hi, need help?" --primary '#0B6E66'
2446
+ printf %s "$WEBHOOK_SECRET" | chatta webhooks test https://example.com/hook --event message:send --secret-stdin
2447
+ chatta webhooks deliveries <webhookId> # then: webhooks retry <webhookId> <deliveryId>
2448
+ chatta webhooks rotate-secret <webhookId> # prints the new secret once
2449
+ chatta links code acme-help # is the code free? suggestions if not
2450
+ chatta links domain <linkId> set chat.acme.com # then: links domain <linkId> verify
2451
+ chatta keys create --name Site --origins https://acme.com
2452
+ chatta keys rotate <keyId> --yes # 1.5.7: prints the new key once; also keys revoke, keys usage
2453
+ chatta messages tail <conversationId> # 1.7.0: new messages as they arrive (owner token), Ctrl-C to stop
2454
+ chatta meetings list --link <linkId> # then: meetings schedule --link <linkId> --title Standup --start 2026-12-01T15:00:00Z --invitees ada@acme.com [--idempotency-key k to make a re-run safe]
2455
+ chatta meetings cancel <meetingId> --yes # invitees are told; safe to repeat
2456
+ chatta webhooks listen <webhookId> --forward http://localhost:3000/hook # real deliveries to your laptop (localhost only; only the signature is forwarded)
2457
+ ```
2458
+
2459
+ Full reference: [docs/cli.md](docs/cli.md).
2460
+
2461
+ ## Build Commands
2462
+
2463
+ ```bash
2464
+ # Install dependencies
2465
+ yarn install
2466
+
2467
+ # Type-check
2468
+ yarn typecheck
2469
+
2470
+ # Build (ESM + CJS + UMD)
2471
+ yarn build
2472
+
2473
+ # Build minified
2474
+ yarn build:min
2475
+
2476
+ # Build all (minified + unminified)
2477
+ yarn build:all
2478
+
2479
+ # Single format
2480
+ yarn build:esm
2481
+ yarn build:cjs
2482
+ yarn build:umd
2483
+
2484
+ # Check bundle size (brotli; budgets in package.json `size-limit`)
2485
+ yarn size
2486
+ ```
2487
+
2488
+ CI runs `yarn test`, `yarn build:esm`, `yarn publish:dry` and `yarn size` on every push and PR.
2489
+ Budgets: 34 kB for `dist/esm/livechatta.esm.min.js`, 36 kB for the UMD bundle (brotli, minified).
2490
+ `socket.io-client` is a peer dependency, so it is not counted. These are revisited (with headroom,
2491
+ not a bare-minimum fit) whenever a feature pushes the measured size past ~90% of the budget — see
2492
+ `CHANGELOG.md` for when a budget last moved and why.
2493
+
2494
+ `sideEffects: false` plus named exports mean a consumer bundling with webpack/rollup/esbuild and
2495
+ importing only `HttpAPI`/`SocketAPI` (skipping `Launcher`/`EmbedUI`) is tree-shaken down by their own
2496
+ bundler; the budgets above measure the full `.` entry point (every export, including the embed UI),
2497
+ which is the worst case, not what every integration actually ships.
2498
+
2499
+ ### Output Structure
2500
+
2501
+ ```
2502
+ dist/
2503
+ esm/
2504
+ livechatta.esm.js
2505
+ livechatta.esm.min.js
2506
+ cjs/
2507
+ livechatta.cjs.js
2508
+ livechatta.cjs.min.js
2509
+ umd/
2510
+ livechatta.umd.js
2511
+ livechatta.umd.min.js
2512
+ types/
2513
+ index.d.ts
2514
+ ...
2515
+ platforms/
2516
+ angular/
2517
+ vue/
2518
+ nuxt/
2519
+ svelte/
2520
+ react/
2521
+ react-native/
2522
+ android/
2523
+ ios/
2524
+ flutter/
2525
+ web/
2526
+ ```
2527
+
2528
+ ## Publishing
2529
+
2530
+ Releases go out from a pushed tag to npm, Maven Central, pub.dev and SwiftPM, after a person approves them.
2531
+ `node scripts/release.mjs minor` bumps every version and the changelog; [docs/PUBLISHING.md](docs/PUBLISHING.md) lists the steps and every secret.
2532
+ To publish from your own machine, run `./release.sh` (or `yarn run release`) on a clean, up-to-date `development`. It bumps from the newest version on npm or GitHub (`--low` 1.0.x is the default, `--mid` 1.x.0, `--major` x.0.0), builds and tests, packs the `.tgz`, publishes it to npm (using `NPM_TOKEN` if set, otherwise `npm login`), pushes the `vX.Y.Z` tag and creates the GitHub release. Try `./release.sh --dry-run` first.
2533
+
2534
+ ```bash
2535
+ # Typecheck, minified build and the npm file listing, without publishing
2536
+ yarn publish:dry
2537
+ ```
2538
+
2539
+ The `prepublishOnly` script runs the typecheck and minified build before every publish. Spec files are
2540
+ not part of the typecheck (vitest transpiles them), so the build needs no `@types/node`.
2541
+
2542
+ ## Versioning
2543
+
2544
+ This SDK follows [semver](https://semver.org/): patch for fixes and docs, minor for additive methods/
2545
+ types/fields, major for anything that breaks a typed consumer (a removed/renamed field, a method's
2546
+ signature or required payload changing, an error shape changing). A minor release that includes a
2547
+ breaking change for typed consumers still calls it out under an explicit "⚠ Breaking" heading in
2548
+ `CHANGELOG.md` — see the 1.2.2, 1.3.0 and 1.3.1 entries for examples — because the TypeScript compiler
2549
+ would not otherwise catch every such change (string-keyed socket payloads on the native SDKs,
2550
+ for instance, break at runtime, not at compile time).
2551
+
2552
+ Every release is recorded in `CHANGELOG.md` before it is read: what server PR(s) it tracks, what's
2553
+ Added/Changed/Fixed, and which native SDKs (Kotlin, Swift, Dart) and CLI got the matching surface.
2554
+ `CHANGELOG.md` ships inside the published npm package (see `files` in `package.json`), so
2555
+ `node_modules/@livechatta/sdk/CHANGELOG.md` is always available offline, not just on GitHub.
2556
+
2557
+ ## License
2558
+
2559
+ MIT