stream-chat 10.0.0-rc.2 → 10.0.0-rc.21

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 (298) hide show
  1. package/README.md +11 -8
  2. package/dist/cjs/index.browser.js +15397 -12090
  3. package/dist/cjs/index.browser.js.map +4 -4
  4. package/dist/cjs/index.node.js +15349 -11991
  5. package/dist/cjs/index.node.js.map +4 -4
  6. package/dist/esm/index.mjs +15164 -11880
  7. package/dist/esm/index.mjs.map +4 -4
  8. package/dist/types/ChannelManager.d.ts +246 -6
  9. package/dist/types/CooldownTimer.d.ts +22 -8
  10. package/dist/types/EventHandlerPipeline.d.ts +12 -16
  11. package/dist/types/LiveLocationManager.d.ts +69 -6
  12. package/dist/types/api-client.d.ts +22 -9
  13. package/dist/types/channel.d.ts +550 -300
  14. package/dist/types/channel_state.d.ts +167 -22
  15. package/dist/types/client.d.ts +325 -305
  16. package/dist/types/configuration/ConfigController.d.ts +172 -0
  17. package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +192 -0
  18. package/dist/types/configuration/index.d.ts +3 -0
  19. package/dist/types/configuration/keys.d.ts +31 -0
  20. package/dist/types/configuration/shape.d.ts +58 -0
  21. package/dist/types/configuration/types.d.ts +206 -50
  22. package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +59 -0
  23. package/dist/types/configuration/utils/copyConfigPatch.d.ts +1 -0
  24. package/dist/types/configuration/utils/declarativeSlices.d.ts +24 -0
  25. package/dist/types/configuration/utils/deepFreezeConfig.d.ts +22 -0
  26. package/dist/types/configuration/utils/index.d.ts +1 -0
  27. package/dist/types/configuration/utils/serverAuthority.d.ts +49 -0
  28. package/dist/types/connection/ConnectionIdManager.d.ts +67 -0
  29. package/dist/types/connection/ConnectionRecoveryManager.d.ts +164 -0
  30. package/dist/types/connection/index.d.ts +4 -0
  31. package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +153 -0
  32. package/dist/types/connection/networkConnection/index.d.ts +3 -0
  33. package/dist/types/connection/networkConnection/reporters.d.ts +43 -0
  34. package/dist/types/connection/networkConnection/types.d.ts +55 -0
  35. package/dist/types/connection/wsConnection/StableWSConnection.d.ts +204 -0
  36. package/dist/types/connection/wsConnection/WSConnection.d.ts +168 -0
  37. package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +55 -0
  38. package/dist/types/connection/wsConnection/config.d.ts +51 -0
  39. package/dist/types/connection/wsConnection/index.d.ts +4 -0
  40. package/dist/types/connection/wsConnection/types.d.ts +99 -0
  41. package/dist/types/constants.d.ts +3 -1
  42. package/dist/types/entityStore/EntityStore.d.ts +160 -40
  43. package/dist/types/entityStore/StoreBackedItemIndex.d.ts +48 -29
  44. package/dist/types/entityStore/index.d.ts +0 -1
  45. package/dist/types/errors.d.ts +24 -4
  46. package/dist/types/formatMessageMemo.d.ts +5 -0
  47. package/dist/types/gen/chat/ChannelApi.d.ts +51 -23
  48. package/dist/types/gen/chat/ChatApi.d.ts +215 -168
  49. package/dist/types/gen/models/index.d.ts +2164 -557
  50. package/dist/types/gen/models/timestamp-guard.d.ts +22 -0
  51. package/dist/types/gen/moderation/ModerationApi.d.ts +39 -32
  52. package/dist/types/gen-imports.d.ts +1 -0
  53. package/dist/types/index.d.ts +20 -7
  54. package/dist/types/languageNames.d.ts +97 -0
  55. package/dist/types/logger.d.ts +1 -1
  56. package/dist/types/messageComposer/CustomDataManager.d.ts +7 -1
  57. package/dist/types/messageComposer/LocationComposer.d.ts +10 -4
  58. package/dist/types/messageComposer/attachmentIdentity.d.ts +11 -0
  59. package/dist/types/messageComposer/attachmentManager.d.ts +48 -10
  60. package/dist/types/messageComposer/attachmentUtils.d.ts +34 -0
  61. package/dist/types/messageComposer/configuration/commands.configuration.d.ts +1 -3
  62. package/dist/types/messageComposer/configuration/configuration.d.ts +9 -1
  63. package/dist/types/messageComposer/configuration/index.d.ts +0 -1
  64. package/dist/types/messageComposer/configuration/types.d.ts +57 -1
  65. package/dist/types/messageComposer/index.d.ts +1 -0
  66. package/dist/types/messageComposer/linkPreviewsManager.d.ts +10 -4
  67. package/dist/types/messageComposer/messageComposer.d.ts +210 -14
  68. package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +20 -1
  69. package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +11 -0
  70. package/dist/types/messageComposer/middleware/messageComposer/types.d.ts +2 -2
  71. package/dist/types/messageComposer/middleware/pollComposer/index.d.ts +1 -0
  72. package/dist/types/messageComposer/middleware/pollComposer/state.d.ts +3 -2
  73. package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +9 -2
  74. package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +44 -0
  75. package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +2 -2
  76. package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +94 -229
  77. package/dist/types/messageComposer/pollComposer.d.ts +8 -3
  78. package/dist/types/messageComposer/textComposer.d.ts +9 -1
  79. package/dist/types/messageComposer/types.d.ts +7 -3
  80. package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +64 -8
  81. package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +48 -11
  82. package/dist/types/messageOperations/FailedSendCache.d.ts +34 -0
  83. package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +52 -6
  84. package/dist/types/messageOperations/MessageOperations.d.ts +94 -11
  85. package/dist/types/{entityStore → messageOperations}/applyReactionLocally.d.ts +8 -2
  86. package/dist/types/messageOperations/createMessageOperations.d.ts +11 -0
  87. package/dist/types/messageOperations/index.d.ts +7 -1
  88. package/dist/types/messageOperations/reflectReactionEvent.d.ts +24 -0
  89. package/dist/types/messageOperations/sendOrdering.d.ts +17 -0
  90. package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +28 -0
  91. package/dist/types/messageOperations/types.d.ts +66 -1
  92. package/dist/types/middleware.d.ts +8 -0
  93. package/dist/types/moderation.d.ts +18 -4
  94. package/dist/types/notifications/NotificationManager.d.ts +43 -2
  95. package/dist/types/notifications/types.d.ts +55 -42
  96. package/dist/types/offline-support/offline_support_api.d.ts +128 -12
  97. package/dist/types/offline-support/offline_sync_manager.d.ts +26 -5
  98. package/dist/types/offline-support/queueableOperations.d.ts +106 -0
  99. package/dist/types/offline-support/types.d.ts +77 -28
  100. package/dist/types/pagination/FilterBuilder.d.ts +1 -18
  101. package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +2 -1
  102. package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +21 -3
  103. package/dist/types/pagination/filterCompiler.d.ts +5 -0
  104. package/dist/types/pagination/paginators/BasePaginator.d.ts +331 -7
  105. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +54 -11
  106. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +283 -66
  107. package/dist/types/pagination/paginators/MessagePaginator.d.ts +10 -9
  108. package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +17 -1
  109. package/dist/types/pagination/paginators/ReminderPaginator.d.ts +8 -8
  110. package/dist/types/pagination/paginators/ThreadPaginator.d.ts +57 -0
  111. package/dist/types/pagination/paginators/index.d.ts +1 -0
  112. package/dist/types/pagination/utility.normalization.d.ts +29 -2
  113. package/dist/types/poll.d.ts +41 -14
  114. package/dist/types/poll_manager.d.ts +3 -2
  115. package/dist/types/poll_optimistic_votes.d.ts +61 -0
  116. package/dist/types/reminders/Reminder.d.ts +17 -7
  117. package/dist/types/reminders/ReminderManager.d.ts +34 -6
  118. package/dist/types/search/BaseSearchSource.d.ts +50 -25
  119. package/dist/types/search/ChannelMemberSearchSource.d.ts +11 -6
  120. package/dist/types/search/ChannelSearchSource.d.ts +27 -5
  121. package/dist/types/search/MessageSearchSource.d.ts +36 -6
  122. package/dist/types/search/SearchController.d.ts +44 -11
  123. package/dist/types/search/UserSearchSource.d.ts +11 -5
  124. package/dist/types/search/types.d.ts +14 -1
  125. package/dist/types/signing.d.ts +0 -157
  126. package/dist/types/thread.d.ts +118 -62
  127. package/dist/types/thread_manager.d.ts +124 -35
  128. package/dist/types/token_manager.d.ts +5 -8
  129. package/dist/types/types.d.ts +138 -562
  130. package/dist/types/types.utility.d.ts +8 -0
  131. package/dist/types/upload-utils.d.ts +20 -0
  132. package/dist/types/uploadManager.d.ts +50 -2
  133. package/dist/types/utils/FixedSizeQueueCache.d.ts +2 -0
  134. package/dist/types/utils/WithSubscriptions.d.ts +1 -1
  135. package/dist/types/utils/objectPath.d.ts +49 -0
  136. package/dist/types/utils/time.d.ts +85 -0
  137. package/dist/types/utils.d.ts +63 -40
  138. package/package.json +22 -33
  139. package/src/ChannelManager.ts +561 -109
  140. package/src/CooldownTimer.ts +55 -45
  141. package/src/EventHandlerPipeline.ts +13 -23
  142. package/src/LiveLocationManager.ts +191 -37
  143. package/src/api-client.ts +144 -53
  144. package/src/channel.ts +1573 -1050
  145. package/src/channel_state.ts +239 -129
  146. package/src/client.ts +843 -892
  147. package/src/client_state.ts +2 -2
  148. package/src/configuration/ConfigController.ts +298 -0
  149. package/src/configuration/InstanceConfigurationRegistry.ts +430 -0
  150. package/src/configuration/index.ts +7 -0
  151. package/src/configuration/keys.ts +86 -0
  152. package/src/configuration/shape.ts +776 -0
  153. package/src/configuration/types.ts +218 -60
  154. package/src/configuration/utils/applyInstanceConfiguration.ts +184 -0
  155. package/src/configuration/utils/copyConfigPatch.ts +61 -0
  156. package/src/configuration/utils/declarativeSlices.ts +81 -0
  157. package/src/configuration/utils/deepFreezeConfig.ts +33 -0
  158. package/src/configuration/utils/index.ts +5 -0
  159. package/src/configuration/utils/serverAuthority.ts +146 -0
  160. package/src/connection/ConnectionIdManager.ts +153 -0
  161. package/src/connection/ConnectionRecoveryManager.ts +371 -0
  162. package/src/connection/index.ts +4 -0
  163. package/src/connection/networkConnection/NetworkConnectionObserver.ts +281 -0
  164. package/src/connection/networkConnection/index.ts +3 -0
  165. package/src/connection/networkConnection/reporters.ts +85 -0
  166. package/src/connection/networkConnection/types.ts +60 -0
  167. package/src/{connection.ts → connection/wsConnection/StableWSConnection.ts} +242 -151
  168. package/src/connection/wsConnection/WSConnection.ts +345 -0
  169. package/src/connection/wsConnection/WSConnectionFallback.ts +259 -0
  170. package/src/connection/wsConnection/config.ts +108 -0
  171. package/src/connection/wsConnection/index.ts +4 -0
  172. package/src/connection/wsConnection/types.ts +101 -0
  173. package/src/constants.ts +5 -3
  174. package/src/entityStore/EntityStore.ts +350 -10
  175. package/src/entityStore/StoreBackedItemIndex.ts +66 -37
  176. package/src/entityStore/index.ts +0 -1
  177. package/src/errors.ts +40 -7
  178. package/src/formatMessageMemo.ts +23 -0
  179. package/src/gen/chat/ChannelApi.ts +230 -44
  180. package/src/gen/chat/ChatApi.ts +1047 -1745
  181. package/src/gen/models/index.ts +2378 -3721
  182. package/src/gen/models/timestamp-guard.ts +27 -0
  183. package/src/gen/moderation/ModerationApi.ts +218 -388
  184. package/src/gen-imports.ts +1 -0
  185. package/src/index.ts +82 -6
  186. package/src/languageNames.ts +103 -0
  187. package/src/logger.ts +1 -1
  188. package/src/messageComposer/CustomDataManager.ts +10 -1
  189. package/src/messageComposer/LocationComposer.ts +68 -20
  190. package/src/messageComposer/attachmentIdentity.ts +39 -0
  191. package/src/messageComposer/attachmentManager.ts +191 -68
  192. package/src/messageComposer/attachmentUtils.ts +58 -0
  193. package/src/messageComposer/configuration/commands.configuration.ts +1 -26
  194. package/src/messageComposer/configuration/configuration.ts +22 -3
  195. package/src/messageComposer/configuration/index.ts +0 -1
  196. package/src/messageComposer/configuration/types.ts +58 -1
  197. package/src/messageComposer/index.ts +1 -0
  198. package/src/messageComposer/linkPreviewsManager.ts +16 -10
  199. package/src/messageComposer/messageComposer.ts +487 -98
  200. package/src/messageComposer/middleware/attachmentManager/postUpload/AttachmentPostUploadMiddlewareExecutor.ts +1 -1
  201. package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +58 -33
  202. package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +7 -2
  203. package/src/messageComposer/middleware/attachmentManager/preUpload/blockedUploadNotification.ts +3 -2
  204. package/src/messageComposer/middleware/messageComposer/attachments.ts +98 -1
  205. package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +20 -10
  206. package/src/messageComposer/middleware/messageComposer/sharedLocation.ts +7 -2
  207. package/src/messageComposer/middleware/messageComposer/types.ts +2 -7
  208. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +11 -6
  209. package/src/messageComposer/middleware/pollComposer/index.ts +1 -0
  210. package/src/messageComposer/middleware/pollComposer/state.ts +43 -11
  211. package/src/messageComposer/middleware/pollComposer/types.ts +9 -2
  212. package/src/messageComposer/middleware/pollComposer/validation.ts +76 -0
  213. package/src/messageComposer/middleware/textComposer/commandUtils.ts +3 -2
  214. package/src/messageComposer/middleware/textComposer/commands.ts +1 -2
  215. package/src/messageComposer/middleware/textComposer/mentions.ts +91 -39
  216. package/src/messageComposer/pollComposer.ts +11 -3
  217. package/src/messageComposer/textComposer.ts +36 -4
  218. package/src/messageComposer/types.ts +19 -14
  219. package/src/messageDelivery/MessageDeliveryReporter.ts +154 -53
  220. package/src/messageDelivery/MessageReceiptsTracker.ts +136 -64
  221. package/src/messageOperations/FailedSendCache.ts +90 -0
  222. package/src/messageOperations/MessageOperationStatePolicy.ts +269 -27
  223. package/src/messageOperations/MessageOperations.ts +340 -136
  224. package/src/{entityStore → messageOperations}/applyReactionLocally.ts +10 -3
  225. package/src/messageOperations/createMessageOperations.ts +192 -0
  226. package/src/messageOperations/index.ts +7 -0
  227. package/src/messageOperations/reflectReactionEvent.ts +51 -0
  228. package/src/messageOperations/sendOrdering.ts +28 -0
  229. package/src/messageOperations/settlePendingAttachmentUploads.ts +110 -0
  230. package/src/messageOperations/types.ts +74 -0
  231. package/src/middleware.ts +11 -0
  232. package/src/moderation.ts +47 -24
  233. package/src/notifications/NotificationManager.ts +73 -3
  234. package/src/notifications/configuration.ts +10 -8
  235. package/src/notifications/types.ts +58 -42
  236. package/src/offline-support/offline_support_api.ts +380 -197
  237. package/src/offline-support/offline_sync_manager.ts +105 -32
  238. package/src/offline-support/queueableOperations.ts +270 -0
  239. package/src/offline-support/types.ts +85 -39
  240. package/src/pagination/FilterBuilder.ts +1 -22
  241. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +11 -7
  242. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +25 -7
  243. package/src/pagination/filterCompiler.ts +17 -0
  244. package/src/pagination/paginators/BasePaginator.ts +731 -81
  245. package/src/pagination/paginators/ChannelPaginator.ts +210 -102
  246. package/src/pagination/paginators/MessageIntervalPaginator.ts +703 -193
  247. package/src/pagination/paginators/MessagePaginator.ts +45 -36
  248. package/src/pagination/paginators/PinnedMessagePaginator.ts +74 -28
  249. package/src/pagination/paginators/ReminderPaginator.ts +15 -13
  250. package/src/pagination/paginators/ThreadPaginator.ts +181 -0
  251. package/src/pagination/paginators/UserGroupPaginator.ts +8 -1
  252. package/src/pagination/paginators/index.ts +1 -0
  253. package/src/pagination/utility.normalization.ts +37 -9
  254. package/src/poll.ts +189 -112
  255. package/src/poll_manager.ts +14 -8
  256. package/src/poll_optimistic_votes.ts +335 -0
  257. package/src/reminders/Reminder.ts +34 -16
  258. package/src/reminders/ReminderManager.ts +68 -41
  259. package/src/reminders/ReminderTimer.ts +7 -6
  260. package/src/search/BaseSearchSource.ts +133 -40
  261. package/src/search/ChannelMemberSearchSource.ts +27 -18
  262. package/src/search/ChannelSearchSource.ts +61 -7
  263. package/src/search/MessageSearchSource.ts +133 -28
  264. package/src/search/SearchController.ts +93 -16
  265. package/src/search/UserSearchSource.ts +27 -13
  266. package/src/search/types.ts +14 -1
  267. package/src/signing.ts +1 -315
  268. package/src/thread.ts +503 -511
  269. package/src/thread_manager.ts +339 -204
  270. package/src/token_manager.ts +12 -32
  271. package/src/types.ts +159 -780
  272. package/src/types.utility.ts +14 -0
  273. package/src/upload-utils.ts +53 -0
  274. package/src/uploadManager.ts +85 -7
  275. package/src/utils/FixedSizeQueueCache.ts +5 -0
  276. package/src/utils/WithSubscriptions.ts +1 -1
  277. package/src/utils/objectPath.ts +67 -0
  278. package/src/utils/time.ts +104 -0
  279. package/src/utils.ts +209 -157
  280. package/dist/types/base64.d.ts +0 -2
  281. package/dist/types/configuration/InstanceConfigurationService.d.ts +0 -26
  282. package/dist/types/connection.d.ts +0 -146
  283. package/dist/types/connection_fallback.d.ts +0 -42
  284. package/dist/types/gen/model-decoders/decoders.d.ts +0 -3
  285. package/dist/types/gen/model-decoders/event-decoder-mapping.d.ts +0 -6
  286. package/dist/types/insights.d.ts +0 -58
  287. package/dist/types/pagination/utility.queryChannel.d.ts +0 -26
  288. package/dist/types/permissions.d.ts +0 -55
  289. package/dist/types/store.d.ts +0 -125
  290. package/src/base64.ts +0 -78
  291. package/src/configuration/InstanceConfigurationService.ts +0 -73
  292. package/src/connection_fallback.ts +0 -215
  293. package/src/gen/model-decoders/decoders.ts +0 -2680
  294. package/src/gen/model-decoders/event-decoder-mapping.ts +0 -198
  295. package/src/insights.ts +0 -83
  296. package/src/pagination/utility.queryChannel.ts +0 -84
  297. package/src/permissions.ts +0 -102
  298. package/src/store.ts +0 -304
