stream-chat 10.1.1 → 10.3.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 (109) hide show
  1. package/dist/cjs/index.browser.js +4736 -2819
  2. package/dist/cjs/index.browser.js.map +4 -4
  3. package/dist/cjs/index.node.js +4757 -2819
  4. package/dist/cjs/index.node.js.map +4 -4
  5. package/dist/esm/index.mjs +4736 -2819
  6. package/dist/esm/index.mjs.map +4 -4
  7. package/dist/types/channel.d.ts +62 -3
  8. package/dist/types/client.d.ts +9 -1
  9. package/dist/types/configuration/types.d.ts +2 -0
  10. package/dist/types/connection/ConnectionRecoveryManager.d.ts +1 -0
  11. package/dist/types/gen/chat/ChatApi.d.ts +12 -1
  12. package/dist/types/gen/models/index.d.ts +659 -11
  13. package/dist/types/gen/moderation/ModerationApi.d.ts +3 -1
  14. package/dist/types/index.d.ts +2 -0
  15. package/dist/types/messageComposer/attachmentManager.d.ts +2 -0
  16. package/dist/types/messageComposer/index.d.ts +1 -0
  17. package/dist/types/messageComposer/linkPreviewsManager.d.ts +1 -0
  18. package/dist/types/messageComposer/messageComposer.d.ts +33 -7
  19. package/dist/types/messageComposer/middleware/messageComposer/compositionValidation.d.ts +1 -2
  20. package/dist/types/messageComposer/middleware/messageComposer/index.d.ts +1 -0
  21. package/dist/types/messageComposer/middleware/messageComposer/scheduledMessage.d.ts +4 -0
  22. package/dist/types/messageComposer/middleware/textComposer/commandUtils.d.ts +1 -0
  23. package/dist/types/messageComposer/scheduledMessageComposition.d.ts +32 -0
  24. package/dist/types/messageMarks/MessageMarkManager.d.ts +44 -0
  25. package/dist/types/messageMarks/index.d.ts +1 -0
  26. package/dist/types/messageOperations/MessageOperations.d.ts +12 -1
  27. package/dist/types/messageOperations/index.d.ts +1 -0
  28. package/dist/types/messageOperations/reflectMessageMarkEvent.d.ts +9 -0
  29. package/dist/types/messageOperations/sendOrdering.d.ts +4 -3
  30. package/dist/types/messageOperations/types.d.ts +6 -2
  31. package/dist/types/notifications/types.d.ts +4 -0
  32. package/dist/types/offline-support/offline_support_api.d.ts +19 -1
  33. package/dist/types/offline-support/types.d.ts +19 -1
  34. package/dist/types/pagination/PaginatorView.d.ts +55 -0
  35. package/dist/types/pagination/index.d.ts +1 -0
  36. package/dist/types/pagination/paginators/BasePaginator.d.ts +49 -0
  37. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +0 -9
  38. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +6 -0
  39. package/dist/types/pagination/paginators/MessageMarkPaginator.d.ts +61 -0
  40. package/dist/types/pagination/paginators/ScheduledMessagePaginator.d.ts +83 -0
  41. package/dist/types/pagination/paginators/index.d.ts +2 -0
  42. package/dist/types/scheduledMessages/ScheduledMessagePaginatorsManager.d.ts +47 -0
  43. package/dist/types/scheduledMessages/ScheduledMessageStatePolicy.d.ts +12 -0
  44. package/dist/types/scheduledMessages/ScheduledMessagesView.d.ts +38 -0
  45. package/dist/types/scheduledMessages/composition.d.ts +5 -0
  46. package/dist/types/scheduledMessages/constants.d.ts +56 -0
  47. package/dist/types/scheduledMessages/editResolvers.d.ts +4 -0
  48. package/dist/types/scheduledMessages/errors.d.ts +3 -0
  49. package/dist/types/scheduledMessages/eventHandlers.d.ts +8 -0
  50. package/dist/types/scheduledMessages/index.d.ts +7 -0
  51. package/dist/types/scheduledMessages/limits.d.ts +6 -0
  52. package/dist/types/scheduledMessages/types.d.ts +65 -0
  53. package/dist/types/thread.d.ts +12 -1
  54. package/dist/types/utils.d.ts +7 -0
  55. package/package.json +1 -1
  56. package/src/channel.ts +231 -7
  57. package/src/client.ts +46 -2
  58. package/src/configuration/keys.ts +2 -0
  59. package/src/configuration/shape.ts +15 -0
  60. package/src/configuration/types.ts +3 -1
  61. package/src/connection/ConnectionRecoveryManager.ts +7 -0
  62. package/src/errors.ts +11 -0
  63. package/src/gen/chat/ChatApi.ts +60 -3
  64. package/src/gen/models/index.ts +794 -23
  65. package/src/gen/moderation/ModerationApi.ts +24 -3
  66. package/src/index.ts +2 -0
  67. package/src/messageComposer/attachmentManager.ts +43 -24
  68. package/src/messageComposer/index.ts +1 -0
  69. package/src/messageComposer/messageComposer.ts +140 -32
  70. package/src/messageComposer/middleware/messageComposer/MessageComposerMiddlewareExecutor.ts +2 -0
  71. package/src/messageComposer/middleware/messageComposer/compositionValidation.ts +40 -47
  72. package/src/messageComposer/middleware/messageComposer/index.ts +1 -0
  73. package/src/messageComposer/middleware/messageComposer/scheduledMessage.ts +38 -0
  74. package/src/messageComposer/middleware/textComposer/commandUtils.ts +8 -0
  75. package/src/messageComposer/scheduledMessageComposition.ts +324 -0
  76. package/src/messageMarks/MessageMarkManager.ts +145 -0
  77. package/src/messageMarks/index.ts +1 -0
  78. package/src/messageOperations/MessageOperationStatePolicy.ts +7 -0
  79. package/src/messageOperations/MessageOperations.ts +154 -1
  80. package/src/messageOperations/index.ts +1 -0
  81. package/src/messageOperations/reflectMessageMarkEvent.ts +47 -0
  82. package/src/messageOperations/reflectReactionEvent.ts +3 -0
  83. package/src/messageOperations/sendOrdering.ts +11 -4
  84. package/src/messageOperations/types.ts +6 -2
  85. package/src/notifications/types.ts +4 -0
  86. package/src/offline-support/offline_support_api.ts +61 -1
  87. package/src/offline-support/queueableOperations.ts +6 -0
  88. package/src/offline-support/types.ts +28 -0
  89. package/src/pagination/PaginatorView.ts +103 -0
  90. package/src/pagination/index.ts +1 -0
  91. package/src/pagination/paginators/BasePaginator.ts +204 -29
  92. package/src/pagination/paginators/ChannelPaginator.ts +8 -28
  93. package/src/pagination/paginators/MessageIntervalPaginator.ts +14 -1
  94. package/src/pagination/paginators/MessageMarkPaginator.ts +222 -0
  95. package/src/pagination/paginators/ScheduledMessagePaginator.ts +352 -0
  96. package/src/pagination/paginators/index.ts +2 -0
  97. package/src/scheduledMessages/ScheduledMessagePaginatorsManager.ts +268 -0
  98. package/src/scheduledMessages/ScheduledMessageStatePolicy.ts +42 -0
  99. package/src/scheduledMessages/ScheduledMessagesView.ts +57 -0
  100. package/src/scheduledMessages/composition.ts +129 -0
  101. package/src/scheduledMessages/constants.ts +79 -0
  102. package/src/scheduledMessages/editResolvers.ts +51 -0
  103. package/src/scheduledMessages/errors.ts +45 -0
  104. package/src/scheduledMessages/eventHandlers.ts +58 -0
  105. package/src/scheduledMessages/index.ts +7 -0
  106. package/src/scheduledMessages/limits.ts +32 -0
  107. package/src/scheduledMessages/types.ts +124 -0
  108. package/src/thread.ts +41 -17
  109. package/src/utils.ts +18 -0
