stream-chat 10.0.0-rc.30 → 10.0.0-rc.32

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 (40) hide show
  1. package/dist/cjs/index.browser.js +248 -293
  2. package/dist/cjs/index.browser.js.map +3 -3
  3. package/dist/cjs/index.node.js +252 -293
  4. package/dist/cjs/index.node.js.map +3 -3
  5. package/dist/esm/index.mjs +248 -293
  6. package/dist/esm/index.mjs.map +3 -3
  7. package/dist/types/channel.d.ts +2 -1
  8. package/dist/types/channel_state.d.ts +5 -0
  9. package/dist/types/client.d.ts +0 -1
  10. package/dist/types/messageComposer/attachmentManager.d.ts +16 -3
  11. package/dist/types/messageComposer/middleware/messageComposer/commandInjection.d.ts +5 -0
  12. package/dist/types/messageComposer/middleware/messageComposer/index.d.ts +1 -0
  13. package/dist/types/messageComposer/middleware/messageComposer/userDataInjection.d.ts +5 -0
  14. package/dist/types/messageComposer/middleware/textComposer/commandUtils.d.ts +4 -0
  15. package/dist/types/messageComposer/textComposer.d.ts +5 -0
  16. package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +5 -1
  17. package/dist/types/offline-support/queueableOperations.d.ts +6 -0
  18. package/dist/types/types.d.ts +1 -7
  19. package/package.json +1 -1
  20. package/src/channel.ts +16 -40
  21. package/src/channel_state.ts +5 -0
  22. package/src/client.ts +9 -22
  23. package/src/messageComposer/attachmentManager.ts +46 -124
  24. package/src/messageComposer/messageComposer.ts +6 -1
  25. package/src/messageComposer/middleware/messageComposer/MessageComposerMiddlewareExecutor.ts +6 -0
  26. package/src/messageComposer/middleware/messageComposer/commandInjection.ts +10 -4
  27. package/src/messageComposer/middleware/messageComposer/customData.ts +14 -2
  28. package/src/messageComposer/middleware/messageComposer/index.ts +1 -0
  29. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +8 -1
  30. package/src/messageComposer/middleware/textComposer/TextComposerMiddlewareExecutor.ts +7 -0
  31. package/src/messageComposer/middleware/textComposer/commandUtils.ts +9 -1
  32. package/src/messageComposer/textComposer.ts +10 -0
  33. package/src/messageOperations/MessageOperationStatePolicy.ts +19 -8
  34. package/src/messageOperations/MessageOperations.ts +2 -2
  35. package/src/offline-support/offline_support_api.ts +5 -0
  36. package/src/offline-support/queueableOperations.ts +26 -0
  37. package/src/pagination/paginators/BasePaginator.ts +8 -3
  38. package/src/pagination/paginators/ChannelPaginator.ts +1 -4
  39. package/src/search/MessageSearchSource.ts +2 -1
  40. package/src/types.ts +0 -6
