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

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 (269) hide show
  1. package/dist/cjs/index.browser.js +2196 -3902
  2. package/dist/cjs/index.browser.js.map +3 -3
  3. package/dist/cjs/index.node.js +2197 -3902
  4. package/dist/cjs/index.node.js.map +3 -3
  5. package/dist/esm/index.mjs +2199 -3905
  6. package/dist/esm/index.mjs.map +4 -4
  7. package/dist/types/ChannelManager.d.ts +120 -233
  8. package/dist/types/CooldownTimer.d.ts +8 -23
  9. package/dist/types/EventHandlerPipeline.d.ts +17 -37
  10. package/dist/types/LiveLocationManager.d.ts +22 -50
  11. package/dist/types/api-client.d.ts +9 -14
  12. package/dist/types/channel.d.ts +253 -448
  13. package/dist/types/channel_state.d.ts +48 -95
  14. package/dist/types/client.d.ts +245 -370
  15. package/dist/types/client_state.d.ts +1 -3
  16. package/dist/types/configuration/ConfigController.d.ts +30 -124
  17. package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +31 -123
  18. package/dist/types/configuration/keys.d.ts +5 -19
  19. package/dist/types/configuration/shape.d.ts +12 -29
  20. package/dist/types/configuration/types.d.ts +59 -87
  21. package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +13 -35
  22. package/dist/types/configuration/utils/copyConfigPatch.d.ts +8 -0
  23. package/dist/types/configuration/utils/declarativeSlices.d.ts +5 -16
  24. package/dist/types/configuration/utils/deepFreezeConfig.d.ts +3 -17
  25. package/dist/types/configuration/utils/serverAuthority.d.ts +9 -29
  26. package/dist/types/connection/ConnectionIdManager.d.ts +18 -40
  27. package/dist/types/connection/ConnectionRecoveryManager.d.ts +29 -120
  28. package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +32 -103
  29. package/dist/types/connection/networkConnection/reporters.d.ts +9 -32
  30. package/dist/types/connection/networkConnection/types.d.ts +12 -27
  31. package/dist/types/connection/wsConnection/StableWSConnection.d.ts +37 -116
  32. package/dist/types/connection/wsConnection/WSConnection.d.ts +41 -104
  33. package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +8 -16
  34. package/dist/types/connection/wsConnection/config.d.ts +8 -28
  35. package/dist/types/connection/wsConnection/types.d.ts +17 -70
  36. package/dist/types/entityStore/EntityStore.d.ts +153 -113
  37. package/dist/types/entityStore/StoreBackedItemIndex.d.ts +13 -46
  38. package/dist/types/errors.d.ts +7 -19
  39. package/dist/types/gen/chat/ChannelApi.d.ts +2 -1
  40. package/dist/types/gen/chat/ChatApi.d.ts +28 -14
  41. package/dist/types/gen/models/index.d.ts +769 -86
  42. package/dist/types/gen/moderation/ModerationApi.d.ts +4 -4
  43. package/dist/types/index.d.ts +2 -4
  44. package/dist/types/languageNames.d.ts +9 -24
  45. package/dist/types/logger.d.ts +1 -3
  46. package/dist/types/messageComposer/LocationComposer.d.ts +1 -1
  47. package/dist/types/messageComposer/attachmentIdentity.d.ts +1 -6
  48. package/dist/types/messageComposer/attachmentManager.d.ts +10 -32
  49. package/dist/types/messageComposer/attachmentUtils.d.ts +3 -14
  50. package/dist/types/messageComposer/configuration/configuration.d.ts +2 -5
  51. package/dist/types/messageComposer/configuration/types.d.ts +29 -56
  52. package/dist/types/messageComposer/linkPreviewsManager.d.ts +6 -9
  53. package/dist/types/messageComposer/messageComposer.d.ts +30 -164
  54. package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +4 -14
  55. package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +2 -9
  56. package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +2 -4
  57. package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +7 -19
  58. package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +9 -0
  59. package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +11 -18
  60. package/dist/types/messageComposer/middleware/textComposer/textMiddlewareUtils.d.ts +9 -3
  61. package/dist/types/messageComposer/middleware/textComposer/types.d.ts +1 -6
  62. package/dist/types/messageComposer/pollComposer.d.ts +8 -4
  63. package/dist/types/messageComposer/textComposer.d.ts +3 -9
  64. package/dist/types/messageComposer/types.d.ts +5 -8
  65. package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +25 -79
  66. package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +15 -82
  67. package/dist/types/messageOperations/FailedSendCache.d.ts +4 -9
  68. package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +10 -20
  69. package/dist/types/messageOperations/MessageOperations.d.ts +20 -40
  70. package/dist/types/messageOperations/applyReactionLocally.d.ts +5 -22
  71. package/dist/types/messageOperations/createMessageOperations.d.ts +3 -5
  72. package/dist/types/messageOperations/reflectReactionEvent.d.ts +5 -13
  73. package/dist/types/messageOperations/sendOrdering.d.ts +4 -7
  74. package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +7 -15
  75. package/dist/types/messageOperations/types.d.ts +15 -30
  76. package/dist/types/middleware.d.ts +7 -5
  77. package/dist/types/moderation.d.ts +21 -14
  78. package/dist/types/notifications/NotificationManager.d.ts +8 -31
  79. package/dist/types/notifications/types.d.ts +19 -59
  80. package/dist/types/offline-support/offline_support_api.d.ts +145 -539
  81. package/dist/types/offline-support/offline_sync_manager.d.ts +18 -42
  82. package/dist/types/offline-support/queueableOperations.d.ts +24 -52
  83. package/dist/types/offline-support/types.d.ts +24 -187
  84. package/dist/types/pagination/ItemIndex.d.ts +4 -12
  85. package/dist/types/pagination/cursorDerivation/aroundPaginationFlags.d.ts +13 -0
  86. package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +2 -4
  87. package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +2 -3
  88. package/dist/types/pagination/paginators/BasePaginator.d.ts +235 -622
  89. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +67 -125
  90. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +133 -292
  91. package/dist/types/pagination/paginators/MessagePaginator.d.ts +69 -118
  92. package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +7 -26
  93. package/dist/types/pagination/paginators/ReminderPaginator.d.ts +2 -2
  94. package/dist/types/pagination/paginators/ThreadPaginator.d.ts +15 -23
  95. package/dist/types/pagination/paginators/UserGroupPaginator.d.ts +2 -6
  96. package/dist/types/pagination/sortCompiler.d.ts +11 -22
  97. package/dist/types/pagination/utility.normalization.d.ts +5 -23
  98. package/dist/types/pagination/utility.search.d.ts +3 -8
  99. package/dist/types/poll.d.ts +14 -14
  100. package/dist/types/poll_manager.d.ts +11 -2
  101. package/dist/types/poll_optimistic_votes.d.ts +10 -14
  102. package/dist/types/reminders/Reminder.d.ts +4 -4
  103. package/dist/types/reminders/ReminderManager.d.ts +7 -20
  104. package/dist/types/search/BaseSearchSource.d.ts +7 -12
  105. package/dist/types/search/ChannelSearchSource.d.ts +7 -7
  106. package/dist/types/search/MessageSearchSource.d.ts +7 -9
  107. package/dist/types/search/SearchController.d.ts +17 -22
  108. package/dist/types/search/types.d.ts +6 -10
  109. package/dist/types/signing.d.ts +12 -3
  110. package/dist/types/thread.d.ts +23 -71
  111. package/dist/types/thread_manager.d.ts +45 -70
  112. package/dist/types/token_manager.d.ts +8 -13
  113. package/dist/types/types.d.ts +64 -125
  114. package/dist/types/types.utility.d.ts +3 -3
  115. package/dist/types/upload-utils.d.ts +5 -10
  116. package/dist/types/uploadManager.d.ts +17 -45
  117. package/dist/types/utils/FixedSizeQueueCache.d.ts +6 -11
  118. package/dist/types/utils/WithSubscriptions.d.ts +5 -15
  119. package/dist/types/utils/concurrency.d.ts +11 -19
  120. package/dist/types/utils/mergeWith/mergeWith.d.ts +8 -11
  121. package/dist/types/utils/mergeWith/mergeWithCore.d.ts +5 -13
  122. package/dist/types/utils/mergeWith/mergeWithDiff.d.ts +22 -0
  123. package/dist/types/utils/objectPath.d.ts +6 -41
  124. package/dist/types/utils/retryable.d.ts +8 -12
  125. package/dist/types/utils/throttling/throttle.d.ts +8 -23
  126. package/dist/types/utils/time.d.ts +24 -64
  127. package/dist/types/utils.d.ts +40 -86
  128. package/package.json +7 -2
  129. package/src/ChannelManager.ts +159 -300
  130. package/src/CooldownTimer.ts +11 -29
  131. package/src/EventHandlerPipeline.ts +21 -44
  132. package/src/LiveLocationManager.ts +35 -74
  133. package/src/api-client.ts +43 -61
  134. package/src/campaign.ts +1 -1
  135. package/src/channel.ts +396 -749
  136. package/src/channel_batch_updater.ts +1 -1
  137. package/src/channel_state.ts +50 -105
  138. package/src/client.ts +360 -588
  139. package/src/client_state.ts +1 -6
  140. package/src/configuration/ConfigController.ts +41 -157
  141. package/src/configuration/InstanceConfigurationRegistry.ts +42 -171
  142. package/src/configuration/index.ts +1 -1
  143. package/src/configuration/keys.ts +13 -32
  144. package/src/configuration/shape.ts +67 -70
  145. package/src/configuration/types.ts +60 -100
  146. package/src/configuration/utils/applyInstanceConfiguration.ts +21 -53
  147. package/src/configuration/utils/copyConfigPatch.ts +11 -32
  148. package/src/configuration/utils/declarativeSlices.ts +9 -39
  149. package/src/configuration/utils/deepFreezeConfig.ts +3 -17
  150. package/src/configuration/utils/index.ts +2 -4
  151. package/src/configuration/utils/serverAuthority.ts +20 -68
  152. package/src/connection/ConnectionIdManager.ts +20 -49
  153. package/src/connection/ConnectionRecoveryManager.ts +51 -178
  154. package/src/connection/networkConnection/NetworkConnectionObserver.ts +37 -114
  155. package/src/connection/networkConnection/reporters.ts +9 -36
  156. package/src/connection/networkConnection/types.ts +12 -27
  157. package/src/connection/wsConnection/StableWSConnection.ts +73 -193
  158. package/src/connection/wsConnection/WSConnection.ts +56 -131
  159. package/src/connection/wsConnection/WSConnectionFallback.ts +22 -31
  160. package/src/connection/wsConnection/config.ts +13 -48
  161. package/src/connection/wsConnection/types.ts +17 -70
  162. package/src/constants.ts +4 -4
  163. package/src/entityStore/EntityStore.ts +162 -167
  164. package/src/entityStore/StoreBackedItemIndex.ts +14 -47
  165. package/src/errors.ts +7 -19
  166. package/src/formatMessageMemo.ts +3 -9
  167. package/src/gen/chat/ChannelApi.ts +19 -0
  168. package/src/gen/chat/ChatApi.ts +87 -13
  169. package/src/gen/models/index.ts +793 -71
  170. package/src/gen/moderation/ModerationApi.ts +0 -4
  171. package/src/index.ts +10 -14
  172. package/src/languageNames.ts +9 -24
  173. package/src/logger.ts +1 -3
  174. package/src/messageComposer/LocationComposer.ts +7 -23
  175. package/src/messageComposer/MessageComposerEffectHandlers.ts +1 -2
  176. package/src/messageComposer/attachmentIdentity.ts +2 -13
  177. package/src/messageComposer/attachmentManager.ts +17 -63
  178. package/src/messageComposer/attachmentUtils.ts +3 -17
  179. package/src/messageComposer/configuration/configuration.ts +5 -8
  180. package/src/messageComposer/configuration/types.ts +29 -56
  181. package/src/messageComposer/fileUtils.ts +1 -1
  182. package/src/messageComposer/linkPreviewsManager.ts +8 -20
  183. package/src/messageComposer/messageComposer.ts +54 -222
  184. package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +4 -16
  185. package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +1 -2
  186. package/src/messageComposer/middleware/messageComposer/attachments.ts +14 -40
  187. package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +3 -4
  188. package/src/messageComposer/middleware/messageComposer/textComposer.ts +1 -1
  189. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +4 -11
  190. package/src/messageComposer/middleware/pollComposer/state.ts +2 -2
  191. package/src/messageComposer/middleware/pollComposer/types.ts +2 -4
  192. package/src/messageComposer/middleware/pollComposer/validation.ts +8 -26
  193. package/src/messageComposer/middleware/textComposer/TextComposerMiddlewareExecutor.ts +1 -6
  194. package/src/messageComposer/middleware/textComposer/commandUtils.ts +1 -2
  195. package/src/messageComposer/middleware/textComposer/commands.ts +11 -16
  196. package/src/messageComposer/middleware/textComposer/mentions.ts +32 -70
  197. package/src/messageComposer/middleware/textComposer/textMiddlewareUtils.ts +10 -4
  198. package/src/messageComposer/middleware/textComposer/types.ts +1 -6
  199. package/src/messageComposer/pollComposer.ts +11 -8
  200. package/src/messageComposer/textComposer.ts +9 -59
  201. package/src/messageComposer/types.ts +9 -12
  202. package/src/messageDelivery/MessageDeliveryReporter.ts +60 -113
  203. package/src/messageDelivery/MessageReceiptsTracker.ts +21 -105
  204. package/src/messageOperations/FailedSendCache.ts +4 -9
  205. package/src/messageOperations/MessageOperationStatePolicy.ts +40 -67
  206. package/src/messageOperations/MessageOperations.ts +33 -62
  207. package/src/messageOperations/applyReactionLocally.ts +9 -28
  208. package/src/messageOperations/createMessageOperations.ts +17 -33
  209. package/src/messageOperations/reflectReactionEvent.ts +5 -13
  210. package/src/messageOperations/sendOrdering.ts +4 -7
  211. package/src/messageOperations/settlePendingAttachmentUploads.ts +10 -21
  212. package/src/messageOperations/types.ts +15 -30
  213. package/src/middleware.ts +7 -10
  214. package/src/moderation.ts +25 -21
  215. package/src/notifications/NotificationManager.ts +11 -35
  216. package/src/notifications/types.ts +19 -59
  217. package/src/offline-support/offline_support_api.ts +178 -608
  218. package/src/offline-support/offline_sync_manager.ts +25 -69
  219. package/src/offline-support/queueableOperations.ts +31 -84
  220. package/src/offline-support/types.ts +25 -188
  221. package/src/pagination/ItemIndex.ts +4 -12
  222. package/src/pagination/cursorDerivation/aroundPaginationFlags.ts +29 -0
  223. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +13 -62
  224. package/src/pagination/cursorDerivation/idAroundPaginationFlags.ts +11 -39
  225. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +4 -6
  226. package/src/pagination/filterCompiler.ts +11 -25
  227. package/src/pagination/paginators/BasePaginator.ts +422 -976
  228. package/src/pagination/paginators/ChannelPaginator.ts +130 -190
  229. package/src/pagination/paginators/MessageIntervalPaginator.ts +226 -457
  230. package/src/pagination/paginators/MessagePaginator.ts +135 -175
  231. package/src/pagination/paginators/PinnedMessagePaginator.ts +13 -38
  232. package/src/pagination/paginators/ReminderPaginator.ts +12 -15
  233. package/src/pagination/paginators/ThreadPaginator.ts +16 -26
  234. package/src/pagination/paginators/UserGroupPaginator.ts +6 -17
  235. package/src/pagination/paginators/stateThrottling.ts +5 -10
  236. package/src/pagination/sortCompiler.ts +23 -50
  237. package/src/pagination/utility.normalization.ts +8 -30
  238. package/src/pagination/utility.search.ts +4 -11
  239. package/src/poll.ts +19 -19
  240. package/src/poll_manager.ts +16 -20
  241. package/src/poll_optimistic_votes.ts +17 -22
  242. package/src/reminders/Reminder.ts +5 -6
  243. package/src/reminders/ReminderManager.ts +9 -34
  244. package/src/reminders/ReminderTimer.ts +1 -2
  245. package/src/search/BaseSearchSource.ts +14 -29
  246. package/src/search/ChannelSearchSource.ts +8 -8
  247. package/src/search/MessageSearchSource.ts +19 -25
  248. package/src/search/SearchController.ts +18 -24
  249. package/src/search/types.ts +6 -10
  250. package/src/segment.ts +1 -1
  251. package/src/signing.ts +23 -3
  252. package/src/thread.ts +72 -173
  253. package/src/thread_manager.ts +59 -76
  254. package/src/token_manager.ts +11 -21
  255. package/src/types.ts +78 -126
  256. package/src/types.utility.ts +3 -3
  257. package/src/upload-utils.ts +5 -10
  258. package/src/uploadManager.ts +22 -54
  259. package/src/utils/FixedSizeQueueCache.ts +13 -21
  260. package/src/utils/WithSubscriptions.ts +5 -15
  261. package/src/utils/concurrency.ts +16 -55
  262. package/src/utils/mergeWith/mergeWith.ts +10 -13
  263. package/src/utils/mergeWith/mergeWithCore.ts +24 -81
  264. package/src/utils/mergeWith/mergeWithDiff.ts +15 -33
  265. package/src/utils/objectPath.ts +6 -41
  266. package/src/utils/retryable.ts +10 -14
  267. package/src/utils/throttling/throttle.ts +9 -25
  268. package/src/utils/time.ts +26 -66
  269. package/src/utils.ts +72 -128