@@ -0,0 +1,268 @@
1
+ import { StateStore } from '@stream-io/state-store';
2
+ import { EventHandlerPipeline } from '../EventHandlerPipeline';
3
+ import { WithSubscriptions } from '../utils/WithSubscriptions';
4
+ import { ScheduledMessageErrorReason } from './constants';
5
+ import { getScheduledMessageErrorReason } from './errors';
6
+ import { DEFAULT_SCHEDULED_MESSAGE_EVENT_HANDLERS } from './eventHandlers';
7
+ import type { Unsubscribe } from '@stream-io/state-store';
8
+ import type { StreamChat } from '../client';
9
+ import type { ScheduledMessageResponse } from '../gen/models';
10
+ import type { ScheduledMessagePaginator } from '../pagination/paginators/ScheduledMessagePaginator';
11
+ import type {
12
+ AddScheduledMessageEventHandlerParams,
13
+ RemoveScheduledMessageEventHandlersParams,
14
+ ScheduledMessagePaginatorsManagerEventHandlerContext,
15
+ ScheduledMessagePaginatorsManagerEventHandlers,
16
+ ScheduledMessagePaginatorsManagerEventType,
17
+ ScheduledMessagePaginatorsManagerOptions,
18
+ ScheduledMessagePaginatorsManagerState,
19
+ SetScheduledMessageEventHandlersParams,
20
+ } from './types';
21
+
22
+ const MANAGER_NAME = 'ScheduledMessagePaginatorsManager';
23
+
24
+ const isDisabledError = (error: Error | undefined) =>
25
+ !!error &&
26
+ getScheduledMessageErrorReason(error) === ScheduledMessageErrorReason.Disabled;
27
+
28
+ const createInitialState = (): ScheduledMessagePaginatorsManagerState => ({
29
+ isDisabled: false,
30
+ paginators: [],
31
+ });
32
+
33
+ const copyEventHandlers = (
34
+ handlers: ScheduledMessagePaginatorsManagerEventHandlers,
35
+ ): ScheduledMessagePaginatorsManagerEventHandlers => {
36
+ const copy: ScheduledMessagePaginatorsManagerEventHandlers = {};
37
+ for (const [eventType, eventHandlers] of Object.entries(handlers)) {
38
+ if (eventHandlers) copy[eventType] = [...eventHandlers];
39
+ }
40
+ return copy;
41
+ };
42
+
43
+ const dedupeById = (paginators: ScheduledMessagePaginator[]) => {
44
+ const seenIds = new Set<string>();
45
+ return paginators.filter(({ id }) => {
46
+ if (seenIds.has(id)) return false;
47
+ seenIds.add(id);
48
+ return true;
49
+ });
50
+ };
51
+
52
+ const sameOrder = (
53
+ first: ScheduledMessagePaginator[],
54
+ second: ScheduledMessagePaginator[],
55
+ ) =>
56
+ first.length === second.length &&
57
+ first.every((paginator, index) => paginator === second[index]);
58
+
59
+ export class ScheduledMessagePaginatorsManager extends WithSubscriptions {
60
+ private eventHandlerPipelines = new Map<
61
+ ScheduledMessagePaginatorsManagerEventType,
62
+ EventHandlerPipeline<ScheduledMessagePaginatorsManagerEventHandlerContext>
63
+ >();
64
+ private queryErrorUnsubscribeByPaginator = new Map<
65
+ ScheduledMessagePaginator,
66
+ Unsubscribe
67
+ >();
68
+
69
+ public readonly client: StreamChat;
70
+ public state: StateStore<ScheduledMessagePaginatorsManagerState>;
71
+
72
+ constructor({
73
+ client,
74
+ eventHandlers = ScheduledMessagePaginatorsManager.getDefaultHandlers(),
75
+ }: ScheduledMessagePaginatorsManagerOptions) {
76
+ super();
77
+ this.client = client;
78
+ this.state = new StateStore<ScheduledMessagePaginatorsManagerState>(
79
+ createInitialState(),
80
+ );
81
+
82
+ this.installEventHandlers(eventHandlers);
83
+ }
84
+
85
+ public static getDefaultHandlers(): ScheduledMessagePaginatorsManagerEventHandlers {
86
+ return copyEventHandlers(DEFAULT_SCHEDULED_MESSAGE_EVENT_HANDLERS);
87
+ }
88
+
89
+ get paginators() {
90
+ return this.state.getLatestValue().paginators;
91
+ }
92
+
93
+ get isDisabled() {
94
+ return this.state.getLatestValue().isDisabled;
95
+ }
96
+
97
+ get pipelines() {
98
+ return this.eventHandlerPipelines;
99
+ }
100
+
101
+ private get eventHandlerContext(): ScheduledMessagePaginatorsManagerEventHandlerContext {
102
+ return { scheduledMessagePaginators: this };
103
+ }
104
+
105
+ private installEventHandlers(handlers: ScheduledMessagePaginatorsManagerEventHandlers) {
106
+ for (const [eventType, eventHandlers] of Object.entries(handlers)) {
107
+ if (eventHandlers) this.ensurePipeline(eventType).replaceAll(eventHandlers);
108
+ }
109
+ }
110
+
111
+ private watchQueryErrors(paginator: ScheduledMessagePaginator) {
112
+ if (this.queryErrorUnsubscribeByPaginator.has(paginator)) return;
113
+
114
+ const unsubscribe = paginator.state.subscribeWithSelector(
115
+ ({ lastQueryError }) => ({ lastQueryError }),
116
+ this.updateIsDisabled,
117
+ );
118
+
119
+ this.queryErrorUnsubscribeByPaginator.set(paginator, unsubscribe);
120
+ }
121
+
122
+ private unwatchQueryErrors(paginator: ScheduledMessagePaginator) {
123
+ this.queryErrorUnsubscribeByPaginator.get(paginator)?.();
124
+ this.queryErrorUnsubscribeByPaginator.delete(paginator);
125
+ this.updateIsDisabled();
126
+ }
127
+
128
+ private updateIsDisabled = () => {
129
+ const isDisabled = this.paginators.some(({ lastQueryError }) =>
130
+ isDisabledError(lastQueryError),
131
+ );
132
+
133
+ this.state.partialNext({ isDisabled });
134
+ };
135
+
136
+ public ensurePipeline(eventType: ScheduledMessagePaginatorsManagerEventType) {
137
+ const existingPipeline = this.eventHandlerPipelines.get(eventType);
138
+ if (existingPipeline) return existingPipeline;
139
+
140
+ const pipeline =
141
+ new EventHandlerPipeline<ScheduledMessagePaginatorsManagerEventHandlerContext>({
142
+ id: `${MANAGER_NAME}:${eventType}`,
143
+ });
144
+ this.eventHandlerPipelines.set(eventType, pipeline);
145
+
146
+ return pipeline;
147
+ }
148
+
149
+ public addEventHandler({
150
+ eventType,
151
+ ...payload
152
+ }: AddScheduledMessageEventHandlerParams): Unsubscribe {
153
+ return this.ensurePipeline(eventType).insert(payload);
154
+ }
155
+
156
+ public setEventHandlers({
157
+ eventType,
158
+ handlers,
159
+ }: SetScheduledMessageEventHandlersParams) {
160
+ return this.ensurePipeline(eventType).replaceAll(handlers);
161
+ }
162
+
163
+ public removeEventHandlers({
164
+ eventType,
165
+ handlers,
166
+ }: RemoveScheduledMessageEventHandlersParams) {
167
+ const pipeline = this.eventHandlerPipelines.get(eventType);
168
+ handlers.forEach((params) => pipeline?.remove(params));
169
+ }
170
+
171
+ public getPaginatorById(id: string): ScheduledMessagePaginator | undefined {
172
+ return this.paginators.find((paginator) => paginator.id === id);
173
+ }
174
+
175
+ public setPaginators(paginators: ScheduledMessagePaginator[]) {
176
+ const nextPaginators = dedupeById(paginators);
177
+ const currentPaginators = this.paginators;
178
+ if (sameOrder(currentPaginators, nextPaginators)) return;
179
+
180
+ const detached = currentPaginators.filter(
181
+ (paginator) => !nextPaginators.includes(paginator),
182
+ );
183
+ const attached = nextPaginators.filter(
184
+ (paginator) => !currentPaginators.includes(paginator),
185
+ );
186
+
187
+ this.state.partialNext({ paginators: nextPaginators });
188
+
189
+ detached.forEach((paginator) => {
190
+ this.unwatchQueryErrors(paginator);
191
+ paginator.cancelScheduledQuery();
192
+ });
193
+ attached.forEach((paginator) => this.watchQueryErrors(paginator));
194
+ }
195
+
196
+ public clearPaginators(): ScheduledMessagePaginator[] {
197
+ const cleared = this.paginators;
198
+ this.setPaginators([]);
199
+ return cleared;
200
+ }
201
+
202
+ public insertPaginator({
203
+ index,
204
+ paginator,
205
+ }: {
206
+ paginator: ScheduledMessagePaginator;
207
+ index?: number;
208
+ }) {
209
+ const paginators = this.paginators.filter(({ id }) => id !== paginator.id);
210
+ const validIndex = Math.max(
211
+ 0,
212
+ Math.min(index ?? paginators.length, paginators.length),
213
+ );
214
+ paginators.splice(validIndex, 0, paginator);
215
+ this.setPaginators(paginators);
216
+ }
217
+
218
+ public removePaginator(
219
+ paginatorOrId: ScheduledMessagePaginator | string,
220
+ ): ScheduledMessagePaginator | undefined {
221
+ const id = typeof paginatorOrId === 'string' ? paginatorOrId : paginatorOrId.id;
222
+ const removed = this.getPaginatorById(id);
223
+ if (!removed) return undefined;
224
+ this.setPaginators(this.paginators.filter((paginator) => paginator !== removed));
225
+ return removed;
226
+ }
227
+
228
+ public resetPaginatorStates() {
229
+ this.paginators.forEach((paginator) => {
230
+ paginator.cancelScheduledQuery();
231
+ paginator.resetState();
232
+ });
233
+ this.state.partialNext({ isDisabled: false });
234
+ }
235
+
236
+ public ingest = (scheduledMessage: ScheduledMessageResponse) => {
237
+ this.paginators.forEach((paginator) => paginator.ingestItem(scheduledMessage));
238
+ };
239
+
240
+ public recover = async () => {
241
+ const loadedPaginators = this.paginators.filter(({ hasLoadedPage }) => hasLoadedPage);
242
+
243
+ await Promise.allSettled(loadedPaginators.map((paginator) => paginator.reload()));
244
+ };
245
+
246
+ /**
247
+ * Starts syncing the registered lists with the client's WS events. Nothing keeps them in sync
248
+ * until this is called, so an integration has to call it once a user is connected and call the
249
+ * returned unsubscribe (or {@link unregisterSubscriptions}) on teardown. The Stream UI SDKs do
250
+ * this for you; a pure-LLC integration must do it itself. Ref-counted, so several holders can
251
+ * share one manager and only the last unsubscribe tears the subscriptions down.
252
+ */
253
+ public registerSubscriptions(): Unsubscribe {
254
+ if (!this.hasSubscriptions) {
255
+ this.addUnsubscribeFunction(
256
+ this.client.on((event) => {
257
+ this.eventHandlerPipelines
258
+ .get(event.type)
259
+ ?.run(event, this.eventHandlerContext);
260
+ }).unsubscribe,
261
+ );
262
+ }
263
+
264
+ this.incrementRefCount();
265
+
266
+ return () => this.unregisterSubscriptions();
267
+ }
268
+ }
@@ -0,0 +1,42 @@
1
+ import { SCHEDULED_MESSAGE_STATUS } from './constants';
2
+ import { isScheduledMessageNotFoundError } from './errors';
3
+ import type { ScheduledMessageResponse } from '../gen/models';
4
+
5
+ export type ScheduledMessageOperationKind = 'schedule' | 'update' | 'cancel' | 'sendNow';
6
+
7
+ export type ScheduledMessageStatePolicyContext = {
8
+ ingest: (scheduledMessage: ScheduledMessageResponse) => void;
9
+ get: (id: string) => ScheduledMessageResponse | undefined;
10
+ };
11
+
12
+ export class ScheduledMessageStatePolicy {
13
+ private ctx: ScheduledMessageStatePolicyContext;
14
+
15
+ constructor(ctx: ScheduledMessageStatePolicyContext) {
16
+ this.ctx = ctx;
17
+ }
18
+
19
+ success(
20
+ kind: ScheduledMessageOperationKind,
21
+ scheduledMessage: ScheduledMessageResponse | undefined,
22
+ ) {
23
+ if (!scheduledMessage) return;
24
+
25
+ if (kind === 'cancel') {
26
+ this.ctx.ingest({ ...scheduledMessage, status: SCHEDULED_MESSAGE_STATUS.Canceled });
27
+ return;
28
+ }
29
+
30
+ this.ctx.ingest(scheduledMessage);
31
+ }
32
+
33
+ failure(kind: ScheduledMessageOperationKind, id: string | undefined, error: unknown) {
34
+ if (kind === 'schedule' || kind === 'sendNow') return;
35
+ if (!id || !isScheduledMessageNotFoundError(error)) return;
36
+
37
+ const stored = this.ctx.get(id);
38
+ if (stored) {
39
+ this.ctx.ingest({ ...stored, status: SCHEDULED_MESSAGE_STATUS.Canceled });
40
+ }
41
+ }
42
+ }
@@ -0,0 +1,57 @@
1
+ import type { PaginatorViewState } from '../pagination/PaginatorView';
2
+ import { PaginatorView } from '../pagination/PaginatorView';
3
+ import type { ScheduledMessageResponse } from '../gen/models';
4
+ import type { ScheduledMessagePaginator } from '../pagination/paginators/ScheduledMessagePaginator';
5
+
6
+ /**
7
+ * Which of its paginator's scheduled messages a view shows.
8
+ * - `all`: every one, e.g. of a list registered with `client.scheduledMessagePaginators`.
9
+ * - `channel`: a channel's own, without thread replies.
10
+ * - `thread`: the replies of the thread whose parent message is `parentId`.
11
+ */
12
+ export type ScheduledMessagesViewScope =
13
+ | { type: 'all' }
14
+ | { type: 'channel' }
15
+ | { parentId: string; type: 'thread' };
16
+
17
+ export type ScheduledMessagesViewState = PaginatorViewState<ScheduledMessageResponse>;
18
+
19
+ export type ScheduledMessagesViewOptions = {
20
+ /** The list the messages come from. The view only reads it. */
21
+ paginator: ScheduledMessagePaginator;
22
+ /** Defaults to `{ type: 'all' }`. */
23
+ scope?: ScheduledMessagesViewScope;
24
+ };
25
+
26
+ const getScopePredicate = (scope: ScheduledMessagesViewScope) => {
27
+ switch (scope.type) {
28
+ case 'channel':
29
+ return ({ message }: ScheduledMessageResponse) => !message.parent_id;
30
+ case 'thread':
31
+ return ({ message }: ScheduledMessageResponse) =>
32
+ message.parent_id === scope.parentId;
33
+ default:
34
+ return undefined;
35
+ }
36
+ };
37
+
38
+ /**
39
+ * A scope of a `ScheduledMessagePaginator`, e.g. a channel's own scheduled messages or a thread's
40
+ * scheduled replies. The server cannot filter scheduled messages by thread, so a channel's
41
+ * paginator holds both, and each scope is a `PaginatorView` of it rather than a list of
42
+ * its own. `Channel` and `Thread` hold theirs registered while they are.
43
+ */
44
+ export class ScheduledMessagesView extends PaginatorView<ScheduledMessageResponse> {
45
+ declare public readonly paginator: ScheduledMessagePaginator;
46
+ public readonly scope: ScheduledMessagesViewScope;
47
+
48
+ constructor({ paginator, scope = { type: 'all' } }: ScheduledMessagesViewOptions) {
49
+ super({ paginator, predicate: getScopePredicate(scope) });
50
+ this.scope = scope;
51
+ }
52
+
53
+ /** The thread's parent message ID, for a `thread` scope. */
54
+ get parentId() {
55
+ return this.scope.type === 'thread' ? this.scope.parentId : undefined;
56
+ }
57
+ }
@@ -0,0 +1,129 @@
1
+ import { LOCAL_MESSAGE_FIELDS, RESERVED_UPDATED_MESSAGE_FIELDS } from '../constants';
2
+ import { formatMessage, omitFields, pickFields } from '../utils';
3
+ import { nsToDate } from '../utils/time';
4
+ import type {
5
+ MessageRequest,
6
+ ScheduledMessageContentResponse,
7
+ ScheduledMessageResponse,
8
+ } from '../gen/models';
9
+ import type { DraftMessage, LocalMessage, UserResponse } from '../types';
10
+
11
+ const SCHEDULED_MESSAGE_SERVER_FIELDS = ['id', 'mml', 'shared_location'];
12
+
13
+ const SERVER_OWNED_FIELDS: ReadonlySet<string> = new Set([
14
+ ...Object.keys(RESERVED_UPDATED_MESSAGE_FIELDS),
15
+ ...Object.keys(LOCAL_MESSAGE_FIELDS),
16
+ ...SCHEDULED_MESSAGE_SERVER_FIELDS,
17
+ ]);
18
+
19
+ const COMPOSER_CONTENT_FIELD_NAMES = [
20
+ 'attachments',
21
+ 'custom',
22
+ 'mentioned_channel',
23
+ 'mentioned_group_ids',
24
+ 'mentioned_here',
25
+ 'mentioned_roles',
26
+ 'parent_id',
27
+ 'poll_id',
28
+ 'quoted_message_id',
29
+ 'show_in_channel',
30
+ 'text',
31
+ ] as const satisfies ReadonlyArray<keyof ScheduledMessageContentResponse>;
32
+
33
+ const COMPOSER_OWNED_FIELD_NAMES = [
34
+ ...COMPOSER_CONTENT_FIELD_NAMES,
35
+ 'mentioned_users',
36
+ ] as const satisfies ReadonlyArray<keyof ScheduledMessageContentResponse>;
37
+
38
+ const COMPOSER_OWNED_FIELDS: ReadonlySet<string> = new Set(COMPOSER_OWNED_FIELD_NAMES);
39
+
40
+ const STORED_FIELDS_REPLACED_ON_UPDATE: ReadonlySet<string> = new Set([
41
+ ...SERVER_OWNED_FIELDS,
42
+ ...COMPOSER_OWNED_FIELDS,
43
+ ]);
44
+
45
+ const COMPOSED_FIELDS_DROPPED_ON_UPDATE: ReadonlySet<string> = new Set(
46
+ [...SERVER_OWNED_FIELDS].filter((field) => !COMPOSER_OWNED_FIELDS.has(field)),
47
+ );
48
+
49
+ export const toComposerContent = (
50
+ scheduledMessage: ScheduledMessageResponse,
51
+ ): DraftMessage => {
52
+ const { id, message } = scheduledMessage;
53
+
54
+ const content: DraftMessage = {
55
+ ...pickFields(message, COMPOSER_CONTENT_FIELD_NAMES),
56
+ id,
57
+ };
58
+
59
+ return content;
60
+ };
61
+
62
+ export const toScheduledMessagePayload = (
63
+ composedMessage: MessageRequest,
64
+ scheduledMessage: ScheduledMessageResponse,
65
+ ): MessageRequest => {
66
+ const { message: storedMessage } = scheduledMessage;
67
+ const { parent_id: parentId, pin_expires: pinExpires } = storedMessage;
68
+
69
+ const preservedFields = omitFields(storedMessage, STORED_FIELDS_REPLACED_ON_UPDATE);
70
+ const composedFields = omitFields(composedMessage, COMPOSED_FIELDS_DROPPED_ON_UPDATE);
71
+
72
+ const scheduledMessagePayload: MessageRequest = {
73
+ ...preservedFields,
74
+ ...(pinExpires === undefined ? {} : { pin_expires: nsToDate(pinExpires) }),
75
+ ...composedFields,
76
+ parent_id: parentId,
77
+ };
78
+
79
+ return scheduledMessagePayload;
80
+ };
81
+
82
+ export const toScheduledMessagePreview = (
83
+ scheduledMessage: ScheduledMessageResponse,
84
+ ): LocalMessage => {
85
+ const { cid, created_at, id, message, scheduled_at, user } = scheduledMessage;
86
+ const {
87
+ attachments = [],
88
+ custom = {},
89
+ mentioned_channel = false,
90
+ mentioned_here = false,
91
+ mentioned_users: mentionedUserIds = [],
92
+ parent_id,
93
+ poll_id,
94
+ quoted_message_id,
95
+ show_in_channel,
96
+ silent = false,
97
+ text,
98
+ } = message;
99
+
100
+ return formatMessage({
101
+ attachments,
102
+ cid,
103
+ created_at,
104
+ custom,
105
+ deleted_reply_count: 0,
106
+ html: '',
107
+ id,
108
+ latest_reactions: [],
109
+ mentioned_channel,
110
+ mentioned_here,
111
+ mentioned_users: mentionedUserIds.map((id) => ({ id }) as UserResponse),
112
+ own_reactions: [],
113
+ parent_id,
114
+ pinned: false,
115
+ poll_id,
116
+ quoted_message_id,
117
+ reaction_counts: {},
118
+ reaction_scores: {},
119
+ reply_count: 0,
120
+ restricted_visibility: [],
121
+ shadowed: false,
122
+ show_in_channel,
123
+ silent,
124
+ text,
125
+ type: 'regular',
126
+ updated_at: scheduled_at,
127
+ user,
128
+ });
129
+ };
@@ -0,0 +1,79 @@
1
+ import type {
2
+ ScheduledMessageFailureReason,
3
+ ScheduledMessageQueryStatus,
4
+ ScheduledMessageStatus,
5
+ } from '../gen/models';
6
+
7
+ export const SCHEDULED_MESSAGE_STATUS = {
8
+ Canceled: 'canceled',
9
+ Failed: 'failed',
10
+ Scheduled: 'scheduled',
11
+ Sending: 'sending',
12
+ Sent: 'sent',
13
+ } as const satisfies Record<string, ScheduledMessageStatus>;
14
+
15
+ export const SCHEDULED_MESSAGE_ACTIVE_STATUSES: ScheduledMessageQueryStatus[] = [
16
+ SCHEDULED_MESSAGE_STATUS.Scheduled,
17
+ SCHEDULED_MESSAGE_STATUS.Sending,
18
+ SCHEDULED_MESSAGE_STATUS.Failed,
19
+ ];
20
+
21
+ export const SCHEDULED_MESSAGE_FAILURE_REASON = {
22
+ Banned: 'banned',
23
+ ChannelDeleted: 'channel_deleted',
24
+ ChannelFrozen: 'channel_frozen',
25
+ Expired: 'expired',
26
+ HookRejected: 'hook_rejected',
27
+ InternalError: 'internal_error',
28
+ InvalidMessage: 'invalid_message',
29
+ ModerationBlocked: 'moderation_blocked',
30
+ NoPermission: 'no_permission',
31
+ PendingNotSupported: 'pending_not_supported',
32
+ UserDeleted: 'user_deleted',
33
+ } as const satisfies Record<string, ScheduledMessageFailureReason>;
34
+
35
+ export const ScheduledMessageErrorReason = {
36
+ AlreadySent: 'scheduled_message_already_sent',
37
+ Canceled: 'scheduled_message_canceled',
38
+ ChannelLimit: 'scheduled_limit_channel',
39
+ Conflict: 'scheduled_message_conflict',
40
+ Disabled: 'scheduled_messages_disabled',
41
+ IdTaken: 'scheduled_message_id_taken',
42
+ NotEditable: 'scheduled_message_not_editable',
43
+ Sending: 'scheduled_message_sending',
44
+ TooFar: 'scheduled_at_too_far',
45
+ TooSoon: 'scheduled_at_too_soon',
46
+ UserLimit: 'scheduled_limit_user',
47
+ } as const;
48
+
49
+ export type ScheduledMessageErrorReason =
50
+ (typeof ScheduledMessageErrorReason)[keyof typeof ScheduledMessageErrorReason];
51
+
52
+ export const ScheduledMessageBlockReason = {
53
+ Command: 'command',
54
+ SharedLocation: 'shared_location',
55
+ Unavailable: 'unavailable',
56
+ } as const;
57
+
58
+ export type ScheduledMessageBlockReason =
59
+ (typeof ScheduledMessageBlockReason)[keyof typeof ScheduledMessageBlockReason];
60
+
61
+ export const ScheduledMessageCompositionEndReason = {
62
+ Deleted: 'deleted',
63
+ Failed: 'failed',
64
+ Sent: 'sent',
65
+ } as const;
66
+
67
+ export type ScheduledMessageCompositionEndReason =
68
+ (typeof ScheduledMessageCompositionEndReason)[keyof typeof ScheduledMessageCompositionEndReason];
69
+
70
+ export const ScheduledMessageEventType = {
71
+ Created: 'scheduled_message.created',
72
+ Deleted: 'scheduled_message.deleted',
73
+ Failed: 'scheduled_message.failed',
74
+ Sent: 'scheduled_message.sent',
75
+ Updated: 'scheduled_message.updated',
76
+ } as const;
77
+
78
+ export type ScheduledMessageEventType =
79
+ (typeof ScheduledMessageEventType)[keyof typeof ScheduledMessageEventType];
@@ -0,0 +1,51 @@
1
+ import { formatMessage } from '../utils';
2
+ import { chatLoggerSystem } from '../logger';
3
+ import type { StreamChat } from '../client';
4
+ import type { LocalMessage, UserResponse } from '../types';
5
+
6
+ const logger = chatLoggerSystem.getLogger('message-composer');
7
+
8
+ export const resolveUsersByIds = async (
9
+ client: StreamChat,
10
+ userIds: string[] = [],
11
+ ): Promise<UserResponse[]> => {
12
+ const knownUsers = client.state.users;
13
+ const missingUserIds = userIds.filter((userId) => !knownUsers[userId]);
14
+ const fetchedUsers: Record<string, UserResponse> = {};
15
+
16
+ if (missingUserIds.length) {
17
+ try {
18
+ const { users } = await client.queryUsers({
19
+ payload: { filter_conditions: { id: { $in: missingUserIds } } },
20
+ });
21
+ users.forEach((user) => (fetchedUsers[user.id] = user));
22
+ } catch (error) {
23
+ logger.withExtraTags('resolveUsersByIds').error('Resolving the users failed.', {
24
+ error,
25
+ });
26
+ }
27
+ }
28
+
29
+ return userIds.map(
30
+ (userId) =>
31
+ knownUsers[userId] ?? fetchedUsers[userId] ?? ({ id: userId } as UserResponse),
32
+ );
33
+ };
34
+
35
+ export const resolveMessageById = async (
36
+ client: StreamChat,
37
+ id: string,
38
+ ): Promise<LocalMessage | null> => {
39
+ const storedMessage = client.messageStore.get(id);
40
+ if (storedMessage) return storedMessage;
41
+
42
+ try {
43
+ const { message } = await client.getMessage({ id });
44
+ return formatMessage(message);
45
+ } catch (error) {
46
+ logger.withExtraTags('resolveMessageById').error('Resolving the message failed.', {
47
+ error,
48
+ });
49
+ return null;
50
+ }
51
+ };
@@ -0,0 +1,45 @@
1
+ import { StreamAPIError } from '../types';
2
+ import { ScheduledMessageErrorReason } from './constants';
3
+
4
+ const NOT_FOUND_STATUS = 404;
5
+
6
+ const REASON_BY_ERROR_CODE: Record<number, ScheduledMessageErrorReason> = {
7
+ 114: ScheduledMessageErrorReason.Disabled,
8
+ 115: ScheduledMessageErrorReason.TooSoon,
9
+ 116: ScheduledMessageErrorReason.TooFar,
10
+ 117: ScheduledMessageErrorReason.ChannelLimit,
11
+ 118: ScheduledMessageErrorReason.UserLimit,
12
+ 119: ScheduledMessageErrorReason.IdTaken,
13
+ 120: ScheduledMessageErrorReason.NotEditable,
14
+ 121: ScheduledMessageErrorReason.Sending,
15
+ 122: ScheduledMessageErrorReason.Conflict,
16
+ 123: ScheduledMessageErrorReason.AlreadySent,
17
+ 124: ScheduledMessageErrorReason.Canceled,
18
+ };
19
+
20
+ const KNOWN_ERROR_REASONS = new Set<string>(Object.values(ScheduledMessageErrorReason));
21
+
22
+ const isKnownErrorReason = (reason?: string): reason is ScheduledMessageErrorReason =>
23
+ !!reason && KNOWN_ERROR_REASONS.has(reason);
24
+
25
+ const isStreamAPIError = (error: unknown): error is StreamAPIError =>
26
+ error instanceof StreamAPIError;
27
+
28
+ export const getScheduledMessageErrorReason = (
29
+ error: unknown,
30
+ ): ScheduledMessageErrorReason | undefined => {
31
+ if (!isStreamAPIError(error)) return;
32
+
33
+ const { code, response } = error;
34
+ const { exception_fields: exceptionFields = {} } = response?.data ?? {};
35
+ const { reason } = exceptionFields;
36
+
37
+ const reasonFromCode = code === undefined ? undefined : REASON_BY_ERROR_CODE[code];
38
+
39
+ const errorReason = isKnownErrorReason(reason) ? reason : reasonFromCode;
40
+
41
+ return errorReason;
42
+ };
43
+
44
+ export const isScheduledMessageNotFoundError = (error: unknown) =>
45
+ isStreamAPIError(error) && error.status === NOT_FOUND_STATUS;