@im-more/dsh-slack 0.0.0-stage → 0.1.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 (226) hide show
  1. package/LICENSE +21 -0
  2. package/cordis.patch.yml +13 -0
  3. package/lib/index.js +2659 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/bot.d.ts +66 -0
  6. package/lib/types/bot.d.ts.map +1 -0
  7. package/lib/types/bot.js +165 -0
  8. package/lib/types/bot.js.map +1 -0
  9. package/lib/types/config.d.ts +49 -0
  10. package/lib/types/config.d.ts.map +1 -0
  11. package/lib/types/config.js +54 -0
  12. package/lib/types/config.js.map +1 -0
  13. package/lib/types/decode.d.ts +126 -0
  14. package/lib/types/decode.d.ts.map +1 -0
  15. package/lib/types/decode.js +396 -0
  16. package/lib/types/decode.js.map +1 -0
  17. package/lib/types/errors.d.ts +61 -0
  18. package/lib/types/errors.d.ts.map +1 -0
  19. package/lib/types/errors.js +196 -0
  20. package/lib/types/errors.js.map +1 -0
  21. package/lib/types/identity.d.ts +27 -0
  22. package/lib/types/identity.d.ts.map +1 -0
  23. package/lib/types/identity.js +35 -0
  24. package/lib/types/identity.js.map +1 -0
  25. package/lib/types/index.d.ts +14 -0
  26. package/lib/types/index.d.ts.map +1 -0
  27. package/lib/types/index.js +14 -0
  28. package/lib/types/index.js.map +1 -0
  29. package/lib/types/modes/mrkdwn.d.ts +17 -0
  30. package/lib/types/modes/mrkdwn.d.ts.map +1 -0
  31. package/lib/types/modes/mrkdwn.js +123 -0
  32. package/lib/types/modes/mrkdwn.js.map +1 -0
  33. package/lib/types/modes/shared.d.ts +164 -0
  34. package/lib/types/modes/shared.d.ts.map +1 -0
  35. package/lib/types/modes/shared.js +411 -0
  36. package/lib/types/modes/shared.js.map +1 -0
  37. package/lib/types/mrkdwn.d.ts +41 -0
  38. package/lib/types/mrkdwn.d.ts.map +1 -0
  39. package/lib/types/mrkdwn.js +137 -0
  40. package/lib/types/mrkdwn.js.map +1 -0
  41. package/lib/types/request.d.ts +225 -0
  42. package/lib/types/request.d.ts.map +1 -0
  43. package/lib/types/request.js +330 -0
  44. package/lib/types/request.js.map +1 -0
  45. package/lib/types/send.d.ts +74 -0
  46. package/lib/types/send.d.ts.map +1 -0
  47. package/lib/types/send.js +200 -0
  48. package/lib/types/send.js.map +1 -0
  49. package/lib/types/transport/socket.d.ts +58 -0
  50. package/lib/types/transport/socket.d.ts.map +1 -0
  51. package/lib/types/transport/socket.js +297 -0
  52. package/lib/types/transport/socket.js.map +1 -0
  53. package/lib/types/transport/webhook.d.ts +48 -0
  54. package/lib/types/transport/webhook.d.ts.map +1 -0
  55. package/lib/types/transport/webhook.js +210 -0
  56. package/lib/types/transport/webhook.js.map +1 -0
  57. package/lib/types/types/admin.d.ts +682 -0
  58. package/lib/types/types/admin.d.ts.map +1 -0
  59. package/lib/types/types/admin.js +172 -0
  60. package/lib/types/types/admin.js.map +1 -0
  61. package/lib/types/types/api.d.ts +20 -0
  62. package/lib/types/types/api.d.ts.map +1 -0
  63. package/lib/types/types/api.js +7 -0
  64. package/lib/types/types/api.js.map +1 -0
  65. package/lib/types/types/apps.d.ts +138 -0
  66. package/lib/types/types/apps.d.ts.map +1 -0
  67. package/lib/types/types/apps.js +28 -0
  68. package/lib/types/types/apps.js.map +1 -0
  69. package/lib/types/types/auth.d.ts +36 -0
  70. package/lib/types/types/auth.d.ts.map +1 -0
  71. package/lib/types/types/auth.js +10 -0
  72. package/lib/types/types/auth.js.map +1 -0
  73. package/lib/types/types/bots.d.ts +32 -0
  74. package/lib/types/types/bots.d.ts.map +1 -0
  75. package/lib/types/types/bots.js +7 -0
  76. package/lib/types/types/bots.js.map +1 -0
  77. package/lib/types/types/calls.d.ts +82 -0
  78. package/lib/types/types/calls.d.ts.map +1 -0
  79. package/lib/types/types/calls.js +22 -0
  80. package/lib/types/types/calls.js.map +1 -0
  81. package/lib/types/types/chat.d.ts +208 -0
  82. package/lib/types/types/chat.d.ts.map +1 -0
  83. package/lib/types/types/chat.js +34 -0
  84. package/lib/types/types/chat.js.map +1 -0
  85. package/lib/types/types/conversations.d.ts +266 -0
  86. package/lib/types/types/conversations.d.ts.map +1 -0
  87. package/lib/types/types/conversations.js +58 -0
  88. package/lib/types/types/conversations.js.map +1 -0
  89. package/lib/types/types/definition.d.ts +505 -0
  90. package/lib/types/types/definition.d.ts.map +1 -0
  91. package/lib/types/types/definition.js +2 -0
  92. package/lib/types/types/definition.js.map +1 -0
  93. package/lib/types/types/dialog.d.ts +20 -0
  94. package/lib/types/types/dialog.d.ts.map +1 -0
  95. package/lib/types/types/dialog.js +7 -0
  96. package/lib/types/types/dialog.js.map +1 -0
  97. package/lib/types/types/dnd.d.ts +70 -0
  98. package/lib/types/types/dnd.d.ts.map +1 -0
  99. package/lib/types/types/dnd.js +19 -0
  100. package/lib/types/types/dnd.js.map +1 -0
  101. package/lib/types/types/emoji.d.ts +18 -0
  102. package/lib/types/types/emoji.d.ts.map +1 -0
  103. package/lib/types/types/emoji.js +7 -0
  104. package/lib/types/types/emoji.js.map +1 -0
  105. package/lib/types/types/events/base-events.d.ts +235 -0
  106. package/lib/types/types/events/base-events.d.ts.map +1 -0
  107. package/lib/types/types/events/base-events.js +3 -0
  108. package/lib/types/types/events/base-events.js.map +1 -0
  109. package/lib/types/types/events/index.d.ts +97 -0
  110. package/lib/types/types/events/index.d.ts.map +1 -0
  111. package/lib/types/types/events/index.js +3 -0
  112. package/lib/types/types/events/index.js.map +1 -0
  113. package/lib/types/types/events/message-events.d.ts +215 -0
  114. package/lib/types/types/events/message-events.d.ts.map +1 -0
  115. package/lib/types/types/events/message-events.js +3 -0
  116. package/lib/types/types/events/message-events.js.map +1 -0
  117. package/lib/types/types/files.d.ts +189 -0
  118. package/lib/types/types/files.d.ts.map +1 -0
  119. package/lib/types/types/files.js +43 -0
  120. package/lib/types/types/files.js.map +1 -0
  121. package/lib/types/types/index.d.ts +82 -0
  122. package/lib/types/types/index.d.ts.map +1 -0
  123. package/lib/types/types/index.js +29 -0
  124. package/lib/types/types/index.js.map +1 -0
  125. package/lib/types/types/internal.d.ts +17 -0
  126. package/lib/types/types/internal.d.ts.map +1 -0
  127. package/lib/types/types/internal.js +60 -0
  128. package/lib/types/types/internal.js.map +1 -0
  129. package/lib/types/types/migration.d.ts +25 -0
  130. package/lib/types/types/migration.d.ts.map +1 -0
  131. package/lib/types/types/migration.js +7 -0
  132. package/lib/types/types/migration.js.map +1 -0
  133. package/lib/types/types/oauth.d.ts +50 -0
  134. package/lib/types/types/oauth.d.ts.map +1 -0
  135. package/lib/types/types/oauth.js +13 -0
  136. package/lib/types/types/oauth.js.map +1 -0
  137. package/lib/types/types/pins.d.ts +39 -0
  138. package/lib/types/types/pins.d.ts.map +1 -0
  139. package/lib/types/types/pins.js +13 -0
  140. package/lib/types/types/pins.js.map +1 -0
  141. package/lib/types/types/reactions.d.ts +75 -0
  142. package/lib/types/types/reactions.d.ts.map +1 -0
  143. package/lib/types/types/reactions.js +16 -0
  144. package/lib/types/types/reactions.js.map +1 -0
  145. package/lib/types/types/reminders.d.ts +64 -0
  146. package/lib/types/types/reminders.d.ts.map +1 -0
  147. package/lib/types/types/reminders.js +19 -0
  148. package/lib/types/types/reminders.js.map +1 -0
  149. package/lib/types/types/rtm.d.ts +30 -0
  150. package/lib/types/types/rtm.d.ts.map +1 -0
  151. package/lib/types/types/rtm.js +7 -0
  152. package/lib/types/types/rtm.js.map +1 -0
  153. package/lib/types/types/search.d.ts +24 -0
  154. package/lib/types/types/search.d.ts.map +1 -0
  155. package/lib/types/types/search.js +7 -0
  156. package/lib/types/types/search.js.map +1 -0
  157. package/lib/types/types/stars.d.ts +56 -0
  158. package/lib/types/types/stars.d.ts.map +1 -0
  159. package/lib/types/types/stars.js +13 -0
  160. package/lib/types/types/stars.js.map +1 -0
  161. package/lib/types/types/team.d.ts +98 -0
  162. package/lib/types/types/team.d.ts.map +1 -0
  163. package/lib/types/types/team.js +19 -0
  164. package/lib/types/types/team.js.map +1 -0
  165. package/lib/types/types/usergroups.d.ts +103 -0
  166. package/lib/types/types/usergroups.d.ts.map +1 -0
  167. package/lib/types/types/usergroups.js +25 -0
  168. package/lib/types/types/usergroups.js.map +1 -0
  169. package/lib/types/types/users.d.ts +169 -0
  170. package/lib/types/types/users.d.ts.map +1 -0
  171. package/lib/types/types/users.js +40 -0
  172. package/lib/types/types/users.js.map +1 -0
  173. package/lib/types/types/views.d.ts +56 -0
  174. package/lib/types/types/views.d.ts.map +1 -0
  175. package/lib/types/types/views.js +16 -0
  176. package/lib/types/types/views.js.map +1 -0
  177. package/lib/types/types/workflows.d.ts +45 -0
  178. package/lib/types/types/workflows.d.ts.map +1 -0
  179. package/lib/types/types/workflows.js +13 -0
  180. package/lib/types/types/workflows.js.map +1 -0
  181. package/package.json +65 -3
  182. package/src/bot.ts +273 -0
  183. package/src/config.ts +92 -0
  184. package/src/decode.ts +489 -0
  185. package/src/errors.ts +230 -0
  186. package/src/identity.ts +59 -0
  187. package/src/index.ts +64 -0
  188. package/src/modes/mrkdwn.ts +159 -0
  189. package/src/modes/shared.ts +515 -0
  190. package/src/mrkdwn.ts +146 -0
  191. package/src/request.ts +449 -0
  192. package/src/send.ts +300 -0
  193. package/src/transport/socket.ts +393 -0
  194. package/src/transport/webhook.ts +269 -0
  195. package/src/types/admin.ts +910 -0
  196. package/src/types/api.ts +28 -0
  197. package/src/types/apps.ts +175 -0
  198. package/src/types/auth.ts +49 -0
  199. package/src/types/bots.ts +40 -0
  200. package/src/types/calls.ts +110 -0
  201. package/src/types/chat.ts +255 -0
  202. package/src/types/conversations.ts +342 -0
  203. package/src/types/definition.ts +530 -0
  204. package/src/types/dialog.ts +28 -0
  205. package/src/types/dnd.ts +94 -0
  206. package/src/types/emoji.ts +26 -0
  207. package/src/types/events/base-events.ts +281 -0
  208. package/src/types/events/index.ts +125 -0
  209. package/src/types/events/message-events.ts +253 -0
  210. package/src/types/files.ts +245 -0
  211. package/src/types/index.ts +84 -0
  212. package/src/types/internal.ts +60 -0
  213. package/src/types/migration.ts +34 -0
  214. package/src/types/oauth.ts +66 -0
  215. package/src/types/pins.ts +55 -0
  216. package/src/types/reactions.ts +95 -0
  217. package/src/types/reminders.ts +88 -0
  218. package/src/types/rtm.ts +38 -0
  219. package/src/types/search.ts +32 -0
  220. package/src/types/stars.ts +72 -0
  221. package/src/types/team.ts +122 -0
  222. package/src/types/usergroups.ts +135 -0
  223. package/src/types/users.ts +221 -0
  224. package/src/types/views.ts +76 -0
  225. package/src/types/workflows.ts +61 -0
  226. package/README.md +0 -3