@@ -0,0 +1,90 @@
1
+ import { localMessageToNewMessagePayload } from '../utils';
2
+ import type { LocalMessage, MessageRequest } from '../types';
3
+ import type { MessageOperationsConfig } from './MessageOperations';
4
+ import type { OperationParams } from './types';
5
+
6
+ type FailedSendCacheEntry = {
7
+ message: MessageRequest;
8
+ options?: OperationParams<'send'>['options'];
9
+ cachedAt: number;
10
+ };
11
+
12
+ /**
13
+ * The payloads of sends that failed, kept so a retry sends exactly what failed. An entry expires after
14
+ * `failedSendCacheTtlMs`, and past `failedSendCacheMaxSize` the oldest one is dropped. Both limits are
15
+ * read from the owner's current configuration on every call, so a config change applies at once.
16
+ */
17
+ export class FailedSendCache {
18
+ private readonly entries = new Map<string, FailedSendCacheEntry>();
19
+
20
+ constructor(private readonly getConfig: () => Readonly<MessageOperationsConfig>) {}
21
+
22
+ add({
23
+ message,
24
+ messageId,
25
+ options,
26
+ }: {
27
+ messageId: string;
28
+ message: MessageRequest;
29
+ options?: OperationParams<'send'>['options'];
30
+ }) {
31
+ this.pruneExpired();
32
+
33
+ if (
34
+ !this.entries.has(messageId) &&
35
+ this.entries.size >= this.getConfig().failedSendCacheMaxSize
36
+ ) {
37
+ const oldestMessageId = this.entries.keys().next().value;
38
+ if (oldestMessageId) {
39
+ this.clear(oldestMessageId);
40
+ }
41
+ }
42
+
43
+ this.entries.set(messageId, { cachedAt: Date.now(), message, options });
44
+ }
45
+
46
+ get(messageId: string) {
47
+ const cached = this.entries.get(messageId);
48
+ if (!cached) return;
49
+
50
+ if (Date.now() - cached.cachedAt > this.getConfig().failedSendCacheTtlMs) {
51
+ this.clear(messageId);
52
+ return;
53
+ }
54
+
55
+ return cached;
56
+ }
57
+
58
+ clear(messageId: string) {
59
+ this.entries.delete(messageId);
60
+ }
61
+
62
+ /**
63
+ * Folds an edit into the payload cached for this message's failed send, so a retry resends what the
64
+ * message contains now rather than what it contained when the send failed.
65
+ *
66
+ * This exists so a retry while offline for example is also persisted, rather than just disappearing.
67
+ */
68
+ rewriteWithEdit(localMessage: LocalMessage) {
69
+ const cached = this.get(localMessage.id);
70
+ if (!cached) return;
71
+
72
+ this.entries.set(localMessage.id, {
73
+ ...cached,
74
+ message: {
75
+ ...cached.message,
76
+ ...localMessageToNewMessagePayload(localMessage),
77
+ },
78
+ });
79
+ }
80
+
81
+ private pruneExpired() {
82
+ const now = Date.now();
83
+
84
+ for (const [messageId, entry] of this.entries) {
85
+ if (now - entry.cachedAt > this.getConfig().failedSendCacheTtlMs) {
86
+ this.clear(messageId);
87
+ }
88
+ }
89
+ }
90
+ }
@@ -1,19 +1,80 @@
1
- import type { LocalMessage, MessageResponse, StreamAPIError } from '../types';
1
+ import type { DeleteMessageOptions, LocalMessage, MessageResponse } from '../types';
2
+ import { isAlreadyExistsError, parseError } from '../errors';
2
3
  import { formatMessage } from '../utils';