@@ -18,24 +18,13 @@ export type UserProgress = {
18
18
  export type MessageReceiptsSnapshot = {
19
19
  revision: number;
20
20
  /**
21
- * Which users' read cursor sits *on* each message - not which messages have been read. A reader
22
- * appears once, at the message they stopped on.
23
- *
24
- * This is the compact form: one entry per user, not per message. "Who has read message X" is
25
- * every user at or past it, which {@link MessageReceiptsTracker.readersForMessage} answers, and
26
- * which a consumer rendering a range can accumulate from these buckets in one pass.
21
+ * Users whose read cursor sits on each message: one entry per user, not everyone who has read it.
22
+ * For "who has read X" use {@link MessageReceiptsTracker.readersForMessage}.
27
23
  */
28
24
  readersByMessageId: Record<MessageId, UserResponse[]>;
29
25
  /** As {@link readersByMessageId}, for delivery. */
30
26
  deliveredByMessageId: Record<MessageId, UserResponse[]>;
31
- /**
32
- * How far the furthest *other* member has got, or `null` when nobody has got anywhere.
33
- *
34
- * Delivery and read only move forward, so one ref answers every message: at or before it means
35
- * delivered/read, after it means not yet. A per-message map cannot express that - it marks only
36
- * the message each cursor happens to land on, leaving every earlier message looking less far
37
- * along than a later one, which is a state that cannot occur.
38
- */
27
+ /** Furthest delivered ref of any other member, or `null`. A message at or before it is delivered. */
39
28
  lastDeliveredRefByOthers: MsgRef | null;
40
29
  /** As {@link lastDeliveredRefByOthers}, for reads. */
41
30
  lastReadRefByOthers: MsgRef | null;
@@ -54,8 +43,6 @@ type ReadStoreUserState = {
54
43
  last_delivered_message_id?: string;
55
44
  };
56
45
 
57
- // ---------- ordering utilities ----------
58
-
59
46
  const MIN_REF: MsgRef = {
60
47
  timestamp: asTimestampNS(Number.NEGATIVE_INFINITY),
61
48
  msgId: '',
@@ -82,15 +69,7 @@ const findIndex = <T>(arr: T[], target: MsgRef, keyOf: (x: T) => MsgRef): number
82
69
  return lo;
83
70
  };
84
71
 
85
- /**
86
- * Finds the insertion index after the last equal item. E.g. when array `[a]` exists and `b` is
87
- * being inserted we want `[a, b]`, not `[b, a]`.
88
- *
89
- * @param arr - The sorted array to search.
90
- * @param target - The reference value to compare against.
91
- * @param keyOf - Accessor that maps an item to its comparable reference.
92
- * @returns The insertion index in `arr`.
93
- */
72
+ /** Insertion index after the last equal item, so ties keep arrival order. */
94
73
  const findUpperIndex = <T>(arr: T[], target: MsgRef, keyOf: (x: T) => MsgRef): number => {
95
74
  let lo = 0,
96
75
  hi = arr.length;
@@ -114,7 +93,7 @@ const removeByOldKey = (
114
93
  oldKey: MsgRef,
115
94
  keyOf: (x: UserProgress) => MsgRef,
116
95
  ) => {
117
- // Find the plateau for oldKey, scan to match by user id
96
+ // Find the plateau for oldKey, scan to match by user ID
118
97
  let i = findIndex(arr, oldKey, keyOf);
119
98
  while (i < arr.length && compareRefsAsc(keyOf(arr[i]), oldKey) === 0) {
120
99
  if (arr[i].user.id === item.user.id) {
@@ -131,62 +110,13 @@ export type OwnMessageReceiptsTrackerOptions = {
131
110
  };
132
111
 
133
112
  /**
134
- * MessageReceiptsTracker
135
- * --------------------------------
136
- * Tracks **other participants’** delivery/read progress toward **own (outgoing) messages**
137
- * within a **single timeline** (one channel/thread).
138
- *
139
- * How it works
140
- * ------------
141
- * - Each user has a compact progress record:
142
- * - `lastReadRef`: latest message they have **read**
143
- * - `lastDeliveredRef`: latest message they have **received** (always `>= lastReadRef`)
144
- * - Internally keeps two arrays sorted **ascending by timestamp**:
145
- * - `readSorted` (by `lastReadRef`)
146
- * - `deliveredSorted` (by `lastDeliveredRef`)
147
- * - Queries like “who read message M?” become a **binary search + suffix slice**.
113
+ * Tracks other participants' delivery and read progress toward own messages in one timeline
114
+ * (channel or thread). Per user it keeps `lastReadRef` and `lastDeliveredRef` (always
115
+ * `>= lastReadRef`) in two arrays sorted by timestamp, so "who read message M?" is a binary search
116
+ * plus a suffix slice.
148
117
  *
149
- * Construction
150
- * ------------
151
- * `new MessageReceiptsTracker({ channel, locateMessage? })`
152
- * - By default, message references are read through `channel.state.findMessageByTimestamp`.
153
- * - `locateMessage` can override this lookup strategy.
154
- * If a message cannot be resolved locally, the event is ignored.
155
- *
156
- * Event ingestion
157
- * ---------------
158
- * - `ingestInitial(rows: ReadStateResponse[])`: Builds initial state from server snapshot.
159
- * If a user’s `last_read` is ahead of `last_delivered_at`, the tracker enforces
160
- * the invariant `lastDeliveredRef >= lastReadRef`.
161
- * - `onMessageRead(user, readAt)`:
162
- * Advances the user’s read; also bumps delivered to match if needed.
163
- * - `onMessageDelivered(user, deliveredAt)`:
164
- * Advances the user’s delivered to `max(currentRead, deliveredAt)`.
165
- *
166
- * Queries
167
- * -------
168
- * - `readersForMessage(msgRef) : UserResponse[]` → users with `lastReadRef >= msgRef`
169
- * - `deliveredForMessage(msgRef) : UserResponse[]` → users with `lastDeliveredRef >= msgRef`
170
- * - `deliveredNotReadForMessage(msgRef): UserResponse[]` → delivered but `lastReadRef < msgRef`
171
- * - `usersWhoseLastReadIs : UserResponse[]` → users for whom `msgRef` is their *last read* (exact match)
172
- * - `usersWhoseLastDeliveredIs : UserResponse[]` → users for whom `msgRef` is their *last delivered* (exact match)
173
- * - `groupUsersByLastReadMessage : Record<MsgId, UserResponse[]> → mapping of messages to their readers
174
- * - `groupUsersByLastDeliveredMessage : Record<MsgId, UserResponse[]> → mapping of messages to their receivers
175
- * - `hasUserRead(msgRef, userId) : boolean`
176
- * - `hasUserDelivered(msgRef, userId) : boolean`
177
- *
178
- * Complexity
179
- * ----------
180
- * - Update on read/delivered: **O(log U)** (binary search + one splice) per event, where U is count of users stored by tracker.
181
- * - Query lists: **O(log U + K)** where `K` is the number of returned users (suffix length).
182
- * - Memory: **O(U)** - tracker’s memory grows linearly with the number of users in the channel/thread and does not depend on the number of messages.
183
- *
184
- * Scope & notes
185
- * -------------
186
- * - One tracker instance is **scoped to a single timeline**. Instantiate per channel/thread.
187
- * - Ordering is by **ascending timestamp**; ties are kept stable by inserting at the end of the
188
- * equal-timestamp plateau (upper-bound insertion), preserving intuitive arrival order.
189
- * - This tracker models **others’ progress toward own messages**;
118
+ * Messages resolve through `channel.messagePaginator.findItemByTimestamp` unless `locateMessage` is
119
+ * passed. Events for messages that cannot be resolved are ignored.
190
120
  */
191
121
  export class MessageReceiptsTracker extends WithSubscriptions {
192
122
  private byUser = new Map<UserId, UserProgress>();
@@ -219,8 +149,7 @@ export class MessageReceiptsTracker extends WithSubscriptions {
219
149
  if (this.hasSubscriptions) return;
220
150
 
221
151
  this.addUnsubscribeFunction(
222
- // Subscribe to only the `read` slice of the unified channel state so this reconcile fires on
223
- // read changes, not on every unrelated channel-state write (typing/members/…).
152
+ // Only the `read` slice, to skip unrelated channel-state writes.
224
153
  this.channel.state.subscribeWithSelector(
225
154
  (currentState) => ({ read: currentState.read }),
226
155
  (next, prev) => {
@@ -258,7 +187,7 @@ export class MessageReceiptsTracker extends WithSubscriptions {
258
187
  return;
259
188
  }
260
189
 
261
- // For non-bootstrap updates, we require patch metadata from channel read-store mutations.
190
+ // After the initial bootstrap, only updates that carry patch metadata are applied.
262
191
  if (!meta) return;
263
192
 
264
193
  const removedUserIds = new Set(meta?.removedUserIds ?? []);
@@ -291,7 +220,7 @@ export class MessageReceiptsTracker extends WithSubscriptions {
291
220
  }
292
221
  }
293
222
 
294
- /** Build initial state from server snapshots (single pass + sort). */
223
+ /** Replaces the tracker's state with the given server read states. */
295
224
  ingestInitial(responses: ReadStateResponse[]) {
296
225
  this.byUser.clear();
297
226
  this.readSorted = [];
@@ -327,7 +256,7 @@ export class MessageReceiptsTracker extends WithSubscriptions {
327
256
  this.emitSnapshot();
328
257
  }
329
258
 
330
- /** message.delivered — user device confirmed delivery up to and including messageId. */
259
+ /** `message.delivered`: delivery confirmed up to and including the message. */
331
260
  onMessageDelivered({
332
261
  user,
333
262
  deliveredAt,
@@ -349,7 +278,6 @@ export class MessageReceiptsTracker extends WithSubscriptions {
349
278
  compareRefsAsc(msgRef, userProgress.lastReadRef) < 0
350
279
  ? userProgress.lastReadRef
351
280
  : msgRef; // max(read, loc)
352
- // newly announced delivered is older than or equal what is already registered
353
281
  if (compareRefsAsc(newDelivered, userProgress.lastDeliveredRef) <= 0) return;
354
282
 
355
283
  removeByOldKey(
@@ -363,7 +291,7 @@ export class MessageReceiptsTracker extends WithSubscriptions {
363
291
  this.emitSnapshot();
364
292
  }
365
293
 
366
- /** message.read — user read up to and including messageId. */
294
+ /** `message.read`: read up to and including the message. */
367
295
  onMessageRead({
368
296
  user,
369
297
  readAt,
@@ -380,10 +308,8 @@ export class MessageReceiptsTracker extends WithSubscriptions {
380
308
  : this.locateMessage(timestamp);
381
309
  if (!msgRef) return;
382
310
  const userProgress = this.ensureUser(user);
383
- // newly announced read message is older than or equal the already recorded last read message
384
311
  if (compareRefsAsc(msgRef, userProgress.lastReadRef) <= 0) return;
385
312
 
386
- // move in readSorted
387
313
  removeByOldKey(
388
314
  this.readSorted,
389
315
  userProgress,
@@ -408,12 +334,7 @@ export class MessageReceiptsTracker extends WithSubscriptions {
408
334
  this.emitSnapshot();
409
335
  }
410
336
 
411
- /** notification.mark_unread — user marked messages unread starting at `first_unread_message_id`.
412
- * Sets lastReadRef to the event’s last_read_* values. Delivery never moves backward.
413
- * The event is sent only to the user that triggered the action (own user), so we will never adjust read ref
414
- * for other users - we will not see changes in the UI for other users. However, this implementation does not
415
- * take into consideration this fact and is ready to handle the mark-unread event for any user.
416
- */
337
+ /** `notification.mark_unread`: sets `lastReadRef` from `last_read_*`; delivery never moves back. */
417
338
  onNotificationMarkUnread({
418
339
  user,
419
340
  lastReadAt,
@@ -426,13 +347,12 @@ export class MessageReceiptsTracker extends WithSubscriptions {
426
347
  }) {
427
348
  const userProgress = this.ensureUser(user);
428
349
 
429
- // `0` is the "never read" sentinel
350
+ // A missing or non-finite `lastReadAt` means "never read".
430
351
  const newReadRef: MsgRef =
431
352
  lastReadAt != null && Number.isFinite(lastReadAt)
432
353
  ? { timestamp: lastReadAt, msgId: lastReadMessageId ?? '' }
433
354
  : { ...MIN_REF };
434
355
 
435
- // If no change, exit early.
436
356
  if (
437
357
  compareRefsAsc(newReadRef, userProgress.lastReadRef) === 0 &&
438
358
  newReadRef.msgId === userProgress.lastReadRef.msgId
@@ -481,10 +401,8 @@ export class MessageReceiptsTracker extends WithSubscriptions {
481
401
  }
482
402
 
483
403
  /**
484
- * Whether at least one other member has this message delivered.
485
- *
486
- * Reads the single furthest cursor rather than asking who is past this message, so the answer is
487
- * monotonic by construction: an older message can never report less than a newer one.
404
+ * Whether any other member has this message delivered. Uses the furthest cursor, so it is monotonic
405
+ * across messages.
488
406
  */
489
407
  isDeliveredToOthers(msgRef: MsgRef): boolean {
490
408
  const ref = this.snapshotStore.getLatestValue().lastDeliveredRefByOthers;
@@ -539,8 +457,6 @@ export class MessageReceiptsTracker extends WithSubscriptions {
539
457
  return users;
540
458
  }
541
459
 
542
- // ---- queries: per-user status ----
543
-
544
460
  hasUserRead(msgRef: MsgRef, userId: string): boolean {
545
461
  const up = this.byUser.get(userId);
546
462
  return !!up && compareRefsAsc(up.lastReadRef, msgRef) >= 0;
@@ -635,7 +551,7 @@ export class MessageReceiptsTracker extends WithSubscriptions {
635
551
  ) === 0 &&
636
552
  existingUserProgress.lastDeliveredRef.msgId ===
637
553
  nextUserProgress.lastDeliveredRef.msgId;
638
- // by reference: an updated user (a new name or image) arrives as a new object with the same id
554
+ // by reference: an updated user (a new name or image) arrives as a new object with the same ID
639
555
  const hasSameUser = existingUserProgress.user === nextUserProgress.user;
640
556
 
641
557
  if (hasSameReadRef && hasSameDeliveredRef && hasSameUser) {
@@ -10,9 +10,9 @@ type FailedSendCacheEntry = {
10
10
  };
11
11
 
12
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.
13
+ * Payloads of failed sends, kept so a retry sends exactly what failed. Entries expire after
14
+ * `failedSendCacheTtlMs`, and past `failedSendCacheMaxSize` the oldest is dropped. Both limits are read
15
+ * from the owner's config on every call.
16
16
  */
17
17
  export class FailedSendCache {
18
18
  private readonly entries = new Map<string, FailedSendCacheEntry>();
@@ -59,12 +59,7 @@ export class FailedSendCache {
59
59
  this.entries.delete(messageId);
60
60
  }
61
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
- */
62
+ /** Folds an edit into the cached payload, so a retry resends the message as it is now. */
68
63
  rewriteWithEdit(localMessage: LocalMessage) {
69
64
  const cached = this.get(localMessage.id);
70
65
  if (!cached) return;
@@ -16,14 +16,13 @@ export type MessageOperationStatePolicyContext = {
16
16
 
17
17
  /**
18
18
  * What {@link MessageOperationStatePolicy.optimistic} wrote, handed back to
19
- * {@link MessageOperationStatePolicy.failure} so it can decide whether to revert and to what.
19
+ * {@link MessageOperationStatePolicy.failure} so it can decide whether and what to revert.
20
20
  */
21
21
  export type OptimisticOutcome = {
22
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.
23
+ * The exact object the optimistic step wrote, used as a concurrency guard: `EntityStore.upsert`
24
+ * replaces the canonical copy, so `get(id) === applied` means nothing wrote since. Anything else is a
25
+ * fresher truth (a WS event, another operation) that a revert must not clobber.
27
26
  */
28
27
  applied?: LocalMessage;
29
28
  /** The copy that was there beforehand, i.e. what a revert restores. */
@@ -33,47 +32,33 @@ export type OptimisticOutcome = {
33
32
  const isHardDelete = (options: unknown) =>
34
33
  !!(options as DeleteMessageOptions | undefined)?.hard;
35
34
 
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
- */
35
+ /** Closes each phase's branches on the kind: a new `OperationKind` fails to compile until handled. */
40
36
  const unhandledKind = (kind: never): never => {
41
37
  throw new Error(`Unhandled message operation kind: ${String(kind)}`);
42
38
  };
43
39
 
44
40
  /**
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.
41
+ * The queued tasks that mean a failed request is still pending, so its optimistic state stays. A send
42
+ * has none: one that never reached the server must settle as `failed` even when queued, since retry is
43
+ * the only way the user can get the message out.
49
44
  */
50
45
  const PENDING_WHEN_QUEUED: Record<OperationKind, readonly QueueableType[]> = {
51
46
  delete: ['delete-message'],
52
47
  retry: [],
53
48
  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.
49
+ // An edit of a message the server has never seen is folded into its queued send
50
+ // (`AbstractOfflineDB.handleUpdateMessagePendingTask`), leaving no `update-message` row.
57
51
  update: ['update-message', 'send-message'],
58
52
  };
59
53
 
60
54
  /**
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:
55
+ * The local-state half of every message operation: what to show before the request resolves, and what
56
+ * to do with the answer or the failure.
65
57
  *
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.
58
+ * - send / retry: `sending`, then `failed` on failure, with a `failed` write-ahead to the offline DB.
59
+ * - update: applied and persisted, never reverted (that would destroy the user's text). A definitive
60
+ * rejection marks the message `failed` and keeps the edit; a queued failure is pending, not failed.
61
+ * - delete: marked `deleted` (removed for a hard delete), reverted on a definitive rejection.
77
62
  */
78
63
  export class MessageOperationStatePolicy {
79
64
  private ctx: MessageOperationStatePolicyContext;
@@ -99,10 +84,8 @@ export class MessageOperationStatePolicy {
99
84
  return { previous };
100
85
  }
101
86
 
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.
87
+ // Nothing holds this message, so there is nothing to hide, and ingesting would insert a phantom
88
+ // "Message deleted" row. The offline DB mirrors local state, so it is not written either.
106
89
  if (!previous) return {};
107
90
 
108
91
  const applied: LocalMessage = {
@@ -117,17 +100,16 @@ export class MessageOperationStatePolicy {
117
100
  }
118
101
 
119
102
  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`.
103
+ // An edit keeps the message's status: one the server has must not go back to `sending`, and one
104
+ // that never left the device stays `failed`.
122
105
  const isFailed = localMessage.status === 'failed';
123
106
  const editedAt = nowNs();
124
107
  const applied: LocalMessage = {
125
108
  ...localMessage,
126
109
  error: isFailed ? localMessage.error : undefined,
127
110
  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.
111
+ // `message_text_updated_at` drives the "edited" indicator, so it appears immediately, but only
112
+ // for a message the server has seen: a failed one never had a confirmed text update.
131
113
  ...(isFailed ? {} : { message_text_updated_at: editedAt }),
132
114
  };
133
115
  this.ctx.ingest(applied);
@@ -145,10 +127,9 @@ export class MessageOperationStatePolicy {
145
127
  : localMessage.status,
146
128
  };
147
129
  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.
130
+ // Write-ahead, pessimistically `failed`: if the app dies before the server's ack the message
131
+ // comes back failed and retryable, and a success overwrites it. The retry payload is not
132
+ // persisted: `MessageOperations.retry` rebuilds it when `failedSendCache` is cold.
152
133
  this.ctx.persist({ ...applied, status: 'failed' });
153
134
  return { applied, previous };
154
135
  }
@@ -169,9 +150,8 @@ export class MessageOperationStatePolicy {
169
150
  optimistic?: OptimisticOutcome;
170
151
  options?: MessageOperationSpec[K]['options'];
171
152
  }) {
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.
153
+ // `formatMessage(undefined)` does not throw: it yields an ID-less message whose `updated_at` would
154
+ // beat the freshness check below.
175
155
  if (!messageFromResponse) return;
176
156
 
177
157
  const formatted = formatMessage({ ...messageFromResponse, status: 'received' });
@@ -182,9 +162,8 @@ export class MessageOperationStatePolicy {
182
162
  this.ctx.purge(messageId);
183
163
  return;
184
164
  }
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.
165
+ // Mirrors the `!previous` guard in `optimistic`. Read live, not from the optimistic snapshot, so a
166
+ // copy that arrived while the request was open is still marked.
188
167
  if (!this.ctx.get(messageId)) return;
189
168
 
190
169
  this.ctx.ingest(formatted);
@@ -198,10 +177,8 @@ export class MessageOperationStatePolicy {
198
177
  const nothingWroteSinceOptimistic =
199
178
  !!optimistic?.applied && existing === optimistic.applied;
200
179
 
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.
180
+ // When something else wrote since the optimistic step, both copies are server derived, so
181
+ // `updated_at` compares one clock.
205
182
  const serverNewer = !existing || formatted.updated_at > existing.updated_at;
206
183
  const serverSameOrNewer = !existing || formatted.updated_at >= existing.updated_at;
207
184
  const existingIsOurOptimisticSend = existing?.status === 'sending';
@@ -211,12 +188,13 @@ export class MessageOperationStatePolicy {
211
188
  serverNewer ||
212
189
  (existingIsOurOptimisticSend && serverSameOrNewer);
213
190
 
191
+ // Declined only when a copy at least as fresh already landed (for example the same message
192
+ // from a WS event), whose own write replaced the `failed` row.
214
193
  if (!applyServerCopy) return;
215
194
 
216
195
  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.
196
+ // Persist only what was applied, so the row never disagrees with memory. For send/retry this
197
+ // supersedes the `failed` write-ahead.
220
198
  this.ctx.persist(formatted);
221
199
  return;
222
200
  }
@@ -251,8 +229,7 @@ export class MessageOperationStatePolicy {
251
229
  return;
252
230
  }
253
231
 
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.
232
+ // A request waiting in the offline queue has not failed: the optimistic state stays.
256
233
  const pendingTaskTypes = PENDING_WHEN_QUEUED[kind];
257
234
  const queued =
258
235
  pendingTaskTypes.length > 0 &&
@@ -265,9 +242,8 @@ export class MessageOperationStatePolicy {
265
242
 
266
243
  if (kind === 'update') {
267
244
  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.
245
+ // The edit is kept and the failure recorded on it. Note the retry this enables re-sends rather
246
+ // than re-edits.
271
247
  const failed: LocalMessage = {
272
248
  ...(this.ctx.get(messageId) ?? localMessage),
273
249
  error: parsed,
@@ -298,12 +274,10 @@ export class MessageOperationStatePolicy {
298
274
  options?: MessageOperationSpec[K]['options'];
299
275
  }) {
300
276
  const previous = optimistic?.previous;
301
- // Nothing was held locally, so the optimistic step changed nothing to put back.
302
277
  if (!previous) return;
303
278
 
304
279
  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.
280
+ // A hard delete removed the message, so there is no current copy to compare: restore the snapshot.
307
281
  this.ctx.ingest(previous);
308
282
  this.ctx.persist(previous);
309
283
  return;
@@ -312,8 +286,7 @@ export class MessageOperationStatePolicy {
312
286
  if (optimistic?.applied && this.ctx.get(messageId) !== optimistic.applied) return;
313
287
 
314
288
  this.ctx.ingest(previous);
315
- // Undoes the row the optimistic step soft-deleted: the upsert rewrites `type` and `deletedAt` from
316
- // the restored message.
289
+ // The upsert rewrites `type` and `deletedAt` from the restored message, undoing the soft delete.
317
290
  this.ctx.persist(previous);
318
291
  }
319
292
  }