@@ -132,6 +132,7 @@ __export(src_exports, {
132
132
  ThreadPaginator: () => ThreadPaginator,
133
133
  TokenManager: () => TokenManager,
134
134
  UPDATE_LIVE_LOCATION_REQUEST_MIN_THROTTLE_TIMEOUT: () => UPDATE_LIVE_LOCATION_REQUEST_MIN_THROTTLE_TIMEOUT,
135
+ USER_DATA_INJECTION_MIDDLEWARE_ID: () => USER_DATA_INJECTION_MIDDLEWARE_ID,
135
136
  UploadManager: () => UploadManager,
136
137
  UserFromToken: () => UserFromToken,
137
138
  UserGroupPaginator: () => UserGroupPaginator,
@@ -148,6 +149,7 @@ __export(src_exports, {
148
149
  chatCodes: () => chatCodes,
149
150
  chatLoggerSystem: () => chatLoggerSystem,
150
151
  clampWSConnectionConfig: () => clampWSConnectionConfig,
152
+ commandTakesNoArguments: () => commandTakesNoArguments,
151
153
  convertTimestampToDate: () => convertTimestampToDate,
152
154
  createActiveCommandGuardMiddleware: () => createActiveCommandGuardMiddleware,
153
155
  createAttachmentsCompositionMiddleware: () => createAttachmentsCompositionMiddleware,
@@ -179,6 +181,7 @@ __export(src_exports, {
179
181
  createTextComposerPreValidationMiddleware: () => createTextComposerPreValidationMiddleware,
180
182
  createUploadConfigCheckMiddleware: () => createUploadConfigCheckMiddleware,
181
183
  createUploadErrorHandlerMiddleware: () => createUploadErrorHandlerMiddleware,
184
+ createUserDataInjectionMiddleware: () => createUserDataInjectionMiddleware,
182
185
  createWSConnectionNetworkStatusReporter: () => createWSConnectionNetworkStatusReporter,
183
186
  dateToNs: () => dateToNs,
184
187
  defaultCommandSendabilityValidator: () => defaultCommandSendabilityValidator,
@@ -262,6 +265,7 @@ __export(src_exports, {
262
265
  stripCommandFromText: () => stripCommandFromText,
263
266
  stripMentionTokens: () => stripMentionTokens,
264
267
  textIsEmpty: () => textIsEmpty,
268
+ textStartsWithCommand: () => textStartsWithCommand,
265
269
  timeLeftMs: () => timeLeftMs,
266
270
  withCancellation: () => withCancellation,
267
271
  withoutConcurrency: () => withoutConcurrency
@@ -2837,6 +2841,8 @@ var initState2 = ({
2837
2841
  };
2838
2842
  })
2839
2843
  });
2844
+ var isUploadInputAttachment = (input) => "localMetadata" in input;
2845
+ var toUploadError = (rejection) => rejection instanceof Error || isUploadCancellation(rejection) ? rejection : new Error("unknown error", { cause: rejection });
2840
2846
  var _AttachmentManager = class _AttachmentManager {
2841
2847
  constructor({ composer, message }) {
2842
2848
  this.setCustomUploadFn = (doUploadRequest) => {
@@ -3025,7 +3031,11 @@ var _AttachmentManager = class _AttachmentManager {
3025
3031
  localAttachment.localMetadata.uploadState = uploadPermissionCheck.uploadBlocked ? "blocked" : "pending";
3026
3032
  return localAttachment;
3027
3033
  };
3028
- this.ensureLocalUploadAttachment = async (attachment) => {
3034
+ /**
3035
+ * Whether `attachment` carries what an upload needs: a file and a local id. Reports the missing one
3036
+ * as an error notification.
3037
+ */
3038
+ this.isUploadableOrNotify = (attachment) => {
3029
3039
  if (!attachment.localMetadata?.file) {
3030
3040
  this.client.notifications.addError({
3031
3041
  message: "File is required for upload attachment",
@@ -3035,7 +3045,7 @@ var _AttachmentManager = class _AttachmentManager {
3035
3045
  },
3036
3046
  options: { type: CORE_NOTIFICATION_TYPE.attachmentFileMissing }
3037
3047
  });
3038
- return;
3048
+ return false;
3039
3049
  }
3040
3050
  if (!attachment.localMetadata.id) {
3041
3051
  this.client.notifications.addError({
@@ -3046,16 +3056,9 @@ var _AttachmentManager = class _AttachmentManager {
3046
3056
  },
3047
3057
  options: { type: CORE_NOTIFICATION_TYPE.attachmentIdMissing }
3048
3058
  });
3049
- return;
3050
- }
3051
- if (!this.fileUploadFilter(attachment)) return;
3052
- const newAttachment = await this.fileToLocalUploadAttachment(
3053
- attachment.localMetadata.file
3054
- );
3055
- if (attachment.localMetadata.id) {
3056
- newAttachment.localMetadata.id = attachment.localMetadata.id;
3059
+ return false;
3057
3060
  }
3058
- return newAttachment;
3061
+ return true;
3059
3062
  };
3060
3063
  /** The default upload, skipping the custom `doUploadRequest` so a custom one can delegate here. */
3061
3064
  this.doDefaultUploadRequest = async (fileLike, options) => {
@@ -3096,99 +3099,27 @@ var _AttachmentManager = class _AttachmentManager {
3096
3099
  }
3097
3100
  return this.doDefaultUploadRequest(fileLike, options);
3098
3101
  };
3099
- // @deprecated use attachmentManager.uploadFile(file)
3100
- this.uploadAttachment = async (attachment) => {
3101
- if (!this.isUploadEnabled) return;
3102
- const localAttachment = await this.ensureLocalUploadAttachment(attachment);
3103
- if (typeof localAttachment === "undefined") return;
3104
- if (localAttachment.localMetadata.uploadState === "blocked") {
3105
- this.upsertAttachments([localAttachment]);
3106
- this.client.notifications.addError({
3107
- message: `The attachment upload was blocked`,
3108
- origin: {
3109
- emitter: "AttachmentManager",
3110
- context: {
3111
- attachment,
3112
- blockedAttachment: localAttachment,
3113
- composer: this.composer
3114
- }
3115
- },
3116
- options: {
3117
- type: CORE_NOTIFICATION_TYPE.attachmentUploadBlocked,
3118
- metadata: {
3119
- reason: localAttachment.localMetadata.uploadPermissionCheck?.reason
3120
- }
3121
- }
3122
- });
3123
- return localAttachment;
3124
- }
3125
- let response;
3126
- try {
3127
- response = await this.upload(attachment);
3128
- } catch (error) {
3129
- const reason = error instanceof Error ? error.message : "unknown error";
3130
- const failedAttachment = {
3131
- ...attachment,
3132
- localMetadata: {
3133
- ...attachment.localMetadata,
3134
- uploadState: "failed",
3135
- uploadProgress: void 0,
3136
- // `false`, not `undefined`: `mergeWith` skips `undefined`, which would leave a stale `true`.
3137
- uploadConfirmationPending: false
3138
- }
3139
- };
3140
- if (!isUploadCancellation(error)) {
3141
- this.client.notifications.addError({
3142
- message: "Error uploading attachment",
3143
- origin: {
3144
- emitter: "AttachmentManager",
3145
- context: { attachment, failedAttachment, composer: this.composer }
3146
- },
3147
- options: {
3148
- type: CORE_NOTIFICATION_TYPE.attachmentUploadFailed,
3149
- metadata: { reason },
3150
- originalError: error instanceof Error ? error : void 0
3151
- }
3152
- });
3153
- }
3154
- this.updateAttachment(failedAttachment);
3155
- return failedAttachment;
3156
- }
3157
- if (!response) {
3158
- this.removeAttachments([attachment.localMetadata.id]);
3159
- return;
3160
- }
3161
- const uploadedAttachment = {
3162
- ...attachment,
3163
- localMetadata: {
3164
- ...attachment.localMetadata,
3165
- uploadState: "finished",
3166
- uploadProgress: void 0,
3167
- uploadConfirmationPending: false
3168
- }
3169
- };
3170
- const previewUri = uploadedAttachment.localMetadata.previewUri;
3171
- if (previewUri) {
3172
- if (previewUri.startsWith("blob:")) URL.revokeObjectURL(previewUri);
3173
- delete uploadedAttachment.localMetadata.previewUri;
3174
- }
3175
- if (isLocalImageAttachment(uploadedAttachment)) {
3176
- uploadedAttachment.image_url = response.file;
3102
+ /**
3103
+ * Uploads a file, or an existing local attachment, through the pre- and post-upload middleware.
3104
+ *
3105
+ * A file becomes a new attachment. An attachment keeps its `localMetadata.id`, its fields and its
3106
+ * position in `attachments`: a failed upload is retried in place, and an attachment the caller built
3107
+ * is uploaded with its own fields. An attachment without a file or a local id is returned unchanged,
3108
+ * with an error notification.
3109
+ *
3110
+ * Unlike {@link uploadFiles}, it does not check {@link isUploadEnabled}.
3111
+ */
3112
+ this.uploadFile = async (fileOrAttachment) => {
3113
+ let initialAttachment;
3114
+ if (isUploadInputAttachment(fileOrAttachment)) {
3115
+ if (!this.isUploadableOrNotify(fileOrAttachment)) return fileOrAttachment;
3116
+ initialAttachment = fileOrAttachment;
3177
3117
  } else {
3178
- uploadedAttachment.asset_url = response.file;
3179
- }
3180
- if (response.thumb_url) {
3181
- uploadedAttachment.thumb_url = response.thumb_url;
3118
+ initialAttachment = _AttachmentManager.toLocalUploadAttachment(fileOrAttachment);
3182
3119
  }
3183
- this.updateAttachment(uploadedAttachment);
3184
- return uploadedAttachment;
3185
- };
3186
- this.uploadFile = async (file) => {
3187
3120
  const preUpload = await this.preUploadMiddlewareExecutor.execute({
3188
3121
  eventName: "prepare",
3189
- initialValue: {
3190
- attachment: _AttachmentManager.toLocalUploadAttachment(file)
3191
- },
3122
+ initialValue: { attachment: initialAttachment },
3192
3123
  mode: "concurrent"
3193
3124
  });
3194
3125
  const attachment = preUpload.state.attachment;
@@ -3218,7 +3149,7 @@ var _AttachmentManager = class _AttachmentManager {
3218
3149
  try {
3219
3150
  response = await this.upload(attachment);
3220
3151
  } catch (err) {
3221
- error = err instanceof Error ? err : void 0;
3152
+ error = toUploadError(err);
3222
3153
  }
3223
3154
  const postUpload = await this.postUploadMiddlewareExecutor.execute({
3224
3155
  eventName: "postProcess",
@@ -3567,6 +3498,8 @@ var createCompositionDataCleanupMiddleware = (composer) => ({
3567
3498
  });
3568
3499
 
3569
3500
  // src/messageComposer/middleware/messageComposer/customData.ts
3501
+ var hasFields = (data) => !!data && Object.keys(data).length > 0;
3502
+ var editClearsCustomData = (composer) => hasFields(composer.editedMessage?.custom) && !hasFields(composer.customDataManager.customMessageData);
3570
3503
  var createCustomDataCompositionMiddleware = (composer) => ({
3571
3504
  id: "stream-io/message-composer-middleware/custom-data",
3572
3505
  handlers: {
@@ -3576,7 +3509,7 @@ var createCustomDataCompositionMiddleware = (composer) => ({
3576
3509
  forward
3577
3510
  }) => {
3578
3511
  const data = composer.customDataManager.customMessageData;
3579
- if (!data || !Object.keys(data).length) return forward();
3512
+ if (!hasFields(data) && !editClearsCustomData(composer)) return forward();
3580
3513
  return next({
3581
3514
  ...state,
3582
3515
  localMessage: {
@@ -3600,7 +3533,7 @@ var createDraftCustomDataCompositionMiddleware = (composer) => ({
3600
3533
  forward
3601
3534
  }) => {
3602
3535
  const data = composer.customDataManager.customMessageData;
3603
- if (!data || !Object.keys(data).length) return forward();
3536
+ if (!hasFields(data)) return forward();
3604
3537
  return next({
3605
3538
  ...state,
3606
3539
  draft: {
@@ -3635,6 +3568,80 @@ var userSuggestionToUserResponse = (suggestion) => {
3635
3568
  };
3636
3569
  var userSuggestionToMentionEntity = (suggestion) => userResponseToMentionEntity(userSuggestionToUserResponse(suggestion));
3637
3570
 
3571
+ // src/messageComposer/middleware/textComposer/commandUtils.ts
3572
+ function escapeCommandRegExp(text) {
3573
+ return text.replace(/[-[\]{}()*+?.,/\\^$|#]/g, "\\$&");
3574
+ }
3575
+ var getRawCommandName = (text) => text?.match(/^\/(\S+)(?:\s.*)?$/)?.[1];
3576
+ var getCompleteCommandInString = (text) => {
3577
+ const match = text.match(/^\/(\S+)\s+.*/);
3578
+ const commandName = match && match[1];
3579
+ return commandName;
3580
+ };
3581
+ var stripCommandFromText = (text, commandName) => text.replace(new RegExp(`^${escapeCommandRegExp(`/${commandName}`)}\\s*`, "i"), "");
3582
+ var textStartsWithCommand = (text, commandName) => new RegExp(`^${escapeCommandRegExp(`/${commandName}`)}(\\s|$)`, "i").test(text);
3583
+ var commandTakesNoArguments = (command) => !command.args?.trim();
3584
+ var stripMentionTokens = (text, mentionedUsersInText, trigger = "@") => mentionedUsersInText.reduce((value, user) => {
3585
+ let next = value.replace(`${trigger}${user.id}`, "");
3586
+ if (user.name) {
3587
+ next = next.replace(`${trigger}${user.name}`, "");
3588
+ }
3589
+ return next.trim();
3590
+ }, text.trim());
3591
+ var getMentionedUsersInText = (text, mentionedUsers) => Array.from(
3592
+ new Set(
3593
+ mentionedUsers.filter(
3594
+ ({ id, name }) => text.includes(`@${id}`) || !!name && text.includes(`@${name}`)
3595
+ )
3596
+ )
3597
+ );
3598
+ var getCommandByName = (searchSource, commandName) => {
3599
+ if (!commandName) return;
3600
+ const normalizedCommandName = commandName.toLowerCase();
3601
+ return searchSource.query(normalizedCommandName).items.find((command) => command.name?.toLowerCase() === normalizedCommandName);
3602
+ };
3603
+ var notifyCommandDisabled = (composer, command) => {
3604
+ const disabledReason = composer.getCommandDisabledReason(command);
3605
+ if (!disabledReason) return;
3606
+ composer.client.notifications.addWarning({
3607
+ message: disabledReason === "editing" ? "Command not available while editing" : "Command not available while replying",
3608
+ origin: {
3609
+ emitter: "MessageComposer",
3610
+ context: { command, composer }
3611
+ },
3612
+ options: {
3613
+ type: CORE_NOTIFICATION_TYPE.commandDisabled,
3614
+ metadata: {
3615
+ command: command.name,
3616
+ reason: disabledReason
3617
+ }
3618
+ }
3619
+ });
3620
+ return true;
3621
+ };
3622
+ var notifyCommandNotReady = ({
3623
+ composer,
3624
+ sendability
3625
+ }) => {
3626
+ if (sendability.ready) return;
3627
+ composer.client.notifications.addWarning({
3628
+ message: "Command not ready to be sent",
3629
+ origin: {
3630
+ emitter: "MessageComposer",
3631
+ context: { command: sendability.command, composer }
3632
+ },
3633
+ options: {
3634
+ type: CORE_NOTIFICATION_TYPE.commandNotReady,
3635
+ metadata: {
3636
+ command: sendability.command.name,
3637
+ ...sendability.reason ? { reason: sendability.reason } : {},
3638
+ ...sendability.metadata ?? {}
3639
+ }
3640
+ }
3641
+ });
3642
+ return true;
3643
+ };
3644
+
3638
3645
  // src/messageComposer/textComposer.ts
3639
3646
  var textIsEmpty = (text) => {
3640
3647
  const trimmedText = text.trim();
@@ -3987,6 +3994,14 @@ var TextComposer = class {
3987
3994
  get textIsEmpty() {
3988
3995
  return textIsEmpty(this.text);
3989
3996
  }
3997
+ /**
3998
+ * Whether the active command is content on its own: a command that takes no arguments is sent as
3999
+ * `/shrug` with no text. A command that takes arguments still needs text.
4000
+ */
4001
+ get activeCommandIsContent() {
4002
+ const { command } = this;
4003
+ return !!command && commandTakesNoArguments(command);
4004
+ }
3990
4005
  setMentionedUsers(users) {
3991
4006
  const nonUserMentions = this.mentions.filter(
3992
4007
  (entity) => !isUserMentionEntity(entity)
@@ -7105,7 +7120,7 @@ var BasePaginator = class {
7105
7120
  if (interval && updateState) {
7106
7121
  this.setActiveInterval(interval, { updateState: false });
7107
7122
  stateUpdate.items = this.intervalToItems(interval);
7108
- } else if (updateState && !items.length && (keepPreviousItems || !isFirstPage)) {
7123
+ } else if (updateState && !filteredItems.length && (keepPreviousItems || !isFirstPage)) {
7109
7124
  stateUpdate.items = this.items;
7110
7125
  }
7111
7126
  const continuesActiveIntervalFlags = !isSeparateInterval || !!interval && this.isActiveInterval(interval);
@@ -7514,11 +7529,7 @@ var ChannelPaginator = class extends BasePaginator {
7514
7529
  }
7515
7530
  return this.client.hydrateChannels(
7516
7531
  cachedQuery.channels,
7517
- {
7518
- offlineMode: true,
7519
- skipInitialization: []
7520
- // an empty array clears existing channel messages (no duplicates)
7521
- },
7532
+ { offlineMode: true },
7522
7533
  request
7523
7534
  );
7524
7535
  }
@@ -10905,7 +10916,7 @@ var MessageSearchSource = class extends BaseSearchSource {
10905
10916
  initialFilterConfig: {
10906
10917
  text: {
10907
10918
  enabled: true,
10908
- generate: ({ searchQuery }) => searchQuery ? { text: searchQuery } : null
10919
+ generate: ({ searchQuery }) => searchQuery ? { text: { $autocomplete: searchQuery } } : null
10909
10920
  },
10910
10921
  ...filterBuilderOptions?.messageSearch?.initialFilterConfig
10911
10922
  }
@@ -11032,78 +11043,6 @@ var MessageSearchSource = class extends BaseSearchSource {
11032
11043
  }
11033
11044
  };
11034
11045
 
11035
- // src/messageComposer/middleware/textComposer/commandUtils.ts
11036
- function escapeCommandRegExp(text) {
11037
- return text.replace(/[-[\]{}()*+?.,/\\^$|#]/g, "\\$&");
11038
- }
11039
- var getRawCommandName = (text) => text?.match(/^\/(\S+)(?:\s.*)?$/)?.[1];
11040
- var getCompleteCommandInString = (text) => {
11041
- const match = text.match(/^\/(\S+)\s+.*/);
11042
- const commandName = match && match[1];
11043
- return commandName;
11044
- };
11045
- var stripCommandFromText = (text, commandName) => text.replace(new RegExp(`^${escapeCommandRegExp(`/${commandName}`)}\\s*`), "");
11046
- var stripMentionTokens = (text, mentionedUsersInText, trigger = "@") => mentionedUsersInText.reduce((value, user) => {
11047
- let next = value.replace(`${trigger}${user.id}`, "");
11048
- if (user.name) {
11049
- next = next.replace(`${trigger}${user.name}`, "");
11050
- }
11051
- return next.trim();
11052
- }, text.trim());
11053
- var getMentionedUsersInText = (text, mentionedUsers) => Array.from(
11054
- new Set(
11055
- mentionedUsers.filter(
11056
- ({ id, name }) => text.includes(`@${id}`) || !!name && text.includes(`@${name}`)
11057
- )
11058
- )
11059
- );
11060
- var getCommandByName = (searchSource, commandName) => {
11061
- if (!commandName) return;
11062
- const normalizedCommandName = commandName.toLowerCase();
11063
- return searchSource.query(normalizedCommandName).items.find((command) => command.name?.toLowerCase() === normalizedCommandName);
11064
- };
11065
- var notifyCommandDisabled = (composer, command) => {
11066
- const disabledReason = composer.getCommandDisabledReason(command);
11067
- if (!disabledReason) return;
11068
- composer.client.notifications.addWarning({
11069
- message: disabledReason === "editing" ? "Command not available while editing" : "Command not available while replying",
11070
- origin: {
11071
- emitter: "MessageComposer",
11072
- context: { command, composer }
11073
- },
11074
- options: {
11075
- type: CORE_NOTIFICATION_TYPE.commandDisabled,
11076
- metadata: {
11077
- command: command.name,
11078
- reason: disabledReason
11079
- }
11080
- }
11081
- });
11082
- return true;
11083
- };
11084
- var notifyCommandNotReady = ({
11085
- composer,
11086
- sendability
11087
- }) => {
11088
- if (sendability.ready) return;
11089
- composer.client.notifications.addWarning({
11090
- message: "Command not ready to be sent",
11091
- origin: {
11092
- emitter: "MessageComposer",
11093
- context: { command: sendability.command, composer }
11094
- },
11095
- options: {
11096
- type: CORE_NOTIFICATION_TYPE.commandNotReady,
11097
- metadata: {
11098
- command: sendability.command.name,
11099
- ...sendability.reason ? { reason: sendability.reason } : {},
11100
- ...sendability.metadata ?? {}
11101
- }
11102
- }
11103
- });
11104
- return true;
11105
- };
11106
-
11107
11046
  // src/messageComposer/middleware/textComposer/textMiddlewareUtils.ts
11108
11047
  var getTriggerCharWithToken = ({
11109
11048
  trigger,
@@ -11635,9 +11574,66 @@ var createDraftMessageComposerStateCompositionMiddleware = (composer) => ({
11635
11574
  }
11636
11575
  });
11637
11576
 
11577
+ // src/messageComposer/middleware/messageComposer/commandInjection.ts
11578
+ var createCommandInjectionMiddleware = (composer) => ({
11579
+ handlers: {
11580
+ compose: ({
11581
+ forward,
11582
+ next,
11583
+ state
11584
+ }) => {
11585
+ const command = composer.textComposer.command;
11586
+ const { text } = state.localMessage;
11587
+ if (!command || textStartsWithCommand(text, command.name)) {
11588
+ return forward();
11589
+ }
11590
+ const injection = `/${command?.name}`;
11591
+ const enrichedText = `${injection} ${text}`;
11592
+ return next({
11593
+ ...state,
11594
+ localMessage: {
11595
+ ...state.localMessage,
11596
+ text: enrichedText
11597
+ },
11598
+ message: {
11599
+ ...state.message,
11600
+ text: enrichedText
11601
+ }
11602
+ });
11603
+ }
11604
+ },
11605
+ id: "stream-io/message-composer-middleware/command-string-injection"
11606
+ });
11607
+ var createDraftCommandInjectionMiddleware = (composer) => ({
11608
+ handlers: {
11609
+ compose: ({
11610
+ forward,
11611
+ next,
11612
+ state
11613
+ }) => {
11614
+ const command = composer.textComposer.command;
11615
+ const { text } = state.draft;
11616
+ if (!command || textStartsWithCommand(text ?? "", command.name)) {
11617
+ return forward();
11618
+ }
11619
+ const injection = `/${command?.name}`;
11620
+ const enrichedText = `${injection} ${text}`;
11621
+ return next({
11622
+ ...state,
11623
+ draft: {
11624
+ ...state.draft,
11625
+ text: enrichedText
11626
+ }
11627
+ });
11628
+ }
11629
+ },
11630
+ id: "stream-io/message-composer-middleware/draft-command-string-injection"
11631
+ });
11632
+
11638
11633
  // src/messageComposer/middleware/messageComposer/userDataInjection.ts
11634
+ var USER_DATA_INJECTION_MIDDLEWARE_ID = "stream-io/message-composer-middleware/user-data-injection";
11639
11635
  var createUserDataInjectionMiddleware = (composer) => ({
11640
- id: "stream-io/message-composer-middleware/user-data-injection",
11636
+ id: USER_DATA_INJECTION_MIDDLEWARE_ID,
11641
11637
  handlers: {
11642
11638
  compose: ({
11643
11639
  state,
@@ -11753,6 +11749,7 @@ var MessageComposerMiddlewareExecutor = class extends MiddlewareExecutor {
11753
11749
  createPollOnlyCompositionMiddleware(composer),
11754
11750
  createTextComposerCompositionMiddleware(composer),
11755
11751
  createAttachmentsCompositionMiddleware(composer),
11752
+ createCommandInjectionMiddleware(composer),
11756
11753
  createLinkPreviewsCompositionMiddleware(composer),
11757
11754
  createSharedLocationCompositionMiddleware(composer),
11758
11755
  createMessageComposerStateCompositionMiddleware(composer),
@@ -11768,6 +11765,7 @@ var MessageDraftComposerMiddlewareExecutor = class extends MiddlewareExecutor {
11768
11765
  this.use([
11769
11766
  createDraftTextComposerCompositionMiddleware(composer),
11770
11767
  createDraftAttachmentsCompositionMiddleware(composer),
11768
+ createDraftCommandInjectionMiddleware(composer),
11771
11769
  createDraftLinkPreviewsCompositionMiddleware(composer),
11772
11770
  createDraftMessageComposerStateCompositionMiddleware(composer),
11773
11771
  createDraftCustomDataCompositionMiddleware(composer),
@@ -11776,62 +11774,6 @@ var MessageDraftComposerMiddlewareExecutor = class extends MiddlewareExecutor {
11776
11774
  }
11777
11775
  };
11778
11776
 
11779
- // src/messageComposer/middleware/messageComposer/commandInjection.ts
11780
- var createCommandInjectionMiddleware = (composer) => ({
11781
- handlers: {
11782
- compose: ({
11783
- forward,
11784
- next,
11785
- state
11786
- }) => {
11787
- const command = composer.textComposer.command;
11788
- if (!command) {
11789
- return forward();
11790
- }
11791
- const { text } = state.localMessage;
11792
- const injection = `/${command?.name}`;
11793
- const enrichedText = `${injection} ${text}`;
11794
- return next({
11795
- ...state,
11796
- localMessage: {
11797
- ...state.localMessage,
11798
- text: enrichedText
11799
- },
11800
- message: {
11801
- ...state.message,
11802
- text: enrichedText
11803
- }
11804
- });
11805
- }
11806
- },
11807
- id: "stream-io/message-composer-middleware/command-string-injection"
11808
- });
11809
- var createDraftCommandInjectionMiddleware = (composer) => ({
11810
- handlers: {
11811
- compose: ({
11812
- forward,
11813
- next,
11814
- state
11815
- }) => {
11816
- const command = composer.textComposer.command;
11817
- if (!command) {
11818
- return forward();
11819
- }
11820
- const { text } = state.draft;
11821
- const injection = `/${command?.name}`;
11822
- const enrichedText = `${injection} ${text}`;
11823
- return next({
11824
- ...state,
11825
- draft: {
11826
- ...state.draft,
11827
- text: enrichedText
11828
- }
11829
- });
11830
- }
11831
- },
11832
- id: "stream-io/message-composer-middleware/draft-command-string-injection"
11833
- });
11834
-
11835
11777
  // src/messageComposer/middleware/pollComposer/validation.ts
11836
11778
  var POLL_COMPOSER_VALIDATION_CODE = {
11837
11779
  maxVotesNotNumeric: "validation:poll:maxVotes:notNumeric",
@@ -12833,9 +12775,14 @@ var TextComposerMiddlewareExecutor = class extends MiddlewareExecutor {
12833
12775
  this.use([
12834
12776
  createTextComposerPreValidationMiddleware(composer),
12835
12777
  createMentionsMiddleware(composer.channel),
12778
+ // While a command is active, the guard stops the commands middleware from suggesting or
12779
+ // activating another one. The extraction moves the active command out of the text, which
12780
+ // the command injection composition middleware puts back in front of the sent text.
12781
+ createActiveCommandGuardMiddleware(),
12836
12782
  createCommandsMiddleware(composer.channel, {
12837
12783
  composer
12838
12784
  }),
12785
+ createCommandStringExtractionMiddleware(),
12839
12786
  createCommandEffectsMiddleware()
12840
12787
  ]);
12841
12788
  }
@@ -13745,6 +13692,22 @@ var QUEUEABLE_OPERATIONS = {
13745
13692
  }
13746
13693
  channelOf(client, task).messagePaginator.trackLatestMessage(formatMessage(message));
13747
13694
  },
13695
+ // the server has the message, meaning an earlier attempt landed but its response was lost
13696
+ onReplayRejected: ({ client, error, task }) => {
13697
+ const store = client.messageStore;
13698
+ const held = store.get(task.messageId);
13699
+ if (held?.status === "failed" && isAlreadyExistsError(error, parseError(error))) {
13700
+ const received = { ...held, error: void 0, status: "received" };
13701
+ store.upsert(received);
13702
+ store.flushSubscribers(received.id);
13703
+ client.offlineDb?.executeQuerySafely(
13704
+ (db) => db.upsertMessageWithChannelGuard({
13705
+ message: { ...received, cid: `${task.channelType}:${task.channelId}` }
13706
+ }),
13707
+ { method: "sendMessage:replayRejected" }
13708
+ );
13709
+ }
13710
+ },
13748
13711
  run: ({ channel, client, task }) => channelOf(client, task, channel).sendMessage(...task.payload)
13749
13712
  },
13750
13713
  "send-reaction": {
@@ -14745,6 +14708,10 @@ var MessageOperationStatePolicy = class {
14745
14708
  }
14746
14709
  return unhandledKind(kind);
14747
14710
  }
14711
+ /**
14712
+ * Records a failed request. Resolves `true` when the error shows the request took effect on the
14713
+ * server, so the operation succeeded after all.
14714
+ */
14748
14715
  async failure({
14749
14716
  error,
14750
14717
  kind,
@@ -14754,23 +14721,27 @@ var MessageOperationStatePolicy = class {
14754
14721
  options
14755
14722
  }) {
14756
14723
  const parsed = parseError(error);
14757
- if (isAlreadyExistsError(error, parsed)) {
14724
+ if ((kind === "send" || kind === "retry") && isAlreadyExistsError(error, parsed)) {
14758
14725
  const existing = this.ctx.get(messageId);
14759
14726
  if (existing?.status === "sending") {
14760
- const received = { ...localMessage, status: "received" };
14727
+ const received = {
14728
+ ...localMessage,
14729
+ error: void 0,
14730
+ status: "received"
14731
+ };
14761
14732
  this.ctx.ingest(received);
14762
14733
  this.ctx.persist(received);
14763
14734
  }
14764
- return;
14735
+ return true;
14765
14736
  }
14766
14737
  const pendingTaskTypes = PENDING_WHEN_QUEUED[kind];
14767
14738
  const queued = pendingTaskTypes.length > 0 && await this.ctx.isQueued(messageId, pendingTaskTypes);
14768
14739
  if (kind === "delete") {
14769
14740
  if (!queued) this.revertDelete({ messageId, optimistic, options });
14770
- return;
14741
+ return false;
14771
14742
  }
14772
14743
  if (kind === "update") {
14773
- if (queued) return;
14744
+ if (queued) return false;
14774
14745
  const failed = {
14775
14746
  ...this.ctx.get(messageId) ?? localMessage,
14776
14747
  error: parsed,
@@ -14778,13 +14749,14 @@ var MessageOperationStatePolicy = class {
14778
14749
  };
14779
14750
  this.ctx.ingest(failed);
14780
14751
  this.ctx.persist(failed);
14781
- return;
14752
+ return false;
14782
14753
  }
14783
14754
  if (kind === "send" || kind === "retry") {
14755
+ if (this.ctx.get(messageId)?.status === "received") return true;
14784
14756
  const failed = { ...localMessage, error: parsed, status: "failed" };
14785
14757
  this.ctx.ingest(failed);
14786
14758
  this.ctx.persist(failed);
14787
- return;
14759
+ return false;
14788
14760
  }
14789
14761
  return unhandledKind(kind);
14790
14762
  }
@@ -14912,7 +14884,7 @@ var MessageOperations = class {
14912
14884
  options: params.options
14913
14885
  });
14914
14886
  } catch (e) {
14915
- await this.policy.failure({
14887
+ const succeeded = await this.policy.failure({
14916
14888
  error: e,
14917
14889
  kind,
14918
14890
  localMessage: effective.localMessage,
@@ -14920,7 +14892,7 @@ var MessageOperations = class {
14920
14892
  optimistic,
14921
14893
  options: params.options
14922
14894
  });
14923
- throw e;
14895
+ if (!succeeded) throw e;
14924
14896
  }
14925
14897
  }
14926
14898
  /*
@@ -16066,18 +16038,7 @@ var Channel = class extends ChannelApi {
16066
16038
  */
16067
16039
  async updatePartial(update, requestOptions) {
16068
16040
  const data = await this.updateChannelPartial(update, requestOptions);
16069
- const channel = data.channel;
16070
- const currentCapabilities = this.data?.own_capabilities ?? [];
16071
- const newCapabilities = channel?.own_capabilities;
16072
- const capabilitiesChanged = newCapabilities && [...currentCapabilities].sort().join() !== [...newCapabilities].sort().join();
16073
- this.data = channel;
16074
- if (capabilitiesChanged) {
16075
- this.getClient().dispatchEvent({
16076
- type: "capabilities.changed",
16077
- cid: this.cid,
16078
- own_capabilities: newCapabilities
16079
- });
16080
- }
16041
+ this.data = data.channel;
16081
16042
  return data;
16082
16043
  }
16083
16044
  /**
@@ -16574,13 +16535,18 @@ var Channel = class extends ChannelApi {
16574
16535
  * Reads `state.data`. Assigning publishes `data`, `memberCount` and `ownCapabilities` in one update.
16575
16536
  * If the object omits `member_count` or `own_capabilities`, the last known values are carried onto
16576
16537
  * a copy (the assigned object is not changed). Editing `channel.data.x` in place does not reach
16577
- * the state.
16538
+ * the state. `ownCapabilities` keeps its array while the capabilities stay the same (in any
16539
+ * order), so a subscriber to it is notified only when they change.
16578
16540
  */
16579
16541
  get data() {
16580
16542
  return this.state.getLatestValue().data;
16581
16543
  }
16582
16544
  set data(next) {
16583
- const previous = this.state.getLatestValue().data;
16545
+ const {
16546
+ data: previous,
16547
+ memberCount: previousMemberCount,
16548
+ ownCapabilities: previousOwnCapabilities
16549
+ } = this.state.getLatestValue();
16584
16550
  const carriedMemberCount = typeof next?.member_count !== "number" && typeof previous?.member_count === "number" ? previous.member_count : void 0;
16585
16551
  const carriedCapabilities = !Array.isArray(next?.own_capabilities) && Array.isArray(previous?.own_capabilities) ? [...previous.own_capabilities] : void 0;
16586
16552
  const data = next && (carriedMemberCount !== void 0 || carriedCapabilities) ? {
@@ -16589,11 +16555,13 @@ var Channel = class extends ChannelApi {
16589
16555
  ...carriedCapabilities && { own_capabilities: carriedCapabilities }
16590
16556
  } : next;
16591
16557
  const memberCount = data?.member_count ?? carriedMemberCount;
16592
- const ownCapabilities = data?.own_capabilities ?? carriedCapabilities;
16558
+ const ownCapabilities = data?.own_capabilities ?? carriedCapabilities ?? [];
16559
+ const toKey = (capabilities) => [...capabilities].sort().join();
16560
+ const haveSameOwnCapabilities = toKey(previousOwnCapabilities) === toKey(ownCapabilities);
16593
16561
  this.state.partialNext({
16594
16562
  data,
16595
- memberCount: memberCount ?? this.state.getLatestValue().memberCount,
16596
- ownCapabilities: ownCapabilities ? [...ownCapabilities] : []
16563
+ memberCount: memberCount ?? previousMemberCount,
16564
+ ownCapabilities: haveSameOwnCapabilities ? previousOwnCapabilities : [...ownCapabilities]
16597
16565
  });
16598
16566
  }
16599
16567
  /**
@@ -17077,18 +17045,8 @@ var Channel = class extends ChannelApi {
17077
17045
  this.getClient().polls.hydratePollCache(state.messages, true);
17078
17046
  this.getClient().reminders.hydrateState(state.messages);
17079
17047
  this.messageComposer.initStateFromChannelResponse(state);
17080
- const areCapabilitiesChanged = [...channel.own_capabilities || []].sort().join() !== [
17081
- ...this.data && Array.isArray(this.data?.own_capabilities) ? this.data.own_capabilities : []
17082
- ].sort().join();
17083
17048
  this.data = channel;
17084
17049
  this.state.partialNext({ initialized: true, offlineMode: false });
17085
- if (areCapabilitiesChanged) {
17086
- this.getClient().dispatchEvent({
17087
- type: "capabilities.changed",
17088
- cid: this.cid,
17089
- own_capabilities: channel.own_capabilities ?? []
17090
- });
17091
- }
17092
17050
  this.getClient().dispatchEvent({
17093
17051
  type: "channels.queried",
17094
17052
  queriedChannels: {
@@ -18093,8 +18051,10 @@ var _MessageComposer = class _MessageComposer extends WithSubscriptions {
18093
18051
  }
18094
18052
  this.clear();
18095
18053
  }).unsubscribe;
18054
+ // The command is selected too: an active command that takes no arguments is content, so clearing
18055
+ // one can empty the composition without changing the text.
18096
18056
  this.subscribeTextComposerStateChanged = () => this.textComposer.state.subscribeWithSelector(
18097
- ({ text }) => [text],
18057
+ ({ command, text }) => [text, command],
18098
18058
  ([currentText], previousSelection) => {
18099
18059
  if (typeof previousSelection === "undefined") return;
18100
18060
  this.logStateUpdateTimestamp();
@@ -18590,15 +18550,15 @@ var _MessageComposer = class _MessageComposer extends WithSubscriptions {
18590
18550
  const hasSendableAttachment = this.attachmentManager.attachments.some(
18591
18551
  (attachment) => isFinishedUpload(attachment) || isPendingUpload(attachment) || isFailedUpload(attachment)
18592
18552
  );
18593
- return !!(!this.textComposer.textIsEmpty || hasSendableAttachment || this.pollId || this.locationComposer.validLocation);
18553
+ return !!(!this.textComposer.textIsEmpty || this.textComposer.activeCommandIsContent || hasSendableAttachment || this.pollId || this.locationComposer.validLocation);
18594
18554
  }
18595
- return !!(!this.attachmentManager.uploadsInProgressCount && (!this.textComposer.textIsEmpty || this.attachmentManager.successfulUploadsCount > 0) || this.pollId || !!this.locationComposer.validLocation);
18555
+ return !!(!this.attachmentManager.uploadsInProgressCount && (!this.textComposer.textIsEmpty || this.textComposer.activeCommandIsContent || this.attachmentManager.successfulUploadsCount > 0) || this.pollId || !!this.locationComposer.validLocation);
18596
18556
  }
18597
18557
  get compositionIsEmpty() {
18598
18558
  return !this.quotedMessage && this.contentIsEmpty;
18599
18559
  }
18600
18560
  get contentIsEmpty() {
18601
- return this.textComposer.textIsEmpty && !this.attachmentManager.attachments.length && !this.pollId && !this.locationComposer.validLocation;
18561
+ return this.textComposer.textIsEmpty && !this.textComposer.activeCommandIsContent && !this.attachmentManager.attachments.length && !this.pollId && !this.locationComposer.validLocation;
18602
18562
  }
18603
18563
  get lastChangeOriginIsLocal() {
18604
18564
  const initiatedWithoutDraft = this.lastChange.draftUpdate === null;
@@ -25205,7 +25165,7 @@ var StreamChat = class _StreamChat extends ChatApi {
25205
25165
  return this.userAgent;
25206
25166
  }
25207
25167
  if (!this.cachedUserAgent) {
25208
- const version = "10.0.0-rc.30";
25168
+ const version = "10.0.0-rc.32";
25209
25169
  const { name: sdkName, version: sdkVersion } = this.sdkIdentifier ?? {};
25210
25170
  const { name: appName, version: appVersion } = this.appIdentifier ?? {};
25211
25171
  const { os, model: deviceModel } = this.deviceIdentifier ?? {};
@@ -25782,7 +25742,7 @@ var StreamChat = class _StreamChat extends ChatApi {
25782
25742
  return await this.queryReactions(...args);
25783
25743
  }
25784
25744
  hydrateChannels(channelsFromApi = [], stateOptions = {}, queryChannelsOptions, headIntervalItemIdsAtRequestByCid) {
25785
- const { skipInitialization, offlineMode = false } = stateOptions;
25745
+ const { offlineMode = false } = stateOptions;
25786
25746
  const channels = [];
25787
25747
  for (const channelState of channelsFromApi) {
25788
25748
  if (!channelState.channel) continue;
@@ -25800,9 +25760,8 @@ var StreamChat = class _StreamChat extends ChatApi {
25800
25760
  c.watchStatus = ChannelWatchStatus.Watching;
25801
25761
  }
25802
25762
  c.push_preferences = channelState.push_preferences;
25803
- const willInitialize = skipInitialization === void 0 || !skipInitialization.includes(channelState.channel.id);
25804
25763
  const requestedPageSize = queryChannelsOptions?.message_limit ?? DEFAULT_QUERY_CHANNELS_MESSAGE_LIST_PAGE_SIZE;
25805
- const placesNewestPage = willInitialize && !c.active;
25764
+ const placesNewestPage = !c.active;
25806
25765
  let placedFirstPage = false;
25807
25766
  if (placesNewestPage) {
25808
25767
  c.messagePaginator.setQueriedLatestMessageAt(
@@ -25816,19 +25775,13 @@ var StreamChat = class _StreamChat extends ChatApi {
25816
25775
  }
25817
25776
  );
25818
25777
  }
25819
- if (skipInitialization === void 0) {
25820
- c._initializeState(channelState);
25821
- } else if (!skipInitialization.includes(channelState.channel.id)) {
25822
- c._initializeState(channelState);
25823
- }
25778
+ c._initializeState(channelState);
25824
25779
  if (placedFirstPage) c.messagePaginator.seedUnreadSnapshot();
25825
- if (willInitialize && !c.active && !wasWatching && !(placesNewestPage && channelState.messages.length)) {
25780
+ if (placesNewestPage && !wasWatching && !channelState.messages.length) {
25826
25781
  c.messagePaginator.unmarkStaleHead();
25827
25782
  }
25828
- if (willInitialize) {
25829
- this.polls.hydratePollCache(channelState.messages, true);
25830
- this.reminders.hydrateState(channelState.messages);
25831
- }
25783
+ this.polls.hydratePollCache(channelState.messages, true);
25784
+ this.reminders.hydrateState(channelState.messages);
25832
25785
  c.messageComposer.initStateFromChannelResponse(channelState);
25833
25786
  c.cooldownTimer.refresh();
25834
25787
  channels.push(c);
@@ -27723,6 +27676,8 @@ var AbstractOfflineDB = class {
27723
27676
  true
27724
27677
  );
27725
27678
  } catch (e) {
27679
+ const operation = QUEUEABLE_OPERATIONS[task.type];
27680
+ operation.onReplayRejected?.({ client: this.client, error: e, task });
27726
27681
  const error = e;
27727
27682
  if (!this.shouldSkipQueueingTask(error)) {
27728
27683
  continue;