package/src/send.ts ADDED
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Outbound hooks: the send pipeline's payload, deletion, member reads, message reads and reactions.
3
+ *
4
+ * Slack publishes a text part with `chat.postMessage` and an attachment with `files.completeUploadExternal`; there is
5
+ * no edit (the adapter does not implement `editPayload`), so the core's `edit` degrades to recall-and-resend.
6
+ */
7
+
8
+ import { PlatformError } from '@deepseek-ai/cordis-plugin-im-core'
9
+ import type {
10
+ ChatRef,
11
+ InboundMessage,
12
+ MembersPage,
13
+ MessageHandle,
14
+ MessageRef,
15
+ SendContext,
16
+ SentPart,
17
+ Target,
18
+ UserRef,
19
+ } from '@deepseek-ai/cordis-plugin-im-core'
20
+ import type { SlackBot } from './bot.ts'
21
+ import { decodeMessage } from './decode.ts'
22
+ import type { SlackMessageLike, SlackReferrer } from './decode.ts'
23
+ import { callApi, finishUpload } from './request.ts'
24
+ import type { SlackApi, SlackParams } from './request.ts'
25
+ import type { SlackPayload } from './modes/shared.ts'
26
+
27
+ /** Everything the send hooks need from the adapter. */
28
+ export interface SlackSendDeps {
29
+ readonly api: SlackApi
30
+ /** `team_id` of the installation, recorded in `SentPart.referrer`. */
31
+ readonly teamId: string | undefined
32
+ }
33
+
34
+ /** One member of the workspace, as `users.list` reports it. */
35
+ interface SlackMember {
36
+ id?: string
37
+ name?: string
38
+ real_name?: string
39
+ is_bot?: boolean
40
+ deleted?: boolean
41
+ profile?: { display_name?: string }
42
+ }
43
+
44
+ /** The message timestamp of one share of a file, per channel. */
45
+ function sharedTs(shares: unknown, channel: string): string | undefined {
46
+ const buckets =
47
+ typeof shares === 'object' && shares !== null
48
+ ? (shares as Record<string, unknown>)
49
+ : {}
50
+ for (const bucketName of ['public', 'private', 'ims']) {
51
+ const bucket = buckets[bucketName]
52
+ if (typeof bucket !== 'object' || bucket === null) continue
53
+ const entries = (bucket as Record<string, unknown>)[channel]
54
+ if (!Array.isArray(entries)) continue
55
+ for (const entry of entries) {
56
+ if (typeof entry !== 'object' || entry === null) continue
57
+ const ts = (entry as { ts?: unknown }).ts
58
+ if (typeof ts === 'string' && ts !== '') return ts
59
+ }
60
+ }
61
+ return undefined
62
+ }
63
+
64
+ /** Milliseconds of one Slack timestamp. */
65
+ function millisecondsOf(ts: string): number {
66
+ const seconds = Number(ts)
67
+ return Number.isFinite(seconds) ? Math.round(seconds * 1000) : Date.now()
68
+ }
69
+
70
+ /**
71
+ * Send one serialized payload.
72
+ * @param deps - the request dependencies.
73
+ * @param payload - the mode's request data.
74
+ * @param _target - the target chat, already carried by the payload.
75
+ * @param _ctx - part index and quote, already resolved by `serialize`.
76
+ * @returns the published part.
77
+ */
78
+ export async function sendPayload(
79
+ deps: SlackSendDeps,
80
+ payload: SlackPayload,
81
+ _target: Target,
82
+ _ctx: SendContext,
83
+ ): Promise<SentPart> {
84
+ const referrer = (channel: string, ts: string): SlackReferrer => ({
85
+ channel,
86
+ ts,
87
+ ...(payload.threadTs === undefined ? {} : { threadTs: payload.threadTs }),
88
+ ...(deps.teamId === undefined ? {} : { team: deps.teamId }),
89
+ })
90
+
91
+ if (payload.kind === 'file') {
92
+ const files = await finishUpload(
93
+ deps.api,
94
+ [{ id: payload.fileId, title: payload.name }],
95
+ payload.channel,
96
+ payload.threadTs,
97
+ )
98
+ const file = files[0]
99
+ if (file === undefined) {
100
+ throw new PlatformError(
101
+ 'invalid',
102
+ 'slack files.completeUploadExternal answered without the shared file',
103
+ { published: 'unknown' },
104
+ )
105
+ }
106
+ const ts = sharedTs(file.shares, payload.channel)
107
+ if (ts === undefined) {
108
+ throw new PlatformError(
109
+ 'invalid',
110
+ 'slack files.completeUploadExternal answered without a message timestamp for the channel',
111
+ { published: 'unknown' },
112
+ )
113
+ }
114
+ return {
115
+ id: ts,
116
+ kind: 'file',
117
+ time: file.created === undefined ? Date.now() : file.created * 1000,
118
+ thread: { id: payload.threadTs ?? ts },
119
+ referrer: referrer(payload.channel, ts),
120
+ }
121
+ }
122
+
123
+ const answer = await callApi<
124
+ { ok?: boolean } & { channel?: string; ts?: string }
125
+ >(deps.api, 'chatPostMessage', {
126
+ channel: payload.channel,
127
+ text: payload.text,
128
+ ...(payload.threadTs === undefined ? {} : { thread_ts: payload.threadTs }),
129
+ ...(payload.replyBroadcast === true ? { reply_broadcast: true } : {}),
130
+ })
131
+ const ts = answer.ts
132
+ if (ts === undefined || ts === '') {
133
+ // The request reached the platform and it accepted the message, so this is not a safe retry.
134
+ throw new PlatformError(
135
+ 'invalid',
136
+ 'slack chat.postMessage answered without a message timestamp',
137
+ { published: 'unknown' },
138
+ )
139
+ }
140
+ return {
141
+ id: ts,
142
+ kind: 'message',
143
+ time: millisecondsOf(ts),
144
+ thread: { id: payload.threadTs ?? ts },
145
+ referrer: referrer(answer.channel ?? payload.channel, ts),
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Recall one published part.
151
+ * @param deps - the request dependencies.
152
+ * @param part - the part to recall.
153
+ * @param handle - the message the part belongs to, which names the channel.
154
+ */
155
+ export async function deletePart(
156
+ deps: SlackSendDeps,
157
+ part: SentPart,
158
+ handle: MessageHandle,
159
+ ): Promise<void> {
160
+ await callApi(deps.api, 'chatDelete', {
161
+ channel: handle.target.chat.id,
162
+ ts: Number(part.id),
163
+ })
164
+ }
165
+
166
+ /** The first of the given names that is not empty. */
167
+ function firstNonEmpty(...values: (string | undefined)[]): string {
168
+ for (const value of values) {
169
+ if (value !== undefined && value !== '') return value
170
+ }
171
+ return ''
172
+ }
173
+
174
+ /** One workspace member as a user reference; the name is what `im_members` shows. */
175
+ function userRefOf(member: SlackMember): UserRef {
176
+ const name = firstNonEmpty(
177
+ member.real_name,
178
+ member.profile?.display_name,
179
+ member.name,
180
+ )
181
+ return {
182
+ id: member.id ?? '',
183
+ ...(name === '' ? {} : { name }),
184
+ ...(member.is_bot === undefined ? {} : { isBot: member.is_bot }),
185
+ }
186
+ }
187
+
188
+ /**
189
+ * List the members of the workspace.
190
+ *
191
+ * `users.list` is workspace-level: Slack has no paged channel-member read that this adapter could page, so the list is
192
+ * every human and bot of the installation, not the people of one conversation.
193
+ *
194
+ * @param deps - the request dependencies.
195
+ * @param _chat - the chat the caller asked about; unused, because the platform's list is not per chat.
196
+ * @param cursor - `next_cursor` of the previous page.
197
+ * @param limit - page size the platform should use.
198
+ * @returns one page of members.
199
+ */
200
+ export async function members(
201
+ deps: SlackSendDeps,
202
+ _chat: ChatRef,
203
+ cursor?: string,
204
+ limit?: number,
205
+ ): Promise<MembersPage> {
206
+ const params: SlackParams = {}
207
+ if (limit !== undefined) params.limit = limit
208
+ if (cursor !== undefined && cursor !== '') params.cursor = cursor
209
+ const answer = await callApi<
210
+ { ok?: boolean } & {
211
+ members?: SlackMember[]
212
+ response_metadata?: { next_cursor?: string }
213
+ }
214
+ >(deps.api, 'usersList', params)
215
+ const data = (answer.members ?? [])
216
+ .filter((member) => member.deleted !== true)
217
+ .map(userRefOf)
218
+ const next = answer.response_metadata?.next_cursor
219
+ return { data, ...(next === undefined || next === '' ? {} : { next }) }
220
+ }
221
+
222
+ /**
223
+ * Read one message by its timestamp.
224
+ *
225
+ * `conversations.history` answers newest first, so the call bounds both ends of the range: `oldest` alone (the
226
+ * upstream form) would return the newest message of the range instead of the one asked for.
227
+ *
228
+ * @param deps - the request dependencies.
229
+ * @param bot - the adapter, needed to decode the answer.
230
+ * @param chat - the chat the caller asked about; the answer carries no chat type, so it is reused verbatim.
231
+ * @param id - platform message timestamp.
232
+ * @returns the decoded message, with the same `chat` the caller passed.
233
+ * @throws PlatformError `not-found` when the timestamp names no message of that chat.
234
+ */
235
+ export async function getMessage(
236
+ deps: SlackSendDeps,
237
+ bot: SlackBot,
238
+ chat: ChatRef,
239
+ id: string,
240
+ ): Promise<InboundMessage> {
241
+ const answer = await callApi<
242
+ { ok?: boolean } & { messages?: readonly SlackMessageLike[] }
243
+ >(deps.api, 'conversationsHistory', {
244
+ channel: chat.id,
245
+ oldest: Number(id),
246
+ latest: Number(id),
247
+ inclusive: true,
248
+ limit: 1,
249
+ })
250
+ const raw = (answer.messages ?? [])[0]
251
+ if (raw === undefined) {
252
+ throw new PlatformError(
253
+ 'not-found',
254
+ `slack: message ${id} is not in ${chat.id}`,
255
+ { published: 'no' },
256
+ )
257
+ }
258
+ return decodeMessage(bot, raw, chat)
259
+ }
260
+
261
+ /** One reaction name: the platform wants the emoji name without its colons. */
262
+ function reactionName(emoji: string): string {
263
+ return emoji.replace(/^:+/, '').replace(/:+$/, '')
264
+ }
265
+
266
+ /**
267
+ * Add one reaction to a published message.
268
+ * @param deps - the request dependencies.
269
+ * @param message - the message to react to.
270
+ * @param emoji - the emoji (`:tada:` or `tada`).
271
+ */
272
+ export async function createReaction(
273
+ deps: SlackSendDeps,
274
+ message: MessageRef,
275
+ emoji: string,
276
+ ): Promise<void> {
277
+ await callApi(deps.api, 'reactionsAdd', {
278
+ channel: message.chat.id,
279
+ timestamp: message.id,
280
+ name: reactionName(emoji),
281
+ })
282
+ }
283
+
284
+ /**
285
+ * Remove one reaction from a published message.
286
+ * @param deps - the request dependencies.
287
+ * @param message - the message to react to.
288
+ * @param emoji - the emoji (`:tada:` or `tada`).
289
+ */
290
+ export async function deleteReaction(
291
+ deps: SlackSendDeps,
292
+ message: MessageRef,
293
+ emoji: string,
294
+ ): Promise<void> {
295
+ await callApi(deps.api, 'reactionsRemove', {
296
+ channel: message.chat.id,
297
+ timestamp: message.id,
298
+ name: reactionName(emoji),
299
+ })
300
+ }
@@ -0,0 +1,393 @@
1
+ /**
2
+ * Socket Mode transport (`protocol: 'ws'`).
3
+ *
4
+ * The adapter asks for a fresh connection URL before every dial (Slack hands out one ticket per connection), dials it
5
+ * with the `http` service, and dials again forever: `ws.retryTimes` is a fast-retry budget, not a give-up count.
6
+ * Configuration failures are the caller's to fix and throw out of `connect()`; transport failures retry.
7
+ *
8
+ * Every `events_api` envelope is acknowledged before it is decoded, which is what Slack's own guidance asks and what
9
+ * keeps a slow intake from tripping the delivery timeout. The cost is that a crash between the acknowledgement and the
10
+ * store loses the event: Slack does not redeliver an acknowledged envelope.
11
+ */
12
+
13
+ import { Status } from '@deepseek-ai/cordis-plugin-im-core'
14
+ import type {} from '@deepseek-ai/cordis-plugin-http'
15
+ import type { SlackBot } from '../bot.ts'
16
+ import { decodeEvent } from '../decode.ts'
17
+ import type { SlackEnvelopeLike } from '../decode.ts'
18
+ import { SlackApiError, SlackFatalError } from '../errors.ts'
19
+ import { callApi } from '../request.ts'
20
+
21
+ /** Waitable sleep that resolves early on abort. */
22
+ function sleep(ms: number, signal: AbortSignal): Promise<void> {
23
+ return new Promise((resolve) => {
24
+ if (signal.aborted) {
25
+ resolve()
26
+ return
27
+ }
28
+ const timer = setTimeout(() => {
29
+ signal.removeEventListener('abort', onAbort)
30
+ resolve()
31
+ }, ms)
32
+ const onAbort = (): void => {
33
+ clearTimeout(timer)
34
+ resolve()
35
+ }
36
+ signal.addEventListener('abort', onAbort, { once: true })
37
+ })
38
+ }
39
+
40
+ /** The WebSocket the `http` service opens (Node's global `WebSocket`). */
41
+ type SlackSocket = ReturnType<SlackBot['ctx']['http']['ws']>
42
+
43
+ /** `apps.connections.open` refusals that only an app or token change can fix. */
44
+ const PERMANENT_OPEN_ERRORS = new Set([
45
+ 'invalid_auth',
46
+ 'not_authed',
47
+ 'token_revoked',
48
+ 'missing_scope',
49
+ ])
50
+
51
+ /** `hello`: the connection is up. */
52
+ interface HelloFrame {
53
+ type: 'hello'
54
+ num_connections?: number
55
+ approximate_connection_time?: number
56
+ connection_info?: { app_id?: string }
57
+ }
58
+
59
+ /** One event the platform pushes over the socket. */
60
+ interface EventsFrame {
61
+ type: 'events_api'
62
+ envelope_id: string
63
+ payload: SlackEnvelopeLike
64
+ accepts_response_payload?: boolean
65
+ }
66
+
67
+ /** The platform about to close the connection. */
68
+ interface DisconnectFrame {
69
+ type: 'disconnect'
70
+ reason?: string
71
+ }
72
+
73
+ /** A frame this adapter consumes without handling: v1 sends no buttons, forms or slash commands. */
74
+ interface UnsupportedFrame {
75
+ type: 'interactive' | 'slash_commands'
76
+ envelope_id: string
77
+ }
78
+
79
+ /** Text of one WebSocket frame. */
80
+ function frameText(data: unknown): string {
81
+ return typeof data === 'string' ? data : String(data)
82
+ }
83
+
84
+ /** Message of any caught value, for a log line. */
85
+ function messageOf(error: unknown): string {
86
+ return error instanceof Error ? error.message : String(error)
87
+ }
88
+
89
+ /** The Socket Mode client of one bot. */
90
+ export class SlackSocketMode {
91
+ private controller: AbortController | undefined
92
+ private running: Promise<void> | undefined
93
+ private socket: SlackSocket | undefined
94
+
95
+ constructor(private readonly bot: SlackBot) {}
96
+
97
+ /**
98
+ * Start the reconnect loop.
99
+ *
100
+ * Returning before the first dial is deliberate: `Bot.start` awaits `connect()`, so waiting here would hold up
101
+ * plugin initialization for as long as Slack is unreachable.
102
+ */
103
+ async start(): Promise<void> {
104
+ this.controller = new AbortController()
105
+ this.running = this.loop(this.controller.signal)
106
+ }
107
+
108
+ /** Stop the loop and wait for it to unwind. */
109
+ async stop(): Promise<void> {
110
+ this.controller?.abort()
111
+ this.controller = undefined
112
+ this.closeSocket()
113
+ await this.running?.catch(() => undefined)
114
+ this.running = undefined
115
+ }
116
+
117
+ private async loop(signal: AbortSignal): Promise<void> {
118
+ let failures = 0
119
+ while (!signal.aborted) {
120
+ try {
121
+ const url = await this.openUrl(signal)
122
+ const socket = await this.dial(url, signal)
123
+ this.socket = socket
124
+ const greeted = await this.accept(socket, signal)
125
+ this.socket = undefined
126
+ if (signal.aborted) return
127
+ // A connection that greeted once proves the credentials work, so the next dial goes out at the fast interval.
128
+ failures = greeted ? 0 : failures + 1
129
+ this.bot.ctx.logger.warn(
130
+ 'slack: the Socket Mode connection closed; reconnecting',
131
+ )
132
+ this.bot.status = Status.RECONNECT
133
+ await sleep(this.intervalOf(failures), signal)
134
+ } catch (error) {
135
+ if (signal.aborted) return
136
+ if (error instanceof SlackFatalError) {
137
+ // A rejected app token cannot be fixed by reconnecting: report it and stop until the profile is edited.
138
+ this.bot.ctx.logger.error('%s', error.message)
139
+ this.bot.offline(error)
140
+ return
141
+ }
142
+ failures += 1
143
+ this.bot.ctx.logger.warn('slack: %s; reconnecting', messageOf(error))
144
+ this.bot.status = Status.RECONNECT
145
+ await sleep(this.intervalOf(failures), signal)
146
+ }
147
+ }
148
+ }
149
+
150
+ /** Delay before the next dial: the fast interval while the failure budget lasts, the lazy one after it. */
151
+ private intervalOf(failures: number): number {
152
+ const { ws } = this.bot.config
153
+ return failures < ws.retryTimes ? ws.retryInterval : ws.retryLazy
154
+ }
155
+
156
+ /** Fetch the connection URL of the next dial. */
157
+ private async openUrl(signal: AbortSignal): Promise<string> {
158
+ let answer: { ok?: boolean } & { url?: string }
159
+ try {
160
+ answer = await callApi(
161
+ this.bot.api,
162
+ 'appsConnectionsOpen',
163
+ {},
164
+ {
165
+ app: true,
166
+ signal,
167
+ },
168
+ )
169
+ } catch (error) {
170
+ if (
171
+ error instanceof SlackApiError &&
172
+ error.code !== undefined &&
173
+ PERMANENT_OPEN_ERRORS.has(error.code)
174
+ ) {
175
+ throw new SlackFatalError(
176
+ `slack: apps.connections.open refused the app-level token (${error.code}); fix token and restart`,
177
+ { cause: error },
178
+ )
179
+ }
180
+ throw error
181
+ }
182
+ if (answer.url === undefined || answer.url === '') {
183
+ throw new Error('slack: apps.connections.open answered without a url')
184
+ }
185
+ return answer.url
186
+ }
187
+
188
+ /** Dial the connection URL and resolve once the socket is open. */
189
+ private dial(url: string, signal: AbortSignal): Promise<SlackSocket> {
190
+ const socket = this.bot.ctx.http.ws(url)
191
+ return new Promise<SlackSocket>((resolve, reject) => {
192
+ const cleanup = (): void => {
193
+ socket.removeEventListener('open', onOpen)
194
+ socket.removeEventListener('error', onError)
195
+ socket.removeEventListener('close', onClose)
196
+ signal.removeEventListener('abort', onAbort)
197
+ }
198
+ const onOpen = (): void => {
199
+ cleanup()
200
+ resolve(socket)
201
+ }
202
+ const onError = (event: { message?: string }): void => {
203
+ cleanup()
204
+ reject(
205
+ new Error(
206
+ `slack: WebSocket error${event.message === undefined ? '' : `: ${event.message}`}`,
207
+ ),
208
+ )
209
+ }
210
+ const onClose = (event: { code: number }): void => {
211
+ cleanup()
212
+ reject(
213
+ new Error(
214
+ `slack: WebSocket closed before opening (code ${event.code})`,
215
+ ),
216
+ )
217
+ }
218
+ const onAbort = (): void => {
219
+ cleanup()
220
+ reject(signal.reason ?? new Error('slack: adapter stopped'))
221
+ }
222
+ if (signal.aborted) {
223
+ onAbort()
224
+ return
225
+ }
226
+ socket.addEventListener('open', onOpen)
227
+ socket.addEventListener('error', onError)
228
+ socket.addEventListener('close', onClose)
229
+ signal.addEventListener('abort', onAbort, { once: true })
230
+ })
231
+ }
232
+
233
+ /**
234
+ * Serve one open connection until it closes.
235
+ * @param socket - the open socket.
236
+ * @param signal - cancellation of the loop.
237
+ * @returns whether `hello` arrived, i.e. whether the connection ever worked.
238
+ */
239
+ private async accept(
240
+ socket: SlackSocket,
241
+ signal: AbortSignal,
242
+ ): Promise<boolean> {
243
+ let greeted = false
244
+ const closed = new Promise<void>((resolve) => {
245
+ socket.addEventListener('close', () => {
246
+ resolve()
247
+ })
248
+ })
249
+ socket.addEventListener('message', (event) => {
250
+ this.handleFrame(socket, frameText(event.data), () => {
251
+ greeted = true
252
+ })
253
+ })
254
+ const onAbort = (): void => {
255
+ this.closeSocket()
256
+ }
257
+ signal.addEventListener('abort', onAbort, { once: true })
258
+ try {
259
+ await closed
260
+ } finally {
261
+ signal.removeEventListener('abort', onAbort)
262
+ }
263
+ return greeted
264
+ }
265
+
266
+ /** Dispatch one received frame: a greeting, an event, a disconnect notice or noise. */
267
+ private handleFrame(
268
+ socket: SlackSocket,
269
+ text: string,
270
+ markGreeted: () => void,
271
+ ): void {
272
+ let parsed: unknown
273
+ try {
274
+ parsed = JSON.parse(text)
275
+ } catch (error) {
276
+ this.bot.ctx.logger.warn(
277
+ 'slack: cannot parse a Socket Mode frame: %s',
278
+ messageOf(error),
279
+ )
280
+ return
281
+ }
282
+ if (typeof parsed !== 'object' || parsed === null) return
283
+ switch ((parsed as { type?: unknown }).type) {
284
+ case 'hello': {
285
+ const frame = parsed as HelloFrame
286
+ markGreeted()
287
+ this.bot.ctx.logger.debug(
288
+ 'slack: connected to app %s (%s connection(s)); the platform may keep it for about %s s',
289
+ frame.connection_info?.app_id ?? 'unknown',
290
+ frame.num_connections ?? 1,
291
+ frame.approximate_connection_time ?? 0,
292
+ )
293
+ this.bot.online()
294
+ return
295
+ }
296
+ case 'events_api':
297
+ void this.deliver(socket, parsed as EventsFrame)
298
+ return
299
+ case 'disconnect':
300
+ this.disconnect(parsed as DisconnectFrame)
301
+ return
302
+ case 'interactive':
303
+ case 'slash_commands': {
304
+ // v1 publishes no buttons, forms or slash commands, but an unacknowledged envelope is redelivered forever.
305
+ this.acknowledge(socket, (parsed as UnsupportedFrame).envelope_id)
306
+ this.bot.ctx.logger.debug(
307
+ 'slack: ignored an %s envelope',
308
+ (parsed as UnsupportedFrame).type,
309
+ )
310
+ return
311
+ }
312
+ default:
313
+ this.bot.ctx.logger.debug(
314
+ 'slack: ignored a Socket Mode frame of type "%s"',
315
+ String((parsed as { type?: unknown }).type ?? 'unknown'),
316
+ )
317
+ }
318
+ }
319
+
320
+ /** Send the acknowledgement of one envelope, when the socket still accepts it. */
321
+ private acknowledge(socket: SlackSocket, envelopeId: string): void {
322
+ try {
323
+ socket.send(JSON.stringify({ envelope_id: envelopeId }))
324
+ } catch (error) {
325
+ this.bot.ctx.logger.warn(
326
+ 'slack: could not acknowledge an envelope: %s',
327
+ messageOf(error),
328
+ )
329
+ }
330
+ }
331
+
332
+ /**
333
+ * Acknowledge one envelope, then hand its event to intake.
334
+ *
335
+ * The acknowledgement goes out first and its failure is only logged: Slack will not redeliver an acknowledged event,
336
+ * so a failed intake is reported here instead of being retried by the platform.
337
+ */
338
+ private async deliver(
339
+ socket: SlackSocket,
340
+ frame: EventsFrame,
341
+ ): Promise<void> {
342
+ this.acknowledge(socket, frame.envelope_id)
343
+ let session
344
+ try {
345
+ session = decodeEvent(this.bot, frame.payload)
346
+ } catch (error) {
347
+ this.bot.ctx.logger.error(
348
+ 'slack: cannot decode an envelope: %s',
349
+ messageOf(error),
350
+ )
351
+ return
352
+ }
353
+ if (session === undefined) {
354
+ this.bot.ctx.logger.debug(
355
+ 'slack: ignored an %s event',
356
+ frame.payload.event?.type ?? 'unknown',
357
+ )
358
+ return
359
+ }
360
+ try {
361
+ await this.bot.receive(session)
362
+ } catch (error) {
363
+ this.bot.ctx.logger.error('slack: intake failed: %s', messageOf(error))
364
+ }
365
+ }
366
+
367
+ /** Handle the platform's notice that the connection is going away. */
368
+ private disconnect(frame: DisconnectFrame): void {
369
+ const reason = frame.reason ?? ''
370
+ if (reason === 'warning') {
371
+ this.bot.ctx.logger.info(
372
+ 'slack: the platform will refresh the connection soon; keeping it until it closes',
373
+ )
374
+ return
375
+ }
376
+ this.bot.ctx.logger.info(
377
+ 'slack: the platform closed the connection (%s); reconnecting',
378
+ reason === '' ? 'no reason given' : reason,
379
+ )
380
+ this.closeSocket()
381
+ }
382
+
383
+ private closeSocket(): void {
384
+ const socket = this.socket
385
+ this.socket = undefined
386
+ try {
387
+ socket?.close(1000, 'adapter stopped')
388
+ } catch (error) {
389
+ // The socket is already closed or closing; nothing left to release.
390
+ void error
391
+ }
392
+ }
393
+ }