4
+ import { nowNs } from '../utils/time';
5
+ import type { QueueableType } from '../offline-support';
6
+ import type { MessageOperationSpec, OperationKind, OperationParams } from './types';
3
7
 
4
8
  export type MessageOperationStatePolicyContext = {
5
9
  ingest: (m: LocalMessage) => void;
6
10
  get: (id: string) => LocalMessage | undefined;
11
+ remove: (id: string) => void;
12
+ persist: (m: LocalMessage) => void;
13
+ purge: (id: string) => void;
14
+ isQueued: (messageId: string, types: readonly QueueableType[]) => Promise<boolean>;
7
15
  };
8
16
 
9
- const parseError = (error: unknown): StreamAPIError => {
10
- const stringError = JSON.stringify(error);
11
- return (stringError ? JSON.parse(stringError) : {}) as StreamAPIError;
17
+ /**
18
+ * What {@link MessageOperationStatePolicy.optimistic} wrote, handed back to
19
+ * {@link MessageOperationStatePolicy.failure} so it can decide whether to revert and to what.
20
+ */
21
+ export type OptimisticOutcome = {
22
+ /**
23
+ * The exact object the optimistic step wrote. Used as a concurrency guard rather than a value:
24
+ * `EntityStore.upsert` REPLACES the canonical copy, so `get(id) === applied` is a sound "nothing
25
+ * else has written since" check, and anything else means a fresher truth (a WS event, another
26
+ * operation) landed and must not be clobbered by a revert.
27
+ */
28
+ applied?: LocalMessage;
29
+ /** The copy that was there beforehand, i.e. what a revert restores. */
30
+ previous?: LocalMessage;
12
31
  };
13
32
 
14
- const isAlreadyExistsError = (error: unknown, parsed: StreamAPIError) =>
15
- parsed.code === 4 && error instanceof Error && error.message.includes('already exists');
33
+ const isHardDelete = (options: unknown) =>
34
+ !!(options as DeleteMessageOptions | undefined)?.hard;
16
35
 
36
+ /**
37
+ * Closes each phase's branches on the kind. A new `OperationKind` fails to compile at every call until
38
+ * that phase decides what the kind does, instead of quietly getting another kind's rules.
39
+ */
40
+ const unhandledKind = (kind: never): never => {
41
+ throw new Error(`Unhandled message operation kind: ${String(kind)}`);
42
+ };
43
+
44
+ /**
45
+ * The queued tasks that mean a failed request is still pending, so its optimistic state stays.
46
+ *
47
+ * A send has none. One that never reached the server has to settle as `failed` even when its task is
48
+ * queued, because the retry affordance is the only way the user can get that message out.
49
+ */
50
+ const PENDING_WHEN_QUEUED: Record<OperationKind, readonly QueueableType[]> = {
51
+ delete: ['delete-message'],
52
+ retry: [],
53
+ send: [],
54
+ // An edit of a message the server has never seen is folded into that message's queued send
55
+ // (`AbstractOfflineDB.handleUpdateMessagePendingTask`), so it leaves no `update-message` row of
56
+ // its own.
57
+ update: ['update-message', 'send-message'],
58
+ };
59
+
60
+ /**
61
+ * The local-state half of every message operation: what to show before the request resolves, what to
62
+ * do with the server's answer, and what to do when it fails.
63
+ *
64
+ * Per-operation rather than uniform, because the three kinds want genuinely different things:
65
+ *
66
+ * - **send / retry** — optimistically `sending`, `failed` on failure, and a pessimistic write-ahead to
67
+ * the offline DB so a process death between compose and server-ack leaves a message that hydrates as
68
+ * failed-and-retryable instead of vanishing.
69
+ * - **update** — optimistically applied and persisted, and **never reverted**: rolling back would
70
+ * destroy text the user typed. A definitive rejection surfaces as a failed/error state on the message
71
+ * while keeping the edit; a queued (offline) failure surfaces as nothing at all, because the edit is
72
+ * pending, not failed.
73
+ * - **delete** — optimistically marked `deleted` (or removed outright, for a hard delete), and
74
+ * **reverted** on a definitive rejection: unlike an edit there is no user input to lose, and leaving a
75
+ * "Message deleted" placeholder on a message that still exists server-side is a lie that only
76
+ * self-corrects on the next query.
77
+ */
17
78
  export class MessageOperationStatePolicy {
18
79
  private ctx: MessageOperationStatePolicyContext;
19
80
 
@@ -21,57 +82,238 @@ export class MessageOperationStatePolicy {
21
82
  this.ctx = ctx;
22
83
  }
23
84
 
24
- optimistic(localMessage: LocalMessage) {
25
- this.ctx.ingest({
26
- ...localMessage,
27
- error: undefined,
28
- status:
29
- !localMessage.status || localMessage.status === 'failed'
30
- ? 'sending'
31
- : localMessage.status,
32
- });
85
+ optimistic<K extends OperationKind>(
86
+ kind: K,
87
+ params: OperationParams<K>,
88
+ ): OptimisticOutcome {
89
+ const { localMessage } = params;
90
+ const previous = this.ctx.get(localMessage.id);
91
+
92
+ if (kind === 'delete') {
93
+ const deleteForMe = (params.options as DeleteMessageOptions | undefined)
94
+ ?.delete_for_me;
95
+
96
+ if (isHardDelete(params.options)) {
97
+ this.ctx.remove(localMessage.id);
98
+ this.ctx.purge(localMessage.id);
99
+ return { previous };
100
+ }
101
+
102
+ // Nothing holds this message, so there is nothing to optimistically hide — and ingesting would
103
+ // insert a phantom "Message deleted" row for something that was never on screen. Nothing is
104
+ // written to the offline DB either: it mirrors local state, so it must not be told about state
105
+ // that does not exist. The server response still reconciles normally below.
106
+ if (!previous) return {};
107
+
108
+ const applied: LocalMessage = {
109
+ ...localMessage,
110
+ deleted_at: nowNs(),
111
+ type: 'deleted',
112
+ ...(deleteForMe ? { deleted_for_me: true } : {}),
113
+ };
114
+ this.ctx.ingest(applied);
115
+ this.ctx.persist(applied);
116
+ return { applied, previous };
117
+ }
118
+
119
+ if (kind === 'update') {
120
+ // An edit keeps the message's status. A message the server already has must not go back to
121
+ // `sending`, and one that never left the device has to stay `failed`.
122
+ const isFailed = localMessage.status === 'failed';
123
+ const editedAt = nowNs();
124
+ const applied: LocalMessage = {
125
+ ...localMessage,
126
+ error: isFailed ? localMessage.error : undefined,
127
+ updated_at: editedAt,
128
+ // `message_text_updated_at` is what drives the "edited" indicator, so it has to appear
129
+ // immediately — but only for a message the server has actually seen. A failed message never
130
+ // received a server-confirmed text update and must not appear to have had one.
131
+ ...(isFailed ? {} : { message_text_updated_at: editedAt }),
132
+ };
133
+ this.ctx.ingest(applied);
134
+ this.ctx.persist(applied);
135
+ return { applied, previous };
136
+ }
137
+
138
+ if (kind === 'send' || kind === 'retry') {
139
+ const applied: LocalMessage = {
140
+ ...localMessage,
141
+ error: undefined,
142
+ status:
143
+ !localMessage.status || localMessage.status === 'failed'
144
+ ? 'sending'
145
+ : localMessage.status,
146
+ };
147
+ this.ctx.ingest(applied);
148
+ // Write-ahead, pessimistically FAILED. If the app dies between here and the server's ack the
149
+ // message comes back as failed and retryable rather than disappearing; a success overwrites
150
+ // it below. The retry payload does not need persisting alongside it —
151
+ // `MessageOperations.retry` reconstructs it from the message when `failedSendCache` is cold.
152
+ this.ctx.persist({ ...applied, status: 'failed' });
153
+ return { applied, previous };
154
+ }
155
+
156
+ return unhandledKind(kind);
33
157
  }
34
158
 
35
- success({
159
+ success<K extends OperationKind>({
160
+ kind,
36
161
  messageFromResponse,
37
162
  messageId,
163
+ optimistic,
164
+ options,
38
165
  }: {
39
- messageFromResponse: MessageResponse;
166
+ kind: K;
167
+ messageFromResponse: MessageResponse | undefined;
40
168
  messageId: string;
169
+ optimistic?: OptimisticOutcome;
170
+ options?: MessageOperationSpec[K]['options'];
41
171
  }) {
172
+ // Guard before anything else. `formatMessage(undefined)` does not throw — it yields
173
+ // `{ status: 'received', created_at: <now>, updated_at: <now> }`, an id-less message whose
174
+ // `updated_at` beats the freshness check below, so without this an empty response ingested junk.
175
+ if (!messageFromResponse) return;
176
+
42
177
  const formatted = formatMessage({ ...messageFromResponse, status: 'received' });
43
- const existing = this.ctx.get(messageId);
44
178
 
45
- const serverNewer =
46
- !existing || formatted.updated_at.getTime() > existing.updated_at.getTime();
47
- const serverSameOrNewer =
48
- !existing || formatted.updated_at.getTime() >= existing.updated_at.getTime();
49
- const existingIsOurOptimisticSend = existing?.status === 'sending';
179
+ if (kind === 'delete') {
180
+ if (isHardDelete(options)) {
181
+ this.ctx.remove(messageId);
182
+ this.ctx.purge(messageId);
183
+ return;
184
+ }
185
+ // Mirrors the `!previous` guard in `optimistic`: a message local state does not hold must not be
186
+ // re-inserted as a "Message deleted" row it never displayed. Read live rather than from the
187
+ // optimistic snapshot, so a copy that arrived while the request was open is still marked.
188
+ if (!this.ctx.get(messageId)) return;
189
+
190
+ this.ctx.ingest(formatted);
191
+ this.ctx.persist(formatted);
192
+ return;
193
+ }
194
+
195
+ if (kind === 'update' || kind === 'send' || kind === 'retry') {
196
+ const existing = this.ctx.get(messageId);
197
+
198
+ const nothingWroteSinceOptimistic =
199
+ !!optimistic?.applied && existing === optimistic.applied;
200
+
201
+ // Reached only when something else did write since the optimistic step. For an edit both
202
+ // copies are then server derived, so comparing their timestamps compares one clock against
203
+ // itself. For a send the copy that landed is a `message.new` WS event, which is server derived
204
+ // too.
205
+ const serverNewer = !existing || formatted.updated_at > existing.updated_at;
206
+ const serverSameOrNewer = !existing || formatted.updated_at >= existing.updated_at;
207
+ const existingIsOurOptimisticSend = existing?.status === 'sending';
208
+
209
+ const applyServerCopy =
210
+ nothingWroteSinceOptimistic ||
211
+ serverNewer ||
212
+ (existingIsOurOptimisticSend && serverSameOrNewer);
213
+
214
+ if (!applyServerCopy) return;
50
215
 
51
- if (serverNewer || (existingIsOurOptimisticSend && serverSameOrNewer)) {
52
216
  this.ctx.ingest(formatted);
217
+ // Persist only what was actually applied, so the row can never disagree with memory. For
218
+ // send/retry this is also what supersedes the pessimistic `failed` write-ahead — and when the
219
+ // copy is declined it is because a fresher one already landed, whose own path wrote the row.
220
+ this.ctx.persist(formatted);
221
+ return;
53
222
  }
223
+
224
+ return unhandledKind(kind);
54
225
  }
55
226
 
56
- failure({
227
+ async failure<K extends OperationKind>({
57
228
  error,
229
+ kind,
58
230
  localMessage,
59
231
  messageId,
232
+ optimistic,
233
+ options,
60
234
  }: {
61
235
  error: unknown;
236
+ kind: K;
62
237
  localMessage: LocalMessage;
63
238
  messageId: string;
239
+ optimistic?: OptimisticOutcome;
240
+ options?: MessageOperationSpec[K]['options'];
64
241
  }) {
65
242
  const parsed = parseError(error);
66
243
 
67
244
  if (isAlreadyExistsError(error, parsed)) {
68
245
  const existing = this.ctx.get(messageId);
69
246
  if (existing?.status === 'sending') {
70
- this.ctx.ingest({ ...localMessage, status: 'received' });
247
+ const received: LocalMessage = { ...localMessage, status: 'received' };
248
+ this.ctx.ingest(received);
249
+ this.ctx.persist(received);
71
250
  }
72
251
  return;
73
252
  }
74
253
 
75
- this.ctx.ingest({ ...localMessage, status: 'failed', error: parsed });
254
+ // A request waiting in the offline queue hasn't failed, it just hasn't been sent yet, so the
255
+ // optimistic state stays exactly as it is.
256
+ const pendingTaskTypes = PENDING_WHEN_QUEUED[kind];
257
+ const queued =
258
+ pendingTaskTypes.length > 0 &&
259
+ (await this.ctx.isQueued(messageId, pendingTaskTypes));
260
+
261
+ if (kind === 'delete') {
262
+ if (!queued) this.revertDelete({ messageId, optimistic, options });
263
+ return;
264
+ }
265
+
266
+ if (kind === 'update') {
267
+ if (queued) return;
268
+ // The edit itself is kept — only the failure is recorded on top of it. NOTE: this lights up the
269
+ // retry affordance, which re-SENDS rather than re-edits; that predates this change and is
270
+ // deliberately left alone.
271
+ const failed: LocalMessage = {
272
+ ...(this.ctx.get(messageId) ?? localMessage),
273
+ error: parsed,
274
+ status: 'failed',
275
+ };
276
+ this.ctx.ingest(failed);
277
+ this.ctx.persist(failed);
278
+ return;
279
+ }
280
+
281
+ if (kind === 'send' || kind === 'retry') {
282
+ const failed: LocalMessage = { ...localMessage, error: parsed, status: 'failed' };
283
+ this.ctx.ingest(failed);
284
+ this.ctx.persist(failed);
285
+ return;
286
+ }
287
+
288
+ return unhandledKind(kind);
289
+ }
290
+
291
+ private revertDelete<K extends OperationKind>({
292
+ messageId,
293
+ optimistic,
294
+ options,
295
+ }: {
296
+ messageId: string;
297
+ optimistic?: OptimisticOutcome;
298
+ options?: MessageOperationSpec[K]['options'];
299
+ }) {
300
+ const previous = optimistic?.previous;
301
+ // Nothing was held locally, so the optimistic step changed nothing to put back.
302
+ if (!previous) return;
303
+
304
+ if (isHardDelete(options)) {
305
+ // A hard delete took the message out of local state, so there is no current copy to compare
306
+ // against — the snapshot is unambiguously what belongs there.
307
+ this.ctx.ingest(previous);
308
+ this.ctx.persist(previous);
309
+ return;
310
+ }
311
+
312
+ if (optimistic?.applied && this.ctx.get(messageId) !== optimistic.applied) return;
313
+
314
+ this.ctx.ingest(previous);
315
+ // Undoes the row the optimistic step soft-deleted: the upsert rewrites `type` and `deletedAt` from
316
+ // the restored message.
317
+ this.ctx.persist(previous);
76
318
  }
77
319
  }