@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/decode.ts ADDED
@@ -0,0 +1,489 @@
1
+ /**
2
+ * Inbound decoding: one Slack event becomes an intake `Session`, and one message object becomes an `InboundMessage`.
3
+ *
4
+ * The event kinds the vocabulary can carry are messages (the plain kind plus `file_share` and `thread_broadcast`),
5
+ * message deletions and reactions; everything else is dropped. Message content is decoded from `blocks` when the
6
+ * message has any, and from the `text` field otherwise, so a plain-text message is not lost.
7
+ */
8
+
9
+ import { h, normalize } from '@deepseek-ai/cordis-plugin-im-core'
10
+ import type {
11
+ ChatRef,
12
+ Element,
13
+ InboundMessage,
14
+ Session,
15
+ UserRef,
16
+ } from '@deepseek-ai/cordis-plugin-im-core'
17
+ import type { SlackBot } from './bot.ts'
18
+ import { parseMrkdwn, unescape } from './mrkdwn.ts'
19
+
20
+ /** Adapter-private context carried through `Target.referrer`. */
21
+ export interface SlackReferrer {
22
+ /** Channel the message appeared in. */
23
+ channel: string
24
+ /** Message timestamp. */
25
+ ts: string
26
+ /** Thread root, when the message is a thread reply. */
27
+ threadTs?: string
28
+ team?: string
29
+ }
30
+
31
+ /** A file attachment of one message. */
32
+ export interface SlackFile {
33
+ id: string
34
+ mimetype?: string
35
+ name?: string | null
36
+ title?: string | null
37
+ created?: number
38
+ }
39
+
40
+ /**
41
+ * The message fields decoding reads.
42
+ *
43
+ * Every field is optional: the message arrives as an event (whose subtypes carry different fields), as a
44
+ * `conversations.history` row, or as the `message` of a `chat.postMessage` answer. The fields are read structurally
45
+ * because this is the wire.
46
+ */
47
+ export interface SlackMessageLike {
48
+ ts?: string
49
+ event_ts?: string
50
+ text?: string
51
+ blocks?: readonly unknown[]
52
+ files?: readonly SlackFile[]
53
+ user?: string
54
+ bot_id?: string
55
+ username?: string
56
+ channel?: string
57
+ channel_type?: string
58
+ thread_ts?: string
59
+ team?: string
60
+ subtype?: string
61
+ previous_message?: SlackMessageLike
62
+ deleted_ts?: string
63
+ reaction?: string
64
+ item?: { type?: string; channel?: string; ts?: string }
65
+ type?: string
66
+ }
67
+
68
+ /** The envelope of one received event; the Events API body is the same object as the Socket Mode payload. */
69
+ export interface SlackEnvelopeLike {
70
+ type?: string
71
+ event?: SlackMessageLike
72
+ event_id?: string
73
+ event_ts?: string
74
+ team_id?: string
75
+ }
76
+
77
+ /** One JSON object from the wire. */
78
+ type Dict = Record<string, unknown>
79
+
80
+ /** One JSON value from the wire, when it is an object. */
81
+ function asRecord(value: unknown): Dict | undefined {
82
+ return typeof value === 'object' && value !== null
83
+ ? (value as Dict)
84
+ : undefined
85
+ }
86
+
87
+ /** One JSON value from the wire, when it is a string. */
88
+ function asString(value: unknown): string | undefined {
89
+ return typeof value === 'string' ? value : undefined
90
+ }
91
+
92
+ /** One JSON value from the wire, when it is an array. */
93
+ function asArray(value: unknown): readonly unknown[] {
94
+ return Array.isArray(value) ? value : []
95
+ }
96
+
97
+ /**
98
+ * Chat type of one Slack conversation.
99
+ *
100
+ * The event's `channel_type` is authoritative when it is present; an id prefix is the fallback, because the read
101
+ * endpoints answer without a type.
102
+ *
103
+ * @param id - the conversation id (`C…`, `G…`, `D…`).
104
+ * @param channelType - `channel_type` of the event, when it carried one.
105
+ * @returns the DSH chat type.
106
+ */
107
+ export function chatTypeOf(
108
+ id: string,
109
+ channelType: string | undefined,
110
+ ): ChatRef['type'] {
111
+ if (channelType === 'im') return 'direct'
112
+ if (channelType !== undefined) return 'group'
113
+ return id.startsWith('D') ? 'direct' : 'group'
114
+ }
115
+
116
+ /** The chat one message belongs to; a message event names the conversation it appeared in. */
117
+ function chatRefOf(data: SlackMessageLike): ChatRef {
118
+ const id = data.channel ?? ''
119
+ return { id, type: chatTypeOf(id, data.channel_type) }
120
+ }
121
+
122
+ /** A Slack timestamp (seconds with a fraction) as milliseconds. */
123
+ function timeOf(ts: string | undefined): number {
124
+ const seconds = Number(ts ?? '')
125
+ return Number.isFinite(seconds) ? Math.floor(seconds * 1000) : Date.now()
126
+ }
127
+
128
+ /** Decode one `emoji` rich-text node's `unicode` (`1f389`, or a `-`-joined sequence) into its characters. */
129
+ function unicodeOf(unicode: string): string | undefined {
130
+ const codePoints: number[] = []
131
+ for (const part of unicode.split('-')) {
132
+ const codePoint = Number.parseInt(part, 16)
133
+ if (!Number.isFinite(codePoint) || codePoint <= 0) return undefined
134
+ codePoints.push(codePoint)
135
+ }
136
+ if (codePoints.length === 0) return undefined
137
+ try {
138
+ return String.fromCodePoint(...codePoints)
139
+ } catch (error) {
140
+ // A code point above U+10FFFF is not a character; the emoji's short name stands in.
141
+ void error
142
+ return undefined
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Decode the inline nodes of one `rich_text*` node.
148
+ * @param raw - the node's `elements` array.
149
+ * @returns the content nodes.
150
+ */
151
+ export function decodeRichText(raw: unknown): Element[] {
152
+ const nodes: Element[] = []
153
+ for (const item of asArray(raw)) {
154
+ const node = asRecord(item)
155
+ if (node === undefined) continue
156
+ switch (asString(node.type)) {
157
+ case 'text': {
158
+ const text = unescape(asString(node.text) ?? '')
159
+ const style = asRecord(node.style) ?? {}
160
+ let element: Element = h.text(text)
161
+ if (style.bold === true) element = h('b', {}, element)
162
+ if (style.italic === true) element = h('i', {}, element)
163
+ if (style.strike === true) element = h('s', {}, element)
164
+ if (style.code === true) element = h('code', {}, element)
165
+ nodes.push(element)
166
+ break
167
+ }
168
+ case 'link': {
169
+ const href = asString(node.url) ?? ''
170
+ const label = unescape(asString(node.text) ?? '')
171
+ nodes.push(h('a', { href }, label === '' ? href : label))
172
+ break
173
+ }
174
+ case 'emoji': {
175
+ const unicode = asString(node.unicode)
176
+ const text = unicode === undefined ? undefined : unicodeOf(unicode)
177
+ if (text !== undefined) nodes.push(h.text(text))
178
+ else if (asString(node.name) !== undefined) {
179
+ nodes.push(h.text(`:${asString(node.name)!}:`))
180
+ }
181
+ break
182
+ }
183
+ case 'user': {
184
+ const id = asString(node.user_id) ?? ''
185
+ nodes.push(h('at', { type: 'user', id }))
186
+ break
187
+ }
188
+ case 'broadcast': {
189
+ nodes.push(
190
+ h('at', { type: asString(node.range) === 'here' ? 'here' : 'all' }),
191
+ )
192
+ break
193
+ }
194
+ default: {
195
+ // A node Slack added later: keeping its text field loses no content.
196
+ const text = asString(node.text)
197
+ if (text !== undefined && text !== '')
198
+ nodes.push(h.text(unescape(text)))
199
+ break
200
+ }
201
+ }
202
+ }
203
+ return nodes
204
+ }
205
+
206
+ /** One `rich_text*` block (or a `rich_text_*` node inside it) as content nodes. */
207
+ function decodeRichBlock(block: Dict): Element[] {
208
+ const nodes: Element[] = []
209
+ for (const item of asArray(block.elements)) {
210
+ const element = asRecord(item)
211
+ if (element === undefined) continue
212
+ switch (asString(element.type)) {
213
+ case 'rich_text_section':
214
+ nodes.push(...decodeRichText(element.elements))
215
+ break
216
+ case 'rich_text_list': {
217
+ const items: Element[] = []
218
+ for (const entry of asArray(element.elements)) {
219
+ const section = asRecord(entry)
220
+ if (section === undefined) continue
221
+ items.push(h('li', {}, ...decodeRichText(section.elements)))
222
+ }
223
+ nodes.push(
224
+ h(asString(element.style) === 'ordered' ? 'ol' : 'ul', {}, ...items),
225
+ )
226
+ break
227
+ }
228
+ case 'rich_text_preformatted':
229
+ nodes.push(h('pre', {}, ...decodeRichText(element.elements)))
230
+ break
231
+ case 'rich_text_quote':
232
+ nodes.push(h('blockquote', {}, ...decodeRichText(element.elements)))
233
+ break
234
+ default: {
235
+ const text = asString(element.text)
236
+ if (text !== undefined && text !== '')
237
+ nodes.push(h.text(unescape(text)))
238
+ break
239
+ }
240
+ }
241
+ }
242
+ return nodes
243
+ }
244
+
245
+ /**
246
+ * Decode the `blocks` of one message.
247
+ *
248
+ * Only the two block kinds that carry content are decoded: `rich_text` (sections, lists, preformatted and quoted runs)
249
+ * and `section` (its mrkdwn text). The rest — `header`, `divider`, `context`, `image`, `actions`, `file` — are left to
250
+ * the message's `text` field, which Slack keeps as the notification fallback of a blocks message.
251
+ *
252
+ * @param raw - the message's `blocks`.
253
+ * @returns the content nodes; empty when the blocks carried nothing decodable.
254
+ */
255
+ export function decodeBlocks(raw: readonly unknown[]): Element[] {
256
+ const nodes: Element[] = []
257
+ for (const item of raw) {
258
+ const block = asRecord(item)
259
+ if (block === undefined) continue
260
+ if (asString(block.type) === 'rich_text') {
261
+ nodes.push(...decodeRichBlock(block))
262
+ continue
263
+ }
264
+ if (asString(block.type) === 'section') {
265
+ const text = asRecord(block.text)
266
+ const content = asString(text?.text)
267
+ if (content !== undefined && content !== '') {
268
+ nodes.push(...parseMrkdwn(content))
269
+ }
270
+ }
271
+ }
272
+ return nodes
273
+ }
274
+
275
+ /**
276
+ * Decode one attachment into the element that names it.
277
+ *
278
+ * The element's source is the bot's own `satori:` route rather than `url_private`: that URL needs the bot token, which
279
+ * the host does not have.
280
+ *
281
+ * @param bot - the receiving adapter, whose route serves the bytes.
282
+ * @param file - one `files[]` entry of the message.
283
+ * @returns the media element, typed by the file's MIME type.
284
+ */
285
+ export function decodeFile(bot: SlackBot, file: SlackFile): Element {
286
+ const src = bot.getInternalUrl(`/files/${file.id}`)
287
+ const mime = file.mimetype ?? ''
288
+ if (mime.startsWith('image/')) return h('img', { src })
289
+ if (mime.startsWith('audio/')) return h('audio', { src })
290
+ if (mime.startsWith('video/')) return h('video', { src })
291
+ const name = file.name ?? file.title ?? ''
292
+ return h('file', { src, ...(name === '' ? {} : { name }) })
293
+ }
294
+
295
+ /** Collect what one decoded message mentions; the self mention is what makes a group chat answer. */
296
+ function collectMentions(
297
+ bot: SlackBot,
298
+ content: Element,
299
+ ): InboundMessage['mentions'] {
300
+ const users: UserRef[] = []
301
+ const seen = new Set<string>()
302
+ const mentions = { self: false, all: false, users }
303
+ const walk = (element: Element): void => {
304
+ if (element.type === 'at') {
305
+ if (element.attrs.type === 'all') mentions.all = true
306
+ else if (element.attrs.type === 'user') {
307
+ const id = element.attrs.id
308
+ if (id !== undefined && !seen.has(id)) {
309
+ seen.add(id)
310
+ users.push({
311
+ id,
312
+ ...(element.attrs.name === undefined
313
+ ? {}
314
+ : { name: element.attrs.name }),
315
+ })
316
+ }
317
+ if (id !== undefined && id === bot.selfId) mentions.self = true
318
+ }
319
+ }
320
+ for (const child of element.children) walk(child)
321
+ }
322
+ walk(content)
323
+ return mentions
324
+ }
325
+
326
+ /** A bounded description of a message that decoded to no content, so `<raw>` stays small. */
327
+ function rawPreview(data: SlackMessageLike): Dict {
328
+ const preview: Dict = {}
329
+ for (const key of [
330
+ 'type',
331
+ 'subtype',
332
+ 'ts',
333
+ 'channel',
334
+ 'user',
335
+ 'bot_id',
336
+ ] as const) {
337
+ const value = data[key]
338
+ if (typeof value === 'string') preview[key] = value
339
+ }
340
+ const files = data.files ?? []
341
+ if (files.length > 0) preview.files = files.length
342
+ return preview
343
+ }
344
+
345
+ /** The sender of one message: Slack names the user, or the bot app of a bot message. */
346
+ function senderOf(data: SlackMessageLike): UserRef {
347
+ const id = data.user ?? data.bot_id ?? data.username ?? ''
348
+ return { id, ...(data.bot_id === undefined ? {} : { isBot: true }) }
349
+ }
350
+
351
+ /**
352
+ * Decode one message object into an inbound message.
353
+ *
354
+ * @param bot - the receiving adapter.
355
+ * @param data - a message event, a `conversations.history` row, or the `message` of a send answer.
356
+ * @param chat - the chat to report; defaults to the one the message names.
357
+ * @returns the decoded message, whose `content` is never empty.
358
+ */
359
+ export function decodeMessage(
360
+ bot: SlackBot,
361
+ data: SlackMessageLike,
362
+ chat: ChatRef = chatRefOf(data),
363
+ ): InboundMessage {
364
+ const nodes = decodeBlocks(data.blocks ?? [])
365
+ if (nodes.length === 0 && data.text !== undefined && data.text !== '') {
366
+ nodes.push(...parseMrkdwn(data.text))
367
+ }
368
+ for (const file of data.files ?? []) nodes.push(decodeFile(bot, file))
369
+ const content = normalize(
370
+ nodes.length > 0
371
+ ? nodes
372
+ : [
373
+ h(
374
+ 'raw',
375
+ {
376
+ platform: 'slack',
377
+ type: data.subtype ?? data.type ?? 'message',
378
+ data: rawPreview(data),
379
+ },
380
+ h.text(''),
381
+ ),
382
+ ],
383
+ )
384
+
385
+ const time = timeOf(data.ts)
386
+ const threadTs = data.thread_ts
387
+ const inThread = threadTs !== undefined && threadTs !== data.ts
388
+ const referrer: SlackReferrer = {
389
+ channel: chat.id,
390
+ ts: data.ts ?? '',
391
+ ...(inThread ? { threadTs } : {}),
392
+ ...(data.team === undefined ? {} : { team: data.team }),
393
+ }
394
+ return {
395
+ id: data.ts ?? '',
396
+ chat,
397
+ ...(inThread ? { thread: { id: threadTs, root: threadTs } } : {}),
398
+ sender: senderOf(data),
399
+ content,
400
+ ...(inThread ? { quote: { id: threadTs } } : {}),
401
+ mentions: collectMentions(bot, content),
402
+ time,
403
+ referrer,
404
+ raw: data,
405
+ }
406
+ }
407
+
408
+ /** The envelope id of one event: global, and the key the host deduplicates on. */
409
+ export function eventIdOf(
410
+ envelope: SlackEnvelopeLike,
411
+ event: SlackMessageLike,
412
+ ): string {
413
+ if (envelope.event_id !== undefined && envelope.event_id !== '') {
414
+ return envelope.event_id
415
+ }
416
+ return `${event.type ?? 'event'}:${event.event_ts ?? event.ts ?? ''}:${event.channel ?? ''}`
417
+ }
418
+
419
+ /**
420
+ * Decode one received event.
421
+ *
422
+ * @param bot - the receiving adapter (its `selfId` marks its own messages, which are dropped because the host stores
423
+ * them from the `send` event instead).
424
+ * @param envelope - the event envelope of either transport.
425
+ * @returns the session to publish, or undefined for an event this adapter does not carry.
426
+ */
427
+ export function decodeEvent(
428
+ bot: SlackBot,
429
+ envelope: SlackEnvelopeLike,
430
+ ): Session | undefined {
431
+ const event = envelope.event
432
+ if (event?.type === undefined) return undefined
433
+ const id = eventIdOf(envelope, event)
434
+
435
+ if (event.type === 'message') {
436
+ // The bot's own message: the host records it from the publication, and a second copy would duplicate the turn.
437
+ if (event.user !== undefined && event.user === bot.selfId) return undefined
438
+ const subtype = event.subtype
439
+ if (
440
+ subtype === undefined ||
441
+ subtype === 'file_share' ||
442
+ subtype === 'thread_broadcast'
443
+ ) {
444
+ const message = decodeMessage(bot, event)
445
+ return bot.session({
446
+ type: 'message',
447
+ id,
448
+ timestamp: message.time,
449
+ message,
450
+ raw: envelope,
451
+ })
452
+ }
453
+ if (subtype === 'message_deleted') {
454
+ const previous = event.previous_message
455
+ const ts = previous?.ts ?? event.deleted_ts ?? ''
456
+ return bot.session({
457
+ type: 'message-deleted',
458
+ id,
459
+ timestamp: timeOf(previous?.ts ?? event.event_ts),
460
+ deleted: { id: ts, chat: chatRefOf(previous ?? event) },
461
+ raw: envelope,
462
+ })
463
+ }
464
+ // `message_changed` has no consumer in this host, and the other subtypes (joins, topic changes, …) carry no chat.
465
+ return undefined
466
+ }
467
+
468
+ if (event.type === 'reaction_added' || event.type === 'reaction_removed') {
469
+ const channel = event.item?.channel ?? ''
470
+ const user = event.user
471
+ return bot.session({
472
+ type:
473
+ event.type === 'reaction_added' ? 'reaction-added' : 'reaction-removed',
474
+ id,
475
+ timestamp: timeOf(event.event_ts),
476
+ reaction: {
477
+ message: {
478
+ id: event.item?.ts ?? '',
479
+ chat: { id: channel, type: chatTypeOf(channel, undefined) },
480
+ },
481
+ emoji: event.reaction ?? '',
482
+ ...(user === undefined ? {} : { user: { id: user } }),
483
+ },
484
+ raw: envelope,
485
+ })
486
+ }
487
+
488
+ return undefined
489
+ }