@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/lib/index.js ADDED
@@ -0,0 +1,2659 @@
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { Adapter, ElementRegistry, PlatformError, Status, defineMode, h, normalize } from "@deepseek-ai/cordis-plugin-im-core";
3
+ import { isPhrasingContainer } from "@deepseek-ai/satori-element";
4
+ import { createHmac, timingSafeEqual } from "node:crypto";
5
+ // \0rolldown/runtime.js
6
+ var __defProp = Object.defineProperty;
7
+ var __exportAll = (all, no_symbols) => {
8
+ let target = {};
9
+ for (var name in all) __defProp(target, name, {
10
+ get: all[name],
11
+ enumerable: true
12
+ });
13
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
14
+ return target;
15
+ };
16
+ // lib/types/config.js
17
+ /** Validated Slack adapter configuration. */
18
+ const Config = z.object({
19
+ selfId: z.string().required(),
20
+ botToken: z.string().role("secret").required(),
21
+ token: z.string().role("secret").default(""),
22
+ signing: z.string().role("secret").default(""),
23
+ protocol: z.union(["ws", "http"]).required(),
24
+ path: z.string().default("/slack"),
25
+ apiBaseUrl: z.string().role("url").default("https://slack.com/api"),
26
+ replyBroadcast: z.boolean().default(false),
27
+ ws: z.object({
28
+ retryTimes: z.natural().default(6),
29
+ retryInterval: z.natural().role("ms").default(5e3),
30
+ retryLazy: z.natural().role("ms").default(6e4)
31
+ }).default({})
32
+ });
33
+ /**
34
+ * The configuration the selected protocol cannot work from.
35
+ *
36
+ * The two transports need different credentials: Socket Mode dials with the app-level token, the Events API verifies
37
+ * with the signing secret. A profile that leaves the needed one out is refused when the plugin loads, not when the
38
+ * first dial or the first callback fails.
39
+ *
40
+ * @param config - the validated configuration.
41
+ * @returns the configuration error, or undefined when the selection is complete.
42
+ */
43
+ function configError(config) {
44
+ if (config.selfId === "") return /* @__PURE__ */ new Error("slack: selfId is required (the bot user id \"U…\"; read it from auth.test)");
45
+ if (config.botToken === "") return /* @__PURE__ */ new Error("slack: botToken is required (the \"xoxb-…\" bot token)");
46
+ if (config.protocol === "ws" && config.token === "") return /* @__PURE__ */ new Error("slack: protocol \"ws\" needs token (the \"xapp-…\" app-level token for apps.connections.open)");
47
+ if (config.protocol === "http" && config.signing === "") return /* @__PURE__ */ new Error("slack: protocol \"http\" needs signing (the Events API signing secret)");
48
+ }
49
+ /**
50
+ * Normalize an inbound route path: absolute, no trailing slash.
51
+ * @param path - the configured `path`.
52
+ * @returns the pathname to register.
53
+ */
54
+ function routePath(path) {
55
+ const withSlash = path.startsWith("/") ? path : `/${path}`;
56
+ return withSlash.length > 1 ? withSlash.replace(/\/+$/, "") : withSlash;
57
+ }
58
+ // lib/types/errors.js
59
+ /**
60
+ * Slack failures and their mapping onto the core platform taxonomy.
61
+ *
62
+ * A Slack Web API answer reports failure in two unrelated ways: an HTTP status (429 with `Retry-After`, 5xx, a
63
+ * transport failure that produced no status at all) and a JSON envelope that says `ok: false` with a symbolic `error`.
64
+ * Only the second is a certain refusal; the first can leave the outcome unknown, so the two are classified separately.
65
+ */
66
+ /** One failed Slack Web API call. */
67
+ var SlackApiError = class extends Error {
68
+ method;
69
+ status;
70
+ code;
71
+ retryAfterMs;
72
+ constructor(message, init) {
73
+ super(message, init.cause === void 0 ? void 0 : { cause: init.cause });
74
+ this.name = "SlackApiError";
75
+ this.method = init.method;
76
+ this.status = init.status ?? 0;
77
+ this.code = init.code;
78
+ this.retryAfterMs = init.retryAfterMs;
79
+ }
80
+ };
81
+ /** Whether a caught value is the abort error of a cancelled request. */
82
+ function isAbortError$1(error) {
83
+ return (error instanceof Error || error instanceof DOMException) && error.name === "AbortError";
84
+ }
85
+ /**
86
+ * A refusal that only an account or app change can fix.
87
+ *
88
+ * The socket transport stops its reconnect loop on one of these instead of dialing again, because the same credential
89
+ * would be refused again.
90
+ */
91
+ var SlackFatalError = class extends Error {
92
+ constructor(message, options = {}) {
93
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
94
+ this.name = "SlackFatalError";
95
+ }
96
+ };
97
+ const RATE_LIMIT = /* @__PURE__ */ new Set(["ratelimited", "rate_limited"]);
98
+ const RETRYABLE_UNKNOWN = /* @__PURE__ */ new Set([
99
+ "fatal_error",
100
+ "internal_error",
101
+ "service_unavailable",
102
+ "request_timeout"
103
+ ]);
104
+ const PERMISSION = /* @__PURE__ */ new Set([
105
+ "not_authed",
106
+ "invalid_auth",
107
+ "token_expired",
108
+ "token_revoked",
109
+ "account_inactive",
110
+ "not_allowed_token_type",
111
+ "missing_scope",
112
+ "no_permission",
113
+ "not_in_channel",
114
+ "ekm_access_denied",
115
+ "team_access_not_granted",
116
+ "org_login_required",
117
+ "enterprise_is_restricted",
118
+ "two_factor_setup_required",
119
+ "messages_tab_disabled",
120
+ "posting_to_channel_denied"
121
+ ]);
122
+ const NOT_FOUND = /* @__PURE__ */ new Set([
123
+ "channel_not_found",
124
+ "invalid_channel_id",
125
+ "message_not_found",
126
+ "team_not_found",
127
+ "file_not_found",
128
+ "file_is_deleted",
129
+ "file_deleted"
130
+ ]);
131
+ const LIMIT = /* @__PURE__ */ new Set([
132
+ "no_text",
133
+ "msg_too_long",
134
+ "msg_blocks_too_long",
135
+ "too_many_attachments",
136
+ "too_many_contact_cards",
137
+ "attachment_payload_limit_exceeded",
138
+ "message_limit_exceeded"
139
+ ]);
140
+ const INVALID = /* @__PURE__ */ new Set([
141
+ "invalid_arguments",
142
+ "invalid_arg_name",
143
+ "invalid_array_arg",
144
+ "invalid_blocks",
145
+ "invalid_blocks_format",
146
+ "invalid_attachments",
147
+ "invalid_form_data",
148
+ "invalid_post_type",
149
+ "invalid_charset",
150
+ "invalid_name",
151
+ "missing_argument",
152
+ "missing_post_type",
153
+ "cant_broadcast_message",
154
+ "is_inactive",
155
+ "is_archived",
156
+ "duplicate_channel_not_found",
157
+ "duplicate_message_not_found",
158
+ "deprecated_endpoint",
159
+ "method_deprecated",
160
+ "restricted_action_thread_only_channel",
161
+ "restricted_action_read_only_channel",
162
+ "restricted_action_non_threadable_channel",
163
+ "restricted_action_thread_locked"
164
+ ]);
165
+ /**
166
+ * Classify one Slack `error` code.
167
+ *
168
+ * A code the platform documented as "the operation may have partly succeeded" leaves the outcome unknown; every other
169
+ * listed code was refused before anything was written. An unlisted code is not guessed: it is retryable with an
170
+ * unknown outcome, because turning it into a safe retry would duplicate a message the platform may have accepted.
171
+ *
172
+ * @param code - Slack's `error` string.
173
+ * @returns the platform error kind and whether anything was published.
174
+ */
175
+ function classifyCode(code) {
176
+ if (RATE_LIMIT.has(code)) return {
177
+ kind: "rate-limit",
178
+ published: "no"
179
+ };
180
+ if (RETRYABLE_UNKNOWN.has(code)) return {
181
+ kind: "retryable",
182
+ published: "unknown"
183
+ };
184
+ if (PERMISSION.has(code)) return {
185
+ kind: "permission",
186
+ published: "no"
187
+ };
188
+ if (NOT_FOUND.has(code)) return {
189
+ kind: "not-found",
190
+ published: "no"
191
+ };
192
+ if (LIMIT.has(code)) return {
193
+ kind: "limit",
194
+ published: "no"
195
+ };
196
+ if (INVALID.has(code)) return {
197
+ kind: "invalid",
198
+ published: "no"
199
+ };
200
+ if (code.startsWith("restricted_action")) return {
201
+ kind: "permission",
202
+ published: "no"
203
+ };
204
+ return {
205
+ kind: "retryable",
206
+ published: "unknown"
207
+ };
208
+ }
209
+ /**
210
+ * Map any Slack failure onto the core platform taxonomy.
211
+ *
212
+ * @param error - the caught failure.
213
+ * @returns the classified platform error.
214
+ */
215
+ function classifySlackError(error) {
216
+ if (error instanceof PlatformError) return error;
217
+ if (isAbortError$1(error)) return new PlatformError("fatal", error instanceof Error ? error.message : "slack request aborted", {
218
+ published: "unknown",
219
+ cause: error
220
+ });
221
+ if (error instanceof SlackApiError) {
222
+ const init = {
223
+ ...error.code === void 0 ? {} : { code: error.code },
224
+ ...error.retryAfterMs === void 0 ? {} : { retryAfterMs: error.retryAfterMs },
225
+ cause: error
226
+ };
227
+ if (error.status === 429) return new PlatformError("rate-limit", error.message, {
228
+ ...init,
229
+ published: "no"
230
+ });
231
+ if (error.code !== void 0) {
232
+ const verdict = classifyCode(error.code);
233
+ return new PlatformError(verdict.kind, error.message, {
234
+ ...init,
235
+ published: verdict.published
236
+ });
237
+ }
238
+ if (error.status >= 500) return new PlatformError("retryable", error.message, {
239
+ ...init,
240
+ published: "unknown"
241
+ });
242
+ if (error.status >= 400) return new PlatformError("invalid", error.message, {
243
+ ...init,
244
+ published: "no"
245
+ });
246
+ return new PlatformError("retryable", error.message, {
247
+ ...init,
248
+ published: "unknown"
249
+ });
250
+ }
251
+ const message = error instanceof Error ? error.message : String(error);
252
+ return new PlatformError("retryable", `slack request failed: ${message}`, {
253
+ published: "unknown",
254
+ cause: error
255
+ });
256
+ }
257
+ // lib/types/request.js
258
+ /**
259
+ * Slack Web API transport: one request path for every method the adapter calls, the `ok` envelope, `Retry-After`,
260
+ * credential-scoped file downloads and the two-step file upload.
261
+ *
262
+ * The migrated `Internal` class in `types/internal.ts` keeps the complete documented method surface for
263
+ * `bot.internal`; the adapter's own calls go through this module because `Internal` hands back the parsed envelope
264
+ * only, while classification needs the one thing the envelope does not carry: the HTTP status and `Retry-After` of a
265
+ * 429 answer.
266
+ */
267
+ /**
268
+ * The endpoints the adapter calls, keyed by method name.
269
+ *
270
+ * The method → path/method/body mapping is the one `Internal.define` installs for the migrated declarations; the two
271
+ * `files.*` upload methods are absent from those 2023 declarations, so their entries are the current API's.
272
+ */
273
+ const ROUTES = {
274
+ authTest: {
275
+ path: "/auth.test",
276
+ method: "GET",
277
+ json: false
278
+ },
279
+ appsConnectionsOpen: {
280
+ path: "/apps.connections.open",
281
+ method: "POST",
282
+ json: false
283
+ },
284
+ chatDelete: {
285
+ path: "/chat.delete",
286
+ method: "POST",
287
+ json: true
288
+ },
289
+ chatPostMessage: {
290
+ path: "/chat.postMessage",
291
+ method: "POST",
292
+ json: true
293
+ },
294
+ conversationsHistory: {
295
+ path: "/conversations.history",
296
+ method: "GET",
297
+ json: false
298
+ },
299
+ filesInfo: {
300
+ path: "/files.info",
301
+ method: "GET",
302
+ json: false
303
+ },
304
+ reactionsAdd: {
305
+ path: "/reactions.add",
306
+ method: "POST",
307
+ json: true
308
+ },
309
+ reactionsRemove: {
310
+ path: "/reactions.remove",
311
+ method: "POST",
312
+ json: true
313
+ },
314
+ usersList: {
315
+ path: "/users.list",
316
+ method: "GET",
317
+ json: false
318
+ },
319
+ getUploadUrlExternal: {
320
+ path: "/files.getUploadURLExternal",
321
+ method: "POST",
322
+ json: false
323
+ },
324
+ completeUploadExternal: {
325
+ path: "/files.completeUploadExternal",
326
+ method: "POST",
327
+ json: false
328
+ }
329
+ };
330
+ /**
331
+ * Build the request endpoints of one bot.
332
+ * @param ctx - the context whose `http` service performs the requests.
333
+ * @param config - `apiBaseUrl` of the profile row.
334
+ * @param botToken - the bot token.
335
+ * @param appToken - the app-level token.
336
+ * @returns the request dependencies, shared by every call of the bot.
337
+ */
338
+ function createSlackApi(ctx, config) {
339
+ return {
340
+ ctx,
341
+ base: config.apiBaseUrl.replace(/\/+$/, ""),
342
+ botToken: config.botToken,
343
+ appToken: config.token
344
+ };
345
+ }
346
+ /**
347
+ * A request body encoded as form fields; an array becomes its JSON text, as Slack's file methods expect.
348
+ * @param params - the request body.
349
+ * @returns the body to send with `application/x-www-form-urlencoded`.
350
+ */
351
+ function encodeForm(params) {
352
+ const form = new URLSearchParams();
353
+ for (const [key, value] of Object.entries(params)) {
354
+ if (value === void 0 || value === null) continue;
355
+ form.append(key, typeof value === "object" ? JSON.stringify(value) : String(value));
356
+ }
357
+ return form;
358
+ }
359
+ /** Whether a caught value is the abort error of a cancelled request. */
360
+ function isAbortError(error) {
361
+ return (error instanceof Error || error instanceof DOMException) && error.name === "AbortError";
362
+ }
363
+ /**
364
+ * `Retry-After` of a 429 answer, in milliseconds.
365
+ * @param response - the answer.
366
+ * @returns the delay in milliseconds, or undefined when the header is absent or unreadable.
367
+ */
368
+ function retryAfterOf(response) {
369
+ const header = response.headers.get("retry-after");
370
+ if (header === null) return void 0;
371
+ const seconds = Number(header);
372
+ if (!Number.isFinite(seconds) || seconds < 0) return void 0;
373
+ return seconds * 1e3;
374
+ }
375
+ /** Read a JSON answer; an unreadable body is reported as absence rather than a parse error. */
376
+ async function jsonOf(response) {
377
+ let body;
378
+ try {
379
+ body = await response.json();
380
+ } catch (error) {
381
+ return;
382
+ }
383
+ if (typeof body !== "object" || body === null) return void 0;
384
+ return body;
385
+ }
386
+ /**
387
+ * Refuse an answer that does not say `ok: true`.
388
+ *
389
+ * `Internal` hands the raw envelope back, so every call site used to have to remember this check. A successful answer
390
+ * may still carry a warning (`message_truncated`), which is logged: the text was accepted but shortened, so it is not
391
+ * an error and must not fail the send.
392
+ *
393
+ * @param api - the request dependencies, for the logger.
394
+ * @param method - Slack method name, for the message.
395
+ * @param body - the parsed envelope.
396
+ * @param status - HTTP status of the answer.
397
+ * @returns the same envelope, for the caller to read its payload.
398
+ * @throws SlackApiError when the platform refused the call.
399
+ */
400
+ function ensureOk(api, method, body, status = 200) {
401
+ const name = ROUTES[method].path.slice(1);
402
+ if (body.ok !== true) throw new SlackApiError(`slack ${name} failed: ${body.error ?? "the answer does not say ok"}`, {
403
+ method: name,
404
+ status,
405
+ ...body.error === void 0 ? {} : { code: body.error }
406
+ });
407
+ const warnings = [...body.warning === void 0 ? [] : [body.warning], ...body.response_metadata?.warnings ?? []];
408
+ if (warnings.length > 0) api.ctx.logger.warn("slack %s answered warnings: %s", name, warnings.join(", "));
409
+ return body;
410
+ }
411
+ /**
412
+ * Call one Web API method and return its `ok: true` answer.
413
+ *
414
+ * @param api - the request dependencies.
415
+ * @param method - Slack method name.
416
+ * @param params - query parameters of a GET, or the request body.
417
+ * @param options - app-token selection and cancellation.
418
+ * @returns the parsed answer.
419
+ * @throws SlackApiError for a status, a refusal or an unreadable answer.
420
+ */
421
+ async function callApi(api, method, params = {}, options = {}) {
422
+ const route = ROUTES[method];
423
+ const token = options.app === true ? api.appToken : api.botToken;
424
+ const config = {
425
+ method: route.method,
426
+ headers: { authorization: `Bearer ${token}` },
427
+ ...options.signal === void 0 ? {} : { signal: options.signal }
428
+ };
429
+ if (route.method === "GET") config.params = params;
430
+ else if (route.json) config.data = params;
431
+ else {
432
+ config.data = encodeForm(params);
433
+ config.headers = {
434
+ ...config.headers,
435
+ "content-type": "application/x-www-form-urlencoded"
436
+ };
437
+ }
438
+ let response;
439
+ try {
440
+ response = await api.ctx.http(`${api.base}${route.path}`, config);
441
+ } catch (cause) {
442
+ if (options.signal?.aborted === true) throw options.signal.reason;
443
+ if (isAbortError(cause)) throw cause;
444
+ throw new SlackApiError(`slack ${route.path.slice(1)} request failed`, {
445
+ method: route.path.slice(1),
446
+ cause
447
+ });
448
+ }
449
+ const status = response.status;
450
+ const retryAfterMs = retryAfterOf(response);
451
+ const body = await jsonOf(response);
452
+ if (body === void 0) throw new SlackApiError(`slack ${route.path.slice(1)} answered ${status} without a JSON envelope`, {
453
+ method: route.path.slice(1),
454
+ status,
455
+ ...retryAfterMs === void 0 ? {} : { retryAfterMs }
456
+ });
457
+ if (status === 429) throw new SlackApiError(`slack ${route.path.slice(1)} was rate limited`, {
458
+ method: route.path.slice(1),
459
+ status,
460
+ ...body.error === void 0 ? {} : { code: body.error },
461
+ ...retryAfterMs === void 0 ? {} : { retryAfterMs }
462
+ });
463
+ return ensureOk(api, method, { ...body }, status);
464
+ }
465
+ /**
466
+ * Whether a URL names a host the bot token may be sent to.
467
+ *
468
+ * Slack's guidance is to never send the credentials to a host outside Slack, and a `url_private` of a remote file
469
+ * names an external host. The comparison is exact on the parsed hostname: `files.slack.com.evil.example` and
470
+ * `evil-slack.com` are both refused, and plain HTTP is refused because the token would travel unencrypted.
471
+ *
472
+ * @param url - the file URL.
473
+ * @returns whether the bot token may be presented to it.
474
+ */
475
+ function isSlackFileUrl(url) {
476
+ if (url.protocol !== "https:") return false;
477
+ const host = url.hostname.toLowerCase();
478
+ return host === "slack.com" || host.endsWith(".slack.com");
479
+ }
480
+ /**
481
+ * Download one Slack-hosted file with the bot token.
482
+ *
483
+ * @param api - the request dependencies.
484
+ * @param src - `url_private` of a `files.info` answer.
485
+ * @param signal - cancellation.
486
+ * @returns the response whose body is the file.
487
+ * @throws SlackApiError when the host is not a Slack file host.
488
+ */
489
+ async function downloadFile(api, src, signal) {
490
+ let url;
491
+ try {
492
+ url = new URL(src);
493
+ } catch (cause) {
494
+ throw new SlackApiError(`slack: "${src}" is not a URL`, {
495
+ method: "files.info",
496
+ cause
497
+ });
498
+ }
499
+ if (!isSlackFileUrl(url)) throw new SlackApiError(`slack: refusing to send the bot token to ${url.hostname}`, { method: "files.info" });
500
+ try {
501
+ return await api.ctx.http(url, {
502
+ headers: { authorization: `Bearer ${api.botToken}` },
503
+ ...signal === void 0 ? {} : { signal }
504
+ });
505
+ } catch (cause) {
506
+ if (signal?.aborted === true) throw signal.reason;
507
+ if (isAbortError(cause)) throw cause;
508
+ throw new SlackApiError("slack file download failed", {
509
+ method: "files.info",
510
+ cause
511
+ });
512
+ }
513
+ }
514
+ /**
515
+ * Ask for the upload URL and the file id (`files.getUploadURLExternal`).
516
+ * @param api - the request dependencies.
517
+ * @param file - name and byte length the platform records.
518
+ * @param signal - cancellation.
519
+ * @returns the ticket of the byte upload.
520
+ */
521
+ async function startUpload(api, file, signal) {
522
+ const answer = await callApi(api, "getUploadUrlExternal", {
523
+ filename: file.name,
524
+ length: file.length
525
+ }, signal === void 0 ? {} : { signal });
526
+ if (answer.upload_url === void 0 || answer.file_id === void 0) throw new SlackApiError("slack files.getUploadURLExternal answered without upload_url/file_id", { method: "getUploadUrlExternal" });
527
+ return {
528
+ uploadUrl: answer.upload_url,
529
+ fileId: answer.file_id
530
+ };
531
+ }
532
+ /**
533
+ * Upload the bytes to the ticket's URL.
534
+ *
535
+ * The URL is pre-signed, so no credential travels with it; the answer is plain text (`OK - <size>`), so a 2xx is the
536
+ * whole success signal.
537
+ *
538
+ * @param api - the request dependencies.
539
+ * @param ticket - what {@link startUpload} returned.
540
+ * @param data - the file bytes.
541
+ * @param signal - cancellation.
542
+ */
543
+ async function putUploadBytes(api, ticket, data, signal) {
544
+ let response;
545
+ try {
546
+ response = await api.ctx.http(ticket.uploadUrl, {
547
+ method: "POST",
548
+ headers: { "content-type": "application/octet-stream" },
549
+ data,
550
+ ...signal === void 0 ? {} : { signal }
551
+ });
552
+ } catch (cause) {
553
+ if (signal?.aborted === true) throw signal.reason;
554
+ if (isAbortError(cause)) throw cause;
555
+ throw new SlackApiError("slack file upload failed", {
556
+ method: "getUploadUrlExternal",
557
+ cause
558
+ });
559
+ }
560
+ if (!response.ok) throw new SlackApiError(`slack file upload answered ${response.status}`, {
561
+ method: "getUploadUrlExternal",
562
+ status: response.status
563
+ });
564
+ }
565
+ /**
566
+ * Share an uploaded file into a channel (`files.completeUploadExternal`).
567
+ * @param api - the request dependencies.
568
+ * @param files - ids and titles to share.
569
+ * @param channel - channel the file message appears in.
570
+ * @param threadTs - thread to post the file into, when the message answers a thread.
571
+ * @param signal - cancellation.
572
+ * @returns the shared files, from which the message timestamp is read.
573
+ */
574
+ async function finishUpload(api, files, channel, threadTs, signal) {
575
+ return (await callApi(api, "completeUploadExternal", {
576
+ files: [...files],
577
+ channel_id: channel,
578
+ ...threadTs === void 0 ? {} : { thread_ts: threadTs }
579
+ }, signal === void 0 ? {} : { signal })).files ?? [];
580
+ }
581
+ // lib/types/identity.js
582
+ /** The configured `selfId` and the account the bot token belongs to disagree. */
583
+ var SlackIdentityError = class extends Error {
584
+ constructor(message) {
585
+ super(message);
586
+ this.name = "SlackIdentityError";
587
+ }
588
+ };
589
+ /**
590
+ * Compare `auth.test.user_id` with the configured account.
591
+ *
592
+ * The bot user id of a Slack app is not part of its token, so it has to be configured; a mismatch is a configuration
593
+ * error that reconnecting cannot fix, and the id the host keys everything on (`ctx.bots`, `sources.bot`, the intake
594
+ * dedupe key) would be wrong for every message.
595
+ *
596
+ * @param api - the request dependencies.
597
+ * @param selfId - the configured bot user id.
598
+ * @returns the identity of the matching account.
599
+ * @throws SlackIdentityError when the token belongs to another account.
600
+ */
601
+ async function verifyIdentity(api, selfId) {
602
+ const answer = await callApi(api, "authTest");
603
+ const userId = answer.user_id ?? "";
604
+ if (userId !== selfId) throw new SlackIdentityError(`slack: selfId is configured as ${selfId} but the bot token belongs to ${userId === "" ? "an unknown user" : userId}; fix selfId and restart`);
605
+ return {
606
+ userId,
607
+ userName: answer.user ?? "",
608
+ teamId: answer.team_id ?? "",
609
+ teamName: answer.team ?? "",
610
+ ...answer.bot_id === void 0 ? {} : { botId: answer.bot_id }
611
+ };
612
+ }
613
+ // lib/types/mrkdwn.js
614
+ /**
615
+ * The `mrkdwn` escaping rules of the upstream adapter and the inbound parser of the same syntax.
616
+ *
617
+ * Slack's message text is a small markup language, not plain text: `*bold*`, `_italic_`, `~strike~`, `` `code` ``,
618
+ * `<@U…>` mentions, `<#C…>` channel links, `<url|label>` links and `:emoji:` names. Outbound, every literal character
619
+ * that would otherwise be read as markup is escaped with a zero-width space; inbound, the same markers are parsed back
620
+ * into the element vocabulary.
621
+ */
622
+ /** Zero-width space put in front of a markup character; it is invisible and keeps the character literal. */
623
+ const MARK_ESCAPE = "​";
624
+ /** Hair space put in front of a leading `>`; a quoted block is started by `>` at the beginning of a line. */
625
+ const QUOTE_ESCAPE = " ";
626
+ /**
627
+ * Escape text so Slack renders it literally.
628
+ *
629
+ * Four rules, identical to the upstream adapter's: a markup character gets a zero-width space; `@everyone`/`@here`
630
+ * are broken up so they cannot notify; a leading `>` cannot start a quoted block; and `<…>` cannot become a link or a
631
+ * mention. The result keeps every visible character and adds only invisible ones.
632
+ *
633
+ * @param text - the text of a `text` element.
634
+ * @returns the text to append to the message body.
635
+ */
636
+ function escape(text) {
637
+ return text.replace(/(?<!\u200B)[*_~`]/g, `${MARK_ESCAPE}$&`).replace(/@everyone/g, () => `@${MARK_ESCAPE}everyone`).replace(/@here/g, () => `@${MARK_ESCAPE}here`).replace(/(?<!\u200B)^>/g, `${QUOTE_ESCAPE}&gt;`).replace(/<(.*?)>/g, "&lt;$1&gt;");
638
+ }
639
+ /**
640
+ * Undo {@link escape}: restore the markup characters, the notification words and a leading `>`.
641
+ *
642
+ * Slack hands back the text of a message as its author typed it, so a zero-width space only appears when the text was
643
+ * written by an adapter of this family; parsing it back is what keeps a relayed message identical.
644
+ *
645
+ * @param text - text of one rich-text run.
646
+ * @returns the text as it was written.
647
+ */
648
+ function unescape(text) {
649
+ return text.replace(/\u200B([*_~`])/g, "$1").replace(new RegExp(`@${MARK_ESCAPE}everyone`, "g"), () => "@everyone").replace(new RegExp(`@${MARK_ESCAPE}here`, "g"), () => "@here").replace(new RegExp(`^${QUOTE_ESCAPE}&gt;`), ">");
650
+ }
651
+ /** A Slack control sequence between angle brackets, e.g. `<@U123>` or `<https://example.com|label>`. */
652
+ const CONTROL = /(<[^<>]*>)/;
653
+ /** An emoji name between colons, e.g. `:tada:` or `:+1:`. */
654
+ const EMOJI = /(:[a-zA-Z0-9_+-]+:)/;
655
+ /** The label of a mention or channel link, when Slack included one (`<@U123|alice>`). */
656
+ function labelOf(raw, prefixLength) {
657
+ const body = raw.slice(prefixLength, -1);
658
+ const separator = body.indexOf("|");
659
+ if (separator < 0) return { id: body };
660
+ return {
661
+ id: body.slice(0, separator),
662
+ ...body.slice(separator + 1) === "" ? {} : { name: body.slice(separator + 1) }
663
+ };
664
+ }
665
+ /** Turn one `<…>` control sequence into elements; an unrecognized one stays as its literal text. */
666
+ function controlElement(raw) {
667
+ const body = raw.slice(1, -1);
668
+ if (body.startsWith("@")) {
669
+ const { id, name } = labelOf(raw, 2);
670
+ return [h("at", {
671
+ type: "user",
672
+ id,
673
+ ...name === void 0 ? {} : { name }
674
+ })];
675
+ }
676
+ if (body.startsWith("#")) {
677
+ const { id, name } = labelOf(raw, 2);
678
+ return [h("channel", {
679
+ id,
680
+ ...name === void 0 ? {} : { name }
681
+ })];
682
+ }
683
+ if (body.startsWith("!")) {
684
+ const range = body.slice(1);
685
+ if (range === "here") return [h("at", { type: "here" })];
686
+ if (range === "channel" || range === "everyone") return [h("at", { type: "all" })];
687
+ return [h.text(raw)];
688
+ }
689
+ const separator = body.indexOf("|");
690
+ if (separator > 0) {
691
+ const href = body.slice(0, separator);
692
+ const label = body.slice(separator + 1);
693
+ return [h("a", { href }, label === "" ? href : label)];
694
+ }
695
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(body)) return [h("a", { href: body }, body)];
696
+ return [h.text(raw)];
697
+ }
698
+ /** Split one plain run on emoji names, keeping the text between them. */
699
+ function emojiElements(text) {
700
+ const parts = text.split(EMOJI);
701
+ const elements = [];
702
+ for (const part of parts) {
703
+ if (part === "") continue;
704
+ if (part.length > 2 && part.startsWith(":") && part.endsWith(":")) {
705
+ const name = part.slice(1, -1);
706
+ elements.push(h("emoji", {
707
+ id: name,
708
+ name
709
+ }));
710
+ continue;
711
+ }
712
+ elements.push(h.text(unescape(part)));
713
+ }
714
+ return elements;
715
+ }
716
+ /**
717
+ * Parse Slack message text into the element vocabulary.
718
+ *
719
+ * Used for the `text` field of a message (when it carries no usable `blocks`), for the `text` of a `section` block,
720
+ * and for a `rich_text_quote`/`rich_text_preformatted` body.
721
+ *
722
+ * @param text - Slack message text.
723
+ * @returns the content nodes; empty when the text is empty.
724
+ */
725
+ function parseMrkdwn(text) {
726
+ const elements = [];
727
+ for (const part of text.split(CONTROL)) {
728
+ if (part === "") continue;
729
+ if (part.startsWith("<") && part.endsWith(">") && part.length > 2) {
730
+ elements.push(...controlElement(part));
731
+ continue;
732
+ }
733
+ elements.push(...emojiElements(part));
734
+ }
735
+ return elements;
736
+ }
737
+ // lib/types/modes/shared.js
738
+ /**
739
+ * Draft model of the single `mrkdwn` mode: the node stream, the paragraph and media splitting, the 4,000-character
740
+ * split that never loses a character, and the exact request payload of one platform message.
741
+ *
742
+ * A run keeps its markup as data (`marks`) instead of embedding it in the text. That is what makes splitting exact: a
743
+ * cut closes the open markers and reopens them in the next chunk, because the markers are not part of the text being
744
+ * counted.
745
+ */
746
+ /** Slack's documented `text` bound: longer text is split into messages of about that size. */
747
+ const SLACK_LIMITS = { text: 4e3 };
748
+ /** A paragraph break node. */
749
+ const BREAK = { type: "break" };
750
+ /**
751
+ * Drop the paragraph break a container put in front of its content, so a list marker is not followed by a newline.
752
+ * @param nodes - rendered children.
753
+ * @returns the children without leading break nodes.
754
+ */
755
+ function withoutLeadingBreaks(nodes) {
756
+ let start = 0;
757
+ while (start < nodes.length && nodes[start].type === "break") start += 1;
758
+ return nodes.slice(start);
759
+ }
760
+ /**
761
+ * One text node under the given marks.
762
+ * @param text - the already escaped text.
763
+ * @param marks - the marks wrapping it, outermost first.
764
+ * @returns the node.
765
+ */
766
+ function textNode(text, marks = []) {
767
+ return {
768
+ type: "text",
769
+ run: {
770
+ text,
771
+ marks
772
+ }
773
+ };
774
+ }
775
+ /** Identity of one mark, for comparing two stacks. */
776
+ function markKey(mark) {
777
+ switch (mark.kind) {
778
+ case "link": return `link:${mark.href}`;
779
+ case "fence": return `fence:${mark.lang ?? ""}`;
780
+ default: return mark.kind;
781
+ }
782
+ }
783
+ /**
784
+ * Wrap every text run of a subtree with one mark.
785
+ *
786
+ * A run already carrying the same mark right above it is left alone, so `<b><b>x</b></b>` does not emit `**x**`.
787
+ *
788
+ * @param nodes - rendered children.
789
+ * @param mark - the mark to add.
790
+ * @returns the children with the mark added to their text runs.
791
+ */
792
+ function withMark(nodes, mark) {
793
+ const key = markKey(mark);
794
+ return nodes.map((node) => {
795
+ if (node.type !== "text") return node;
796
+ const { marks } = node.run;
797
+ const last = marks[marks.length - 1];
798
+ if (last !== void 0 && markKey(last) === key) return node;
799
+ return {
800
+ type: "text",
801
+ run: {
802
+ text: node.run.text,
803
+ marks: [...marks, mark]
804
+ }
805
+ };
806
+ });
807
+ }
808
+ /** The opening marker of one mark. */
809
+ function markOpen(mark) {
810
+ switch (mark.kind) {
811
+ case "bold": return "*";
812
+ case "italic": return "_";
813
+ case "strike": return "~";
814
+ case "code": return "`";
815
+ case "link": return `<${mark.href}|`;
816
+ case "fence": return `\`\`\`${mark.lang ?? ""}\n`;
817
+ }
818
+ }
819
+ /** The closing marker of one mark. */
820
+ function markClose(mark) {
821
+ switch (mark.kind) {
822
+ case "link": return ">";
823
+ case "fence": return "\n```";
824
+ default: return markOpen(mark);
825
+ }
826
+ }
827
+ /** How many marks two stacks share from the outside in. */
828
+ function sharedMarks(left, right) {
829
+ const limit = Math.min(left.length, right.length);
830
+ for (let index = 0; index < limit; index++) if (markKey(left[index]) !== markKey(right[index])) return index;
831
+ return limit;
832
+ }
833
+ /**
834
+ * Render a run list as one message body, closing and reopening marks only where the stack changes.
835
+ * @param runs - the runs of one message.
836
+ * @returns the message body.
837
+ */
838
+ function renderRuns(runs) {
839
+ let body = "";
840
+ let open = [];
841
+ for (const run of runs) {
842
+ const shared = sharedMarks(open, run.marks);
843
+ for (let index = open.length - 1; index >= shared; index--) body += markClose(open[index]);
844
+ for (let index = shared; index < run.marks.length; index++) body += markOpen(run.marks[index]);
845
+ body += run.text;
846
+ open = run.marks;
847
+ }
848
+ for (let index = open.length - 1; index >= 0; index--) body += markClose(open[index]);
849
+ return body;
850
+ }
851
+ /** Visible characters of a run list: one per Unicode code point. */
852
+ function visibleLength(runs) {
853
+ let length = 0;
854
+ for (const run of runs) for (const _ of run.text) length += 1;
855
+ return length;
856
+ }
857
+ /** Canonical identity of a whole mark stack, for joining runs that render identically. */
858
+ function stackKey(marks) {
859
+ return marks.map(markKey).join("\0");
860
+ }
861
+ /** Fold an atom list back into runs, joining neighbours that share their whole stack. */
862
+ function runsOf(atoms) {
863
+ const runs = [];
864
+ let key = "";
865
+ for (const atom of atoms) {
866
+ const atomKey = stackKey(atom.marks);
867
+ const last = runs[runs.length - 1];
868
+ if (last !== void 0 && atomKey === key) {
869
+ last.text += atom.char;
870
+ continue;
871
+ }
872
+ runs.push({
873
+ text: atom.char,
874
+ marks: atom.marks
875
+ });
876
+ key = atomKey;
877
+ }
878
+ return runs;
879
+ }
880
+ /**
881
+ * Split a run list into chunks of at most `limit` visible characters.
882
+ *
883
+ * The cut prefers the last line break of the window, then the last space, then a hard cut; every chunk closes the
884
+ * marks it opened, so each message parses on its own. No visible character is ever dropped.
885
+ *
886
+ * @param runs - the whole message body.
887
+ * @param limit - visible characters per chunk.
888
+ * @returns the chunks, in order.
889
+ */
890
+ function splitRuns(runs, limit) {
891
+ if (visibleLength(runs) <= limit) return [[...runs]];
892
+ const atoms = [];
893
+ for (const run of runs) for (const char of run.text) atoms.push({
894
+ char,
895
+ marks: run.marks
896
+ });
897
+ const chunks = [];
898
+ let start = 0;
899
+ while (start < atoms.length) {
900
+ if (atoms.length - start <= limit) {
901
+ chunks.push(runsOf(atoms.slice(start)));
902
+ break;
903
+ }
904
+ const window = start + limit;
905
+ let cut = window;
906
+ for (let index = window - 1; index >= start; index--) if (atoms[index].char === "\n") {
907
+ cut = index + 1;
908
+ break;
909
+ }
910
+ if (cut === window) {
911
+ for (let index = window - 1; index >= start; index--) if (atoms[index].char === " ") {
912
+ cut = index + 1;
913
+ break;
914
+ }
915
+ }
916
+ chunks.push(runsOf(atoms.slice(start, cut)));
917
+ start = cut;
918
+ }
919
+ return chunks;
920
+ }
921
+ /**
922
+ * Fold the rendered node stream into platform messages.
923
+ *
924
+ * Inline nodes share one body; a media element flushes the body and becomes a message of its own, as the upstream
925
+ * encoder does. A paragraph break adds one newline and never starts a message with one, and the ends of every message
926
+ * are trimmed.
927
+ *
928
+ * @param nodes - rendered nodes in document order.
929
+ * @returns one draft per platform message; a single empty text draft when the content renders nothing.
930
+ */
931
+ function assembleDraft(nodes) {
932
+ const drafts = [];
933
+ let runs = [];
934
+ /** The runs without the whitespace around the message, which no mark wraps. */
935
+ const trimmed = (input) => {
936
+ const copy = input.map((run) => ({
937
+ text: run.text,
938
+ marks: run.marks
939
+ }));
940
+ while (copy.length > 0) {
941
+ const first = copy[0];
942
+ const text = first.text.replace(/^\s+/, "");
943
+ if (text !== "") {
944
+ first.text = text;
945
+ break;
946
+ }
947
+ copy.shift();
948
+ }
949
+ while (copy.length > 0) {
950
+ const last = copy[copy.length - 1];
951
+ const text = last.text.replace(/\s+$/, "");
952
+ if (text !== "") {
953
+ last.text = text;
954
+ break;
955
+ }
956
+ copy.pop();
957
+ }
958
+ return copy;
959
+ };
960
+ const flushText = () => {
961
+ if (runs.length === 0) return;
962
+ for (const chunk of splitRuns(runs, SLACK_LIMITS.text)) {
963
+ const trimmedRuns = trimmed(chunk);
964
+ if (trimmedRuns.length === 0) continue;
965
+ drafts.push({
966
+ type: "text",
967
+ text: renderRuns(trimmedRuns)
968
+ });
969
+ }
970
+ runs = [];
971
+ };
972
+ const append = (run) => {
973
+ const last = runs[runs.length - 1];
974
+ if (last !== void 0 && stackKey(last.marks) === stackKey(run.marks)) {
975
+ last.text += run.text;
976
+ return;
977
+ }
978
+ runs.push({
979
+ text: run.text,
980
+ marks: run.marks
981
+ });
982
+ };
983
+ const lineBreak = () => {
984
+ const last = runs[runs.length - 1];
985
+ if (last === void 0) return;
986
+ if (last.text.endsWith("\n")) return;
987
+ append({
988
+ text: "\n",
989
+ marks: []
990
+ });
991
+ };
992
+ for (const node of nodes) switch (node.type) {
993
+ case "text":
994
+ append(node.run);
995
+ break;
996
+ case "break":
997
+ lineBreak();
998
+ break;
999
+ case "media":
1000
+ flushText();
1001
+ drafts.push({
1002
+ type: "file",
1003
+ ref: node.ref,
1004
+ name: node.name
1005
+ });
1006
+ }
1007
+ flushText();
1008
+ if (drafts.length === 0) drafts.push({
1009
+ type: "text",
1010
+ text: ""
1011
+ });
1012
+ return drafts;
1013
+ }
1014
+ /** The file name of an outbound attachment: the declared name, else the last path segment of the source. */
1015
+ function fileName(name, src) {
1016
+ if (name !== void 0 && name !== "") return name;
1017
+ try {
1018
+ const path = new URL(src).pathname;
1019
+ const segment = path.slice(path.lastIndexOf("/") + 1);
1020
+ if (segment !== "") return decodeURIComponent(segment);
1021
+ } catch (error) {
1022
+ if (src !== "" && !src.includes("/")) return src;
1023
+ }
1024
+ return "file";
1025
+ }
1026
+ /**
1027
+ * The attachment node of one media element.
1028
+ * @param el - one of `img`, `audio`, `video`, `file`.
1029
+ * @param ctx - render context of the mode.
1030
+ * @returns the node to publish after the body it was found in.
1031
+ */
1032
+ function mediaNode(el, ctx) {
1033
+ const parent = ctx.ancestors[ctx.ancestors.length - 1];
1034
+ if (parent !== void 0 && isPhrasingContainer(parent.type)) ctx.report.moved.push({
1035
+ tag: el.type,
1036
+ reason: "slack-media-split",
1037
+ path: ctx.stableId(el)
1038
+ });
1039
+ switch (el.type) {
1040
+ case "img": return {
1041
+ type: "media",
1042
+ ref: ctx.resource("image", el.attrs.src, {}),
1043
+ name: fileName(void 0, el.attrs.src)
1044
+ };
1045
+ case "audio": return {
1046
+ type: "media",
1047
+ ref: ctx.resource("audio", el.attrs.src, el.attrs.name === void 0 ? {} : { name: el.attrs.name }),
1048
+ name: fileName(el.attrs.name, el.attrs.src)
1049
+ };
1050
+ case "video": return {
1051
+ type: "media",
1052
+ ref: ctx.resource("video", el.attrs.src, el.attrs.name === void 0 ? {} : { name: el.attrs.name }),
1053
+ name: fileName(el.attrs.name, el.attrs.src)
1054
+ };
1055
+ case "file": return {
1056
+ type: "media",
1057
+ ref: ctx.resource("file", el.attrs.src, el.attrs.name === void 0 ? {} : { name: el.attrs.name }),
1058
+ name: fileName(el.attrs.name, el.attrs.src)
1059
+ };
1060
+ }
1061
+ }
1062
+ /** The resource key `prepare` resolved for one attachment. */
1063
+ function resolvedKey(prepared, ref) {
1064
+ const resolved = prepared.resolved.get(ref);
1065
+ if (resolved === void 0) throw new Error("slack: the attachment was not prepared before serialize");
1066
+ return resolved.key;
1067
+ }
1068
+ /** `thread_ts` of an inbound referrer, when the target asks to follow it. */
1069
+ function referrerThreadTs(referrer) {
1070
+ if (typeof referrer !== "object" || referrer === null) return void 0;
1071
+ const threadTs = referrer.threadTs;
1072
+ return typeof threadTs === "string" && threadTs !== "" ? threadTs : void 0;
1073
+ }
1074
+ /**
1075
+ * The thread one part answers: an explicit thread, the referrer's thread, or — for the first part only — the quote.
1076
+ *
1077
+ * Slack's "reply to a message" is a thread reply, so a `<quote>` becomes `thread_ts`. Only the first part carries it,
1078
+ * because the later parts of a split message would otherwise start threads of their own.
1079
+ *
1080
+ * @param ctx - serialize context.
1081
+ * @returns the thread timestamp, when this part goes into a thread.
1082
+ */
1083
+ function threadTsOf(ctx) {
1084
+ if (typeof ctx.target.thread === "string") return ctx.target.thread;
1085
+ if (ctx.target.thread === true) return referrerThreadTs(ctx.target.referrer);
1086
+ return ctx.index === 0 ? ctx.quote : void 0;
1087
+ }
1088
+ /**
1089
+ * Build the exact request data of one draft.
1090
+ *
1091
+ * @param prepared - the draft with its resources resolved.
1092
+ * @param ctx - serialize context (channel, thread, part index).
1093
+ * @param replyBroadcast - `replyBroadcast` of the profile row.
1094
+ * @returns the request data of one platform message or file message.
1095
+ */
1096
+ function serializeDraft(prepared, ctx, replyBroadcast) {
1097
+ const { draft } = prepared;
1098
+ const channel = ctx.target.chat.id;
1099
+ const threadTs = threadTsOf(ctx);
1100
+ if (draft.type === "file") return {
1101
+ kind: "file",
1102
+ channel,
1103
+ fileId: resolvedKey(prepared, draft.ref),
1104
+ name: draft.name,
1105
+ ...threadTs === void 0 ? {} : { threadTs }
1106
+ };
1107
+ return {
1108
+ kind: "message",
1109
+ channel,
1110
+ text: draft.text === "" ? "⁠" : draft.text,
1111
+ ...threadTs === void 0 ? {} : { threadTs },
1112
+ ...threadTs !== void 0 && replyBroadcast ? { replyBroadcast: true } : {}
1113
+ };
1114
+ }
1115
+ // lib/types/modes/mrkdwn.js
1116
+ /**
1117
+ * The single `mrkdwn` mode: Slack message text with its mrkdwn markup.
1118
+ *
1119
+ * Native tags are the ones the upstream encoder writes (`text`, `p`, `br`, `b`, `i`, `s`, `code`, `a`, `at`, `channel`,
1120
+ * `emoji`) plus the block structure Slack renders as text (headings, lists, quotes, code fences, a divider) and the
1121
+ * attachments that travel as their own message. Everything else takes the core fallback, which keeps its text — the
1122
+ * platform has no way to render it, so there is no second mode to offer.
1123
+ */
1124
+ const BOLD = { kind: "bold" };
1125
+ const ITALIC = { kind: "italic" };
1126
+ const STRIKE = { kind: "strike" };
1127
+ const CODE = { kind: "code" };
1128
+ /** A heading: Slack has no heading syntax, so a bold line stands in. */
1129
+ function heading(nodes) {
1130
+ return [
1131
+ BREAK,
1132
+ ...withMark(nodes, BOLD),
1133
+ BREAK
1134
+ ];
1135
+ }
1136
+ /** A code block: a fenced block with the language on the opening fence line. */
1137
+ function fenced(nodes, lang) {
1138
+ return withMark([
1139
+ BREAK,
1140
+ ...nodes,
1141
+ BREAK
1142
+ ], lang === void 0 ? {
1143
+ kind: "fence",
1144
+ lang: void 0
1145
+ } : {
1146
+ kind: "fence",
1147
+ lang
1148
+ });
1149
+ }
1150
+ /** Prefix every line of a subtree with the quote marker. */
1151
+ function quoteLines(nodes) {
1152
+ const quoted = [];
1153
+ let atLineStart = true;
1154
+ for (const node of nodes) {
1155
+ if (node.type !== "text") {
1156
+ quoted.push(node);
1157
+ continue;
1158
+ }
1159
+ let text = "";
1160
+ for (const char of node.run.text) {
1161
+ if (atLineStart && char !== "\n") text += "> ";
1162
+ text += char;
1163
+ atLineStart = char === "\n";
1164
+ }
1165
+ quoted.push({
1166
+ type: "text",
1167
+ run: {
1168
+ text,
1169
+ marks: node.run.marks
1170
+ }
1171
+ });
1172
+ }
1173
+ return quoted;
1174
+ }
1175
+ /**
1176
+ * Build the `mrkdwn` mode.
1177
+ * @param replyBroadcast - `replyBroadcast` of the profile row.
1178
+ * @returns the only mode of this adapter.
1179
+ */
1180
+ function createMrkdwnMode(replyBroadcast) {
1181
+ const elements = new ElementRegistry().register("text", (el) => textNode(escape(el.attrs.content))).register("p", (el, ctx) => [
1182
+ BREAK,
1183
+ ...ctx.render(el.children),
1184
+ BREAK
1185
+ ]).register("br", () => textNode("\n")).register("b", (el, ctx) => withMark(ctx.render(el.children), BOLD)).register("i", (el, ctx) => withMark(ctx.render(el.children), ITALIC)).register("s", (el, ctx) => withMark(ctx.render(el.children), STRIKE)).register("code", (el, ctx) => withMark(ctx.render(el.children), CODE)).register("a", (el, ctx) => {
1186
+ const children = ctx.render(el.children);
1187
+ const attachments = children.filter((node) => node.type === "media");
1188
+ if (el.attrs.href === "") return children;
1189
+ const label = escape(ctx.text(el.children));
1190
+ return [textNode(label === "" ? `<${el.attrs.href}>` : `<${el.attrs.href}|${label}>`), ...attachments];
1191
+ }).register("at", (el) => {
1192
+ switch (el.attrs.type) {
1193
+ case "all": return textNode("<!everyone>");
1194
+ case "here": return textNode("<!here>");
1195
+ default: return el.attrs.id === void 0 ? textNode(`@${el.attrs.name ?? ""}`) : textNode(`<@${el.attrs.id}>`);
1196
+ }
1197
+ }, { variants: [
1198
+ "user",
1199
+ "all",
1200
+ "here"
1201
+ ] }).register("channel", (el) => textNode(`<#${el.attrs.id}>`)).register("emoji", (el) => el.attrs.id === "" ? textNode(el.attrs.name ?? "") : textNode(`:${el.attrs.id}:`)).register("h1", (el, ctx) => heading(ctx.render(el.children))).register("h2", (el, ctx) => heading(ctx.render(el.children))).register("h3", (el, ctx) => heading(ctx.render(el.children))).register("h4", (el, ctx) => heading(ctx.render(el.children))).register("h5", (el, ctx) => heading(ctx.render(el.children))).register("h6", (el, ctx) => heading(ctx.render(el.children))).register("ul", (el, ctx) => [
1202
+ BREAK,
1203
+ ...ctx.render(el.children),
1204
+ BREAK
1205
+ ]).register("ol", (el, ctx) => [
1206
+ BREAK,
1207
+ ...ctx.render(el.children),
1208
+ BREAK
1209
+ ]).register("li", (el, ctx) => {
1210
+ const parent = ctx.ancestors[ctx.ancestors.length - 1];
1211
+ const ordered = parent?.type === "ol";
1212
+ const siblings = parent === void 0 ? [] : parent.children;
1213
+ const index = Math.max(siblings.indexOf(el), 0);
1214
+ const start = ordered && parent.attrs.start !== void 0 ? parent.attrs.start : 1;
1215
+ return [
1216
+ textNode(ordered ? `${start + index}. ` : "• "),
1217
+ ...withoutLeadingBreaks(ctx.render(el.children)),
1218
+ BREAK
1219
+ ];
1220
+ }).register("blockquote", (el, ctx) => quoteLines(ctx.render(el.children))).register("pre", (el, ctx) => fenced(ctx.render(el.children), el.attrs.lang), { variants: ["lang"] }).register("hr", () => [
1221
+ BREAK,
1222
+ textNode("———"),
1223
+ BREAK
1224
+ ]).register("img", (el, ctx) => mediaNode(el, ctx), { variants: ["inline"] }).register("audio", (el, ctx) => mediaNode(el, ctx)).register("video", (el, ctx) => mediaNode(el, ctx)).register("file", (el, ctx) => mediaNode(el, ctx));
1225
+ return defineMode()({
1226
+ id: "mrkdwn",
1227
+ elements,
1228
+ limits: { "limit.text.chars": SLACK_LIMITS.text },
1229
+ assemble: (nodes) => assembleDraft(nodes),
1230
+ serialize: (prepared, ctx) => serializeDraft(prepared, ctx, replyBroadcast)
1231
+ });
1232
+ }
1233
+ // lib/types/decode.js
1234
+ /**
1235
+ * Inbound decoding: one Slack event becomes an intake `Session`, and one message object becomes an `InboundMessage`.
1236
+ *
1237
+ * The event kinds the vocabulary can carry are messages (the plain kind plus `file_share` and `thread_broadcast`),
1238
+ * message deletions and reactions; everything else is dropped. Message content is decoded from `blocks` when the
1239
+ * message has any, and from the `text` field otherwise, so a plain-text message is not lost.
1240
+ */
1241
+ /** One JSON value from the wire, when it is an object. */
1242
+ function asRecord(value) {
1243
+ return typeof value === "object" && value !== null ? value : void 0;
1244
+ }
1245
+ /** One JSON value from the wire, when it is a string. */
1246
+ function asString(value) {
1247
+ return typeof value === "string" ? value : void 0;
1248
+ }
1249
+ /** One JSON value from the wire, when it is an array. */
1250
+ function asArray(value) {
1251
+ return Array.isArray(value) ? value : [];
1252
+ }
1253
+ /**
1254
+ * Chat type of one Slack conversation.
1255
+ *
1256
+ * The event's `channel_type` is authoritative when it is present; an id prefix is the fallback, because the read
1257
+ * endpoints answer without a type.
1258
+ *
1259
+ * @param id - the conversation id (`C…`, `G…`, `D…`).
1260
+ * @param channelType - `channel_type` of the event, when it carried one.
1261
+ * @returns the DSH chat type.
1262
+ */
1263
+ function chatTypeOf(id, channelType) {
1264
+ if (channelType === "im") return "direct";
1265
+ if (channelType !== void 0) return "group";
1266
+ return id.startsWith("D") ? "direct" : "group";
1267
+ }
1268
+ /** The chat one message belongs to; a message event names the conversation it appeared in. */
1269
+ function chatRefOf(data) {
1270
+ const id = data.channel ?? "";
1271
+ return {
1272
+ id,
1273
+ type: chatTypeOf(id, data.channel_type)
1274
+ };
1275
+ }
1276
+ /** A Slack timestamp (seconds with a fraction) as milliseconds. */
1277
+ function timeOf(ts) {
1278
+ const seconds = Number(ts ?? "");
1279
+ return Number.isFinite(seconds) ? Math.floor(seconds * 1e3) : Date.now();
1280
+ }
1281
+ /** Decode one `emoji` rich-text node's `unicode` (`1f389`, or a `-`-joined sequence) into its characters. */
1282
+ function unicodeOf(unicode) {
1283
+ const codePoints = [];
1284
+ for (const part of unicode.split("-")) {
1285
+ const codePoint = Number.parseInt(part, 16);
1286
+ if (!Number.isFinite(codePoint) || codePoint <= 0) return void 0;
1287
+ codePoints.push(codePoint);
1288
+ }
1289
+ if (codePoints.length === 0) return void 0;
1290
+ try {
1291
+ return String.fromCodePoint(...codePoints);
1292
+ } catch (error) {
1293
+ return;
1294
+ }
1295
+ }
1296
+ /**
1297
+ * Decode the inline nodes of one `rich_text*` node.
1298
+ * @param raw - the node's `elements` array.
1299
+ * @returns the content nodes.
1300
+ */
1301
+ function decodeRichText(raw) {
1302
+ const nodes = [];
1303
+ for (const item of asArray(raw)) {
1304
+ const node = asRecord(item);
1305
+ if (node === void 0) continue;
1306
+ switch (asString(node.type)) {
1307
+ case "text": {
1308
+ const text = unescape(asString(node.text) ?? "");
1309
+ const style = asRecord(node.style) ?? {};
1310
+ let element = h.text(text);
1311
+ if (style.bold === true) element = h("b", {}, element);
1312
+ if (style.italic === true) element = h("i", {}, element);
1313
+ if (style.strike === true) element = h("s", {}, element);
1314
+ if (style.code === true) element = h("code", {}, element);
1315
+ nodes.push(element);
1316
+ break;
1317
+ }
1318
+ case "link": {
1319
+ const href = asString(node.url) ?? "";
1320
+ const label = unescape(asString(node.text) ?? "");
1321
+ nodes.push(h("a", { href }, label === "" ? href : label));
1322
+ break;
1323
+ }
1324
+ case "emoji": {
1325
+ const unicode = asString(node.unicode);
1326
+ const text = unicode === void 0 ? void 0 : unicodeOf(unicode);
1327
+ if (text !== void 0) nodes.push(h.text(text));
1328
+ else if (asString(node.name) !== void 0) nodes.push(h.text(`:${asString(node.name)}:`));
1329
+ break;
1330
+ }
1331
+ case "user": {
1332
+ const id = asString(node.user_id) ?? "";
1333
+ nodes.push(h("at", {
1334
+ type: "user",
1335
+ id
1336
+ }));
1337
+ break;
1338
+ }
1339
+ case "broadcast":
1340
+ nodes.push(h("at", { type: asString(node.range) === "here" ? "here" : "all" }));
1341
+ break;
1342
+ default: {
1343
+ const text = asString(node.text);
1344
+ if (text !== void 0 && text !== "") nodes.push(h.text(unescape(text)));
1345
+ break;
1346
+ }
1347
+ }
1348
+ }
1349
+ return nodes;
1350
+ }
1351
+ /** One `rich_text*` block (or a `rich_text_*` node inside it) as content nodes. */
1352
+ function decodeRichBlock(block) {
1353
+ const nodes = [];
1354
+ for (const item of asArray(block.elements)) {
1355
+ const element = asRecord(item);
1356
+ if (element === void 0) continue;
1357
+ switch (asString(element.type)) {
1358
+ case "rich_text_section":
1359
+ nodes.push(...decodeRichText(element.elements));
1360
+ break;
1361
+ case "rich_text_list": {
1362
+ const items = [];
1363
+ for (const entry of asArray(element.elements)) {
1364
+ const section = asRecord(entry);
1365
+ if (section === void 0) continue;
1366
+ items.push(h("li", {}, ...decodeRichText(section.elements)));
1367
+ }
1368
+ nodes.push(h(asString(element.style) === "ordered" ? "ol" : "ul", {}, ...items));
1369
+ break;
1370
+ }
1371
+ case "rich_text_preformatted":
1372
+ nodes.push(h("pre", {}, ...decodeRichText(element.elements)));
1373
+ break;
1374
+ case "rich_text_quote":
1375
+ nodes.push(h("blockquote", {}, ...decodeRichText(element.elements)));
1376
+ break;
1377
+ default: {
1378
+ const text = asString(element.text);
1379
+ if (text !== void 0 && text !== "") nodes.push(h.text(unescape(text)));
1380
+ break;
1381
+ }
1382
+ }
1383
+ }
1384
+ return nodes;
1385
+ }
1386
+ /**
1387
+ * Decode the `blocks` of one message.
1388
+ *
1389
+ * Only the two block kinds that carry content are decoded: `rich_text` (sections, lists, preformatted and quoted runs)
1390
+ * and `section` (its mrkdwn text). The rest — `header`, `divider`, `context`, `image`, `actions`, `file` — are left to
1391
+ * the message's `text` field, which Slack keeps as the notification fallback of a blocks message.
1392
+ *
1393
+ * @param raw - the message's `blocks`.
1394
+ * @returns the content nodes; empty when the blocks carried nothing decodable.
1395
+ */
1396
+ function decodeBlocks(raw) {
1397
+ const nodes = [];
1398
+ for (const item of raw) {
1399
+ const block = asRecord(item);
1400
+ if (block === void 0) continue;
1401
+ if (asString(block.type) === "rich_text") {
1402
+ nodes.push(...decodeRichBlock(block));
1403
+ continue;
1404
+ }
1405
+ if (asString(block.type) === "section") {
1406
+ const content = asString(asRecord(block.text)?.text);
1407
+ if (content !== void 0 && content !== "") nodes.push(...parseMrkdwn(content));
1408
+ }
1409
+ }
1410
+ return nodes;
1411
+ }
1412
+ /**
1413
+ * Decode one attachment into the element that names it.
1414
+ *
1415
+ * The element's source is the bot's own `satori:` route rather than `url_private`: that URL needs the bot token, which
1416
+ * the host does not have.
1417
+ *
1418
+ * @param bot - the receiving adapter, whose route serves the bytes.
1419
+ * @param file - one `files[]` entry of the message.
1420
+ * @returns the media element, typed by the file's MIME type.
1421
+ */
1422
+ function decodeFile(bot, file) {
1423
+ const src = bot.getInternalUrl(`/files/${file.id}`);
1424
+ const mime = file.mimetype ?? "";
1425
+ if (mime.startsWith("image/")) return h("img", { src });
1426
+ if (mime.startsWith("audio/")) return h("audio", { src });
1427
+ if (mime.startsWith("video/")) return h("video", { src });
1428
+ const name = file.name ?? file.title ?? "";
1429
+ return h("file", {
1430
+ src,
1431
+ ...name === "" ? {} : { name }
1432
+ });
1433
+ }
1434
+ /** Collect what one decoded message mentions; the self mention is what makes a group chat answer. */
1435
+ function collectMentions(bot, content) {
1436
+ const users = [];
1437
+ const seen = /* @__PURE__ */ new Set();
1438
+ const mentions = {
1439
+ self: false,
1440
+ all: false,
1441
+ users
1442
+ };
1443
+ const walk = (element) => {
1444
+ if (element.type === "at") {
1445
+ if (element.attrs.type === "all") mentions.all = true;
1446
+ else if (element.attrs.type === "user") {
1447
+ const id = element.attrs.id;
1448
+ if (id !== void 0 && !seen.has(id)) {
1449
+ seen.add(id);
1450
+ users.push({
1451
+ id,
1452
+ ...element.attrs.name === void 0 ? {} : { name: element.attrs.name }
1453
+ });
1454
+ }
1455
+ if (id !== void 0 && id === bot.selfId) mentions.self = true;
1456
+ }
1457
+ }
1458
+ for (const child of element.children) walk(child);
1459
+ };
1460
+ walk(content);
1461
+ return mentions;
1462
+ }
1463
+ /** A bounded description of a message that decoded to no content, so `<raw>` stays small. */
1464
+ function rawPreview(data) {
1465
+ const preview = {};
1466
+ for (const key of [
1467
+ "type",
1468
+ "subtype",
1469
+ "ts",
1470
+ "channel",
1471
+ "user",
1472
+ "bot_id"
1473
+ ]) {
1474
+ const value = data[key];
1475
+ if (typeof value === "string") preview[key] = value;
1476
+ }
1477
+ const files = data.files ?? [];
1478
+ if (files.length > 0) preview.files = files.length;
1479
+ return preview;
1480
+ }
1481
+ /** The sender of one message: Slack names the user, or the bot app of a bot message. */
1482
+ function senderOf(data) {
1483
+ return {
1484
+ id: data.user ?? data.bot_id ?? data.username ?? "",
1485
+ ...data.bot_id === void 0 ? {} : { isBot: true }
1486
+ };
1487
+ }
1488
+ /**
1489
+ * Decode one message object into an inbound message.
1490
+ *
1491
+ * @param bot - the receiving adapter.
1492
+ * @param data - a message event, a `conversations.history` row, or the `message` of a send answer.
1493
+ * @param chat - the chat to report; defaults to the one the message names.
1494
+ * @returns the decoded message, whose `content` is never empty.
1495
+ */
1496
+ function decodeMessage(bot, data, chat = chatRefOf(data)) {
1497
+ const nodes = decodeBlocks(data.blocks ?? []);
1498
+ if (nodes.length === 0 && data.text !== void 0 && data.text !== "") nodes.push(...parseMrkdwn(data.text));
1499
+ for (const file of data.files ?? []) nodes.push(decodeFile(bot, file));
1500
+ const content = normalize(nodes.length > 0 ? nodes : [h("raw", {
1501
+ platform: "slack",
1502
+ type: data.subtype ?? data.type ?? "message",
1503
+ data: rawPreview(data)
1504
+ }, h.text(""))]);
1505
+ const time = timeOf(data.ts);
1506
+ const threadTs = data.thread_ts;
1507
+ const inThread = threadTs !== void 0 && threadTs !== data.ts;
1508
+ const referrer = {
1509
+ channel: chat.id,
1510
+ ts: data.ts ?? "",
1511
+ ...inThread ? { threadTs } : {},
1512
+ ...data.team === void 0 ? {} : { team: data.team }
1513
+ };
1514
+ return {
1515
+ id: data.ts ?? "",
1516
+ chat,
1517
+ ...inThread ? { thread: {
1518
+ id: threadTs,
1519
+ root: threadTs
1520
+ } } : {},
1521
+ sender: senderOf(data),
1522
+ content,
1523
+ ...inThread ? { quote: { id: threadTs } } : {},
1524
+ mentions: collectMentions(bot, content),
1525
+ time,
1526
+ referrer,
1527
+ raw: data
1528
+ };
1529
+ }
1530
+ /** The envelope id of one event: global, and the key the host deduplicates on. */
1531
+ function eventIdOf(envelope, event) {
1532
+ if (envelope.event_id !== void 0 && envelope.event_id !== "") return envelope.event_id;
1533
+ return `${event.type ?? "event"}:${event.event_ts ?? event.ts ?? ""}:${event.channel ?? ""}`;
1534
+ }
1535
+ /**
1536
+ * Decode one received event.
1537
+ *
1538
+ * @param bot - the receiving adapter (its `selfId` marks its own messages, which are dropped because the host stores
1539
+ * them from the `send` event instead).
1540
+ * @param envelope - the event envelope of either transport.
1541
+ * @returns the session to publish, or undefined for an event this adapter does not carry.
1542
+ */
1543
+ function decodeEvent(bot, envelope) {
1544
+ const event = envelope.event;
1545
+ if (event?.type === void 0) return void 0;
1546
+ const id = eventIdOf(envelope, event);
1547
+ if (event.type === "message") {
1548
+ if (event.user !== void 0 && event.user === bot.selfId) return void 0;
1549
+ const subtype = event.subtype;
1550
+ if (subtype === void 0 || subtype === "file_share" || subtype === "thread_broadcast") {
1551
+ const message = decodeMessage(bot, event);
1552
+ return bot.session({
1553
+ type: "message",
1554
+ id,
1555
+ timestamp: message.time,
1556
+ message,
1557
+ raw: envelope
1558
+ });
1559
+ }
1560
+ if (subtype === "message_deleted") {
1561
+ const previous = event.previous_message;
1562
+ const ts = previous?.ts ?? event.deleted_ts ?? "";
1563
+ return bot.session({
1564
+ type: "message-deleted",
1565
+ id,
1566
+ timestamp: timeOf(previous?.ts ?? event.event_ts),
1567
+ deleted: {
1568
+ id: ts,
1569
+ chat: chatRefOf(previous ?? event)
1570
+ },
1571
+ raw: envelope
1572
+ });
1573
+ }
1574
+ return;
1575
+ }
1576
+ if (event.type === "reaction_added" || event.type === "reaction_removed") {
1577
+ const channel = event.item?.channel ?? "";
1578
+ const user = event.user;
1579
+ return bot.session({
1580
+ type: event.type === "reaction_added" ? "reaction-added" : "reaction-removed",
1581
+ id,
1582
+ timestamp: timeOf(event.event_ts),
1583
+ reaction: {
1584
+ message: {
1585
+ id: event.item?.ts ?? "",
1586
+ chat: {
1587
+ id: channel,
1588
+ type: chatTypeOf(channel, void 0)
1589
+ }
1590
+ },
1591
+ emoji: event.reaction ?? "",
1592
+ ...user === void 0 ? {} : { user: { id: user } }
1593
+ },
1594
+ raw: envelope
1595
+ });
1596
+ }
1597
+ }
1598
+ // lib/types/send.js
1599
+ /**
1600
+ * Outbound hooks: the send pipeline's payload, deletion, member reads, message reads and reactions.
1601
+ *
1602
+ * Slack publishes a text part with `chat.postMessage` and an attachment with `files.completeUploadExternal`; there is
1603
+ * no edit (the adapter does not implement `editPayload`), so the core's `edit` degrades to recall-and-resend.
1604
+ */
1605
+ /** The message timestamp of one share of a file, per channel. */
1606
+ function sharedTs(shares, channel) {
1607
+ const buckets = typeof shares === "object" && shares !== null ? shares : {};
1608
+ for (const bucketName of [
1609
+ "public",
1610
+ "private",
1611
+ "ims"
1612
+ ]) {
1613
+ const bucket = buckets[bucketName];
1614
+ if (typeof bucket !== "object" || bucket === null) continue;
1615
+ const entries = bucket[channel];
1616
+ if (!Array.isArray(entries)) continue;
1617
+ for (const entry of entries) {
1618
+ if (typeof entry !== "object" || entry === null) continue;
1619
+ const ts = entry.ts;
1620
+ if (typeof ts === "string" && ts !== "") return ts;
1621
+ }
1622
+ }
1623
+ }
1624
+ /** Milliseconds of one Slack timestamp. */
1625
+ function millisecondsOf(ts) {
1626
+ const seconds = Number(ts);
1627
+ return Number.isFinite(seconds) ? Math.round(seconds * 1e3) : Date.now();
1628
+ }
1629
+ /**
1630
+ * Send one serialized payload.
1631
+ * @param deps - the request dependencies.
1632
+ * @param payload - the mode's request data.
1633
+ * @param _target - the target chat, already carried by the payload.
1634
+ * @param _ctx - part index and quote, already resolved by `serialize`.
1635
+ * @returns the published part.
1636
+ */
1637
+ async function sendPayload(deps, payload, _target, _ctx) {
1638
+ const referrer = (channel, ts) => ({
1639
+ channel,
1640
+ ts,
1641
+ ...payload.threadTs === void 0 ? {} : { threadTs: payload.threadTs },
1642
+ ...deps.teamId === void 0 ? {} : { team: deps.teamId }
1643
+ });
1644
+ if (payload.kind === "file") {
1645
+ const file = (await finishUpload(deps.api, [{
1646
+ id: payload.fileId,
1647
+ title: payload.name
1648
+ }], payload.channel, payload.threadTs))[0];
1649
+ if (file === void 0) throw new PlatformError("invalid", "slack files.completeUploadExternal answered without the shared file", { published: "unknown" });
1650
+ const ts = sharedTs(file.shares, payload.channel);
1651
+ if (ts === void 0) throw new PlatformError("invalid", "slack files.completeUploadExternal answered without a message timestamp for the channel", { published: "unknown" });
1652
+ return {
1653
+ id: ts,
1654
+ kind: "file",
1655
+ time: file.created === void 0 ? Date.now() : file.created * 1e3,
1656
+ thread: { id: payload.threadTs ?? ts },
1657
+ referrer: referrer(payload.channel, ts)
1658
+ };
1659
+ }
1660
+ const answer = await callApi(deps.api, "chatPostMessage", {
1661
+ channel: payload.channel,
1662
+ text: payload.text,
1663
+ ...payload.threadTs === void 0 ? {} : { thread_ts: payload.threadTs },
1664
+ ...payload.replyBroadcast === true ? { reply_broadcast: true } : {}
1665
+ });
1666
+ const ts = answer.ts;
1667
+ if (ts === void 0 || ts === "") throw new PlatformError("invalid", "slack chat.postMessage answered without a message timestamp", { published: "unknown" });
1668
+ return {
1669
+ id: ts,
1670
+ kind: "message",
1671
+ time: millisecondsOf(ts),
1672
+ thread: { id: payload.threadTs ?? ts },
1673
+ referrer: referrer(answer.channel ?? payload.channel, ts)
1674
+ };
1675
+ }
1676
+ /**
1677
+ * Recall one published part.
1678
+ * @param deps - the request dependencies.
1679
+ * @param part - the part to recall.
1680
+ * @param handle - the message the part belongs to, which names the channel.
1681
+ */
1682
+ async function deletePart(deps, part, handle) {
1683
+ await callApi(deps.api, "chatDelete", {
1684
+ channel: handle.target.chat.id,
1685
+ ts: Number(part.id)
1686
+ });
1687
+ }
1688
+ /** The first of the given names that is not empty. */
1689
+ function firstNonEmpty(...values) {
1690
+ for (const value of values) if (value !== void 0 && value !== "") return value;
1691
+ return "";
1692
+ }
1693
+ /** One workspace member as a user reference; the name is what `im_members` shows. */
1694
+ function userRefOf(member) {
1695
+ const name = firstNonEmpty(member.real_name, member.profile?.display_name, member.name);
1696
+ return {
1697
+ id: member.id ?? "",
1698
+ ...name === "" ? {} : { name },
1699
+ ...member.is_bot === void 0 ? {} : { isBot: member.is_bot }
1700
+ };
1701
+ }
1702
+ /**
1703
+ * List the members of the workspace.
1704
+ *
1705
+ * `users.list` is workspace-level: Slack has no paged channel-member read that this adapter could page, so the list is
1706
+ * every human and bot of the installation, not the people of one conversation.
1707
+ *
1708
+ * @param deps - the request dependencies.
1709
+ * @param _chat - the chat the caller asked about; unused, because the platform's list is not per chat.
1710
+ * @param cursor - `next_cursor` of the previous page.
1711
+ * @param limit - page size the platform should use.
1712
+ * @returns one page of members.
1713
+ */
1714
+ async function members(deps, _chat, cursor, limit) {
1715
+ const params = {};
1716
+ if (limit !== void 0) params.limit = limit;
1717
+ if (cursor !== void 0 && cursor !== "") params.cursor = cursor;
1718
+ const answer = await callApi(deps.api, "usersList", params);
1719
+ const data = (answer.members ?? []).filter((member) => member.deleted !== true).map(userRefOf);
1720
+ const next = answer.response_metadata?.next_cursor;
1721
+ return {
1722
+ data,
1723
+ ...next === void 0 || next === "" ? {} : { next }
1724
+ };
1725
+ }
1726
+ /**
1727
+ * Read one message by its timestamp.
1728
+ *
1729
+ * `conversations.history` answers newest first, so the call bounds both ends of the range: `oldest` alone (the
1730
+ * upstream form) would return the newest message of the range instead of the one asked for.
1731
+ *
1732
+ * @param deps - the request dependencies.
1733
+ * @param bot - the adapter, needed to decode the answer.
1734
+ * @param chat - the chat the caller asked about; the answer carries no chat type, so it is reused verbatim.
1735
+ * @param id - platform message timestamp.
1736
+ * @returns the decoded message, with the same `chat` the caller passed.
1737
+ * @throws PlatformError `not-found` when the timestamp names no message of that chat.
1738
+ */
1739
+ async function getMessage(deps, bot, chat, id) {
1740
+ const raw = ((await callApi(deps.api, "conversationsHistory", {
1741
+ channel: chat.id,
1742
+ oldest: Number(id),
1743
+ latest: Number(id),
1744
+ inclusive: true,
1745
+ limit: 1
1746
+ })).messages ?? [])[0];
1747
+ if (raw === void 0) throw new PlatformError("not-found", `slack: message ${id} is not in ${chat.id}`, { published: "no" });
1748
+ return decodeMessage(bot, raw, chat);
1749
+ }
1750
+ /** One reaction name: the platform wants the emoji name without its colons. */
1751
+ function reactionName(emoji) {
1752
+ return emoji.replace(/^:+/, "").replace(/:+$/, "");
1753
+ }
1754
+ /**
1755
+ * Add one reaction to a published message.
1756
+ * @param deps - the request dependencies.
1757
+ * @param message - the message to react to.
1758
+ * @param emoji - the emoji (`:tada:` or `tada`).
1759
+ */
1760
+ async function createReaction(deps, message, emoji) {
1761
+ await callApi(deps.api, "reactionsAdd", {
1762
+ channel: message.chat.id,
1763
+ timestamp: message.id,
1764
+ name: reactionName(emoji)
1765
+ });
1766
+ }
1767
+ /**
1768
+ * Remove one reaction from a published message.
1769
+ * @param deps - the request dependencies.
1770
+ * @param message - the message to react to.
1771
+ * @param emoji - the emoji (`:tada:` or `tada`).
1772
+ */
1773
+ async function deleteReaction(deps, message, emoji) {
1774
+ await callApi(deps.api, "reactionsRemove", {
1775
+ channel: message.chat.id,
1776
+ timestamp: message.id,
1777
+ name: reactionName(emoji)
1778
+ });
1779
+ }
1780
+ // lib/types/transport/socket.js
1781
+ /**
1782
+ * Socket Mode transport (`protocol: 'ws'`).
1783
+ *
1784
+ * The adapter asks for a fresh connection URL before every dial (Slack hands out one ticket per connection), dials it
1785
+ * with the `http` service, and dials again forever: `ws.retryTimes` is a fast-retry budget, not a give-up count.
1786
+ * Configuration failures are the caller's to fix and throw out of `connect()`; transport failures retry.
1787
+ *
1788
+ * Every `events_api` envelope is acknowledged before it is decoded, which is what Slack's own guidance asks and what
1789
+ * keeps a slow intake from tripping the delivery timeout. The cost is that a crash between the acknowledgement and the
1790
+ * store loses the event: Slack does not redeliver an acknowledged envelope.
1791
+ */
1792
+ /** Waitable sleep that resolves early on abort. */
1793
+ function sleep(ms, signal) {
1794
+ return new Promise((resolve) => {
1795
+ if (signal.aborted) {
1796
+ resolve();
1797
+ return;
1798
+ }
1799
+ const timer = setTimeout(() => {
1800
+ signal.removeEventListener("abort", onAbort);
1801
+ resolve();
1802
+ }, ms);
1803
+ const onAbort = () => {
1804
+ clearTimeout(timer);
1805
+ resolve();
1806
+ };
1807
+ signal.addEventListener("abort", onAbort, { once: true });
1808
+ });
1809
+ }
1810
+ /** `apps.connections.open` refusals that only an app or token change can fix. */
1811
+ const PERMANENT_OPEN_ERRORS = /* @__PURE__ */ new Set([
1812
+ "invalid_auth",
1813
+ "not_authed",
1814
+ "token_revoked",
1815
+ "missing_scope"
1816
+ ]);
1817
+ /** Text of one WebSocket frame. */
1818
+ function frameText(data) {
1819
+ return typeof data === "string" ? data : String(data);
1820
+ }
1821
+ /** Message of any caught value, for a log line. */
1822
+ function messageOf$2(error) {
1823
+ return error instanceof Error ? error.message : String(error);
1824
+ }
1825
+ /** The Socket Mode client of one bot. */
1826
+ var SlackSocketMode = class {
1827
+ bot;
1828
+ controller;
1829
+ running;
1830
+ socket;
1831
+ constructor(bot) {
1832
+ this.bot = bot;
1833
+ }
1834
+ /**
1835
+ * Start the reconnect loop.
1836
+ *
1837
+ * Returning before the first dial is deliberate: `Bot.start` awaits `connect()`, so waiting here would hold up
1838
+ * plugin initialization for as long as Slack is unreachable.
1839
+ */
1840
+ async start() {
1841
+ this.controller = new AbortController();
1842
+ this.running = this.loop(this.controller.signal);
1843
+ }
1844
+ /** Stop the loop and wait for it to unwind. */
1845
+ async stop() {
1846
+ this.controller?.abort();
1847
+ this.controller = void 0;
1848
+ this.closeSocket();
1849
+ await this.running?.catch(() => void 0);
1850
+ this.running = void 0;
1851
+ }
1852
+ async loop(signal) {
1853
+ let failures = 0;
1854
+ while (!signal.aborted) try {
1855
+ const url = await this.openUrl(signal);
1856
+ const socket = await this.dial(url, signal);
1857
+ this.socket = socket;
1858
+ const greeted = await this.accept(socket, signal);
1859
+ this.socket = void 0;
1860
+ if (signal.aborted) return;
1861
+ failures = greeted ? 0 : failures + 1;
1862
+ this.bot.ctx.logger.warn("slack: the Socket Mode connection closed; reconnecting");
1863
+ this.bot.status = Status.RECONNECT;
1864
+ await sleep(this.intervalOf(failures), signal);
1865
+ } catch (error) {
1866
+ if (signal.aborted) return;
1867
+ if (error instanceof SlackFatalError) {
1868
+ this.bot.ctx.logger.error("%s", error.message);
1869
+ this.bot.offline(error);
1870
+ return;
1871
+ }
1872
+ failures += 1;
1873
+ this.bot.ctx.logger.warn("slack: %s; reconnecting", messageOf$2(error));
1874
+ this.bot.status = Status.RECONNECT;
1875
+ await sleep(this.intervalOf(failures), signal);
1876
+ }
1877
+ }
1878
+ /** Delay before the next dial: the fast interval while the failure budget lasts, the lazy one after it. */
1879
+ intervalOf(failures) {
1880
+ const { ws } = this.bot.config;
1881
+ return failures < ws.retryTimes ? ws.retryInterval : ws.retryLazy;
1882
+ }
1883
+ /** Fetch the connection URL of the next dial. */
1884
+ async openUrl(signal) {
1885
+ let answer;
1886
+ try {
1887
+ answer = await callApi(this.bot.api, "appsConnectionsOpen", {}, {
1888
+ app: true,
1889
+ signal
1890
+ });
1891
+ } catch (error) {
1892
+ if (error instanceof SlackApiError && error.code !== void 0 && PERMANENT_OPEN_ERRORS.has(error.code)) throw new SlackFatalError(`slack: apps.connections.open refused the app-level token (${error.code}); fix token and restart`, { cause: error });
1893
+ throw error;
1894
+ }
1895
+ if (answer.url === void 0 || answer.url === "") throw new Error("slack: apps.connections.open answered without a url");
1896
+ return answer.url;
1897
+ }
1898
+ /** Dial the connection URL and resolve once the socket is open. */
1899
+ dial(url, signal) {
1900
+ const socket = this.bot.ctx.http.ws(url);
1901
+ return new Promise((resolve, reject) => {
1902
+ const cleanup = () => {
1903
+ socket.removeEventListener("open", onOpen);
1904
+ socket.removeEventListener("error", onError);
1905
+ socket.removeEventListener("close", onClose);
1906
+ signal.removeEventListener("abort", onAbort);
1907
+ };
1908
+ const onOpen = () => {
1909
+ cleanup();
1910
+ resolve(socket);
1911
+ };
1912
+ const onError = (event) => {
1913
+ cleanup();
1914
+ reject(/* @__PURE__ */ new Error(`slack: WebSocket error${event.message === void 0 ? "" : `: ${event.message}`}`));
1915
+ };
1916
+ const onClose = (event) => {
1917
+ cleanup();
1918
+ reject(/* @__PURE__ */ new Error(`slack: WebSocket closed before opening (code ${event.code})`));
1919
+ };
1920
+ const onAbort = () => {
1921
+ cleanup();
1922
+ reject(signal.reason ?? /* @__PURE__ */ new Error("slack: adapter stopped"));
1923
+ };
1924
+ if (signal.aborted) {
1925
+ onAbort();
1926
+ return;
1927
+ }
1928
+ socket.addEventListener("open", onOpen);
1929
+ socket.addEventListener("error", onError);
1930
+ socket.addEventListener("close", onClose);
1931
+ signal.addEventListener("abort", onAbort, { once: true });
1932
+ });
1933
+ }
1934
+ /**
1935
+ * Serve one open connection until it closes.
1936
+ * @param socket - the open socket.
1937
+ * @param signal - cancellation of the loop.
1938
+ * @returns whether `hello` arrived, i.e. whether the connection ever worked.
1939
+ */
1940
+ async accept(socket, signal) {
1941
+ let greeted = false;
1942
+ const closed = new Promise((resolve) => {
1943
+ socket.addEventListener("close", () => {
1944
+ resolve();
1945
+ });
1946
+ });
1947
+ socket.addEventListener("message", (event) => {
1948
+ this.handleFrame(socket, frameText(event.data), () => {
1949
+ greeted = true;
1950
+ });
1951
+ });
1952
+ const onAbort = () => {
1953
+ this.closeSocket();
1954
+ };
1955
+ signal.addEventListener("abort", onAbort, { once: true });
1956
+ try {
1957
+ await closed;
1958
+ } finally {
1959
+ signal.removeEventListener("abort", onAbort);
1960
+ }
1961
+ return greeted;
1962
+ }
1963
+ /** Dispatch one received frame: a greeting, an event, a disconnect notice or noise. */
1964
+ handleFrame(socket, text, markGreeted) {
1965
+ let parsed;
1966
+ try {
1967
+ parsed = JSON.parse(text);
1968
+ } catch (error) {
1969
+ this.bot.ctx.logger.warn("slack: cannot parse a Socket Mode frame: %s", messageOf$2(error));
1970
+ return;
1971
+ }
1972
+ if (typeof parsed !== "object" || parsed === null) return;
1973
+ switch (parsed.type) {
1974
+ case "hello": {
1975
+ const frame = parsed;
1976
+ markGreeted();
1977
+ this.bot.ctx.logger.debug("slack: connected to app %s (%s connection(s)); the platform may keep it for about %s s", frame.connection_info?.app_id ?? "unknown", frame.num_connections ?? 1, frame.approximate_connection_time ?? 0);
1978
+ this.bot.online();
1979
+ return;
1980
+ }
1981
+ case "events_api":
1982
+ this.deliver(socket, parsed);
1983
+ return;
1984
+ case "disconnect":
1985
+ this.disconnect(parsed);
1986
+ return;
1987
+ case "interactive":
1988
+ case "slash_commands":
1989
+ this.acknowledge(socket, parsed.envelope_id);
1990
+ this.bot.ctx.logger.debug("slack: ignored an %s envelope", parsed.type);
1991
+ return;
1992
+ default: this.bot.ctx.logger.debug("slack: ignored a Socket Mode frame of type \"%s\"", String(parsed.type ?? "unknown"));
1993
+ }
1994
+ }
1995
+ /** Send the acknowledgement of one envelope, when the socket still accepts it. */
1996
+ acknowledge(socket, envelopeId) {
1997
+ try {
1998
+ socket.send(JSON.stringify({ envelope_id: envelopeId }));
1999
+ } catch (error) {
2000
+ this.bot.ctx.logger.warn("slack: could not acknowledge an envelope: %s", messageOf$2(error));
2001
+ }
2002
+ }
2003
+ /**
2004
+ * Acknowledge one envelope, then hand its event to intake.
2005
+ *
2006
+ * The acknowledgement goes out first and its failure is only logged: Slack will not redeliver an acknowledged event,
2007
+ * so a failed intake is reported here instead of being retried by the platform.
2008
+ */
2009
+ async deliver(socket, frame) {
2010
+ this.acknowledge(socket, frame.envelope_id);
2011
+ let session;
2012
+ try {
2013
+ session = decodeEvent(this.bot, frame.payload);
2014
+ } catch (error) {
2015
+ this.bot.ctx.logger.error("slack: cannot decode an envelope: %s", messageOf$2(error));
2016
+ return;
2017
+ }
2018
+ if (session === void 0) {
2019
+ this.bot.ctx.logger.debug("slack: ignored an %s event", frame.payload.event?.type ?? "unknown");
2020
+ return;
2021
+ }
2022
+ try {
2023
+ await this.bot.receive(session);
2024
+ } catch (error) {
2025
+ this.bot.ctx.logger.error("slack: intake failed: %s", messageOf$2(error));
2026
+ }
2027
+ }
2028
+ /** Handle the platform's notice that the connection is going away. */
2029
+ disconnect(frame) {
2030
+ const reason = frame.reason ?? "";
2031
+ if (reason === "warning") {
2032
+ this.bot.ctx.logger.info("slack: the platform will refresh the connection soon; keeping it until it closes");
2033
+ return;
2034
+ }
2035
+ this.bot.ctx.logger.info("slack: the platform closed the connection (%s); reconnecting", reason === "" ? "no reason given" : reason);
2036
+ this.closeSocket();
2037
+ }
2038
+ closeSocket() {
2039
+ const socket = this.socket;
2040
+ this.socket = void 0;
2041
+ try {
2042
+ socket?.close(1e3, "adapter stopped");
2043
+ } catch (error) {}
2044
+ }
2045
+ };
2046
+ // lib/types/transport/webhook.js
2047
+ /**
2048
+ * Events API transport (`protocol: 'http'`).
2049
+ *
2050
+ * The profile's `webServer` owns the listener, so this transport only registers one anonymous route at `path` and
2051
+ * authenticates every request itself: `v0:` HMAC-SHA256 over `v0:<timestamp>:<raw body>`, inside a five-minute window
2052
+ * and compared in constant time. Interactive payloads (a form body) are refused, because v1 publishes no controls.
2053
+ *
2054
+ * `event_callback` is answered `200` before its event reaches intake. Slack redelivers whatever it could not confirm
2055
+ * within three seconds and gives up after three retries, so a slow intake must not delay the confirmation; the cost is
2056
+ * that a crash between the confirmation and the store loses the event.
2057
+ */
2058
+ /** How far a request's timestamp may be from now before it is refused as a replay. */
2059
+ const TIMESTAMP_WINDOW_SECONDS = 300;
2060
+ /**
2061
+ * The `X-Slack-Signature` value of one request.
2062
+ * @param signing - the app's signing secret.
2063
+ * @param timestamp - `X-Slack-Request-Timestamp`.
2064
+ * @param body - the raw request body, before parsing.
2065
+ * @returns `v0=<hex digest>`.
2066
+ */
2067
+ function signatureOf(signing, timestamp, body) {
2068
+ return `v0=${createHmac("sha256", signing).update(`v0:${timestamp}:${body}`).digest("hex")}`;
2069
+ }
2070
+ /**
2071
+ * Compare two signature strings without leaking where they differ.
2072
+ * @param expected - the signature computed from the body.
2073
+ * @param received - the signature the request carried.
2074
+ * @returns whether they are equal.
2075
+ */
2076
+ function matchesSignature(expected, received) {
2077
+ const left = Buffer.from(expected, "utf8");
2078
+ const right = Buffer.from(received, "utf8");
2079
+ if (left.length !== right.length) return false;
2080
+ return timingSafeEqual(left, right);
2081
+ }
2082
+ /** One header of an inbound request, when it arrived exactly once. */
2083
+ function headerOf(request, name) {
2084
+ const value = request.headers[name];
2085
+ return typeof value === "string" ? value : void 0;
2086
+ }
2087
+ /** Read a request body to its end. The adapter imposes no size limit, as the upstream plugin does not. */
2088
+ async function readBody(request) {
2089
+ const chunks = [];
2090
+ for await (const chunk of request) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
2091
+ return Buffer.concat(chunks).toString("utf8");
2092
+ }
2093
+ /** Answer one request without a body. */
2094
+ function writeStatus(response, status, headers = {}) {
2095
+ response.writeHead(status, headers);
2096
+ response.end();
2097
+ }
2098
+ /** Confirm one request: `200` with the plain-text body Slack's own examples use. */
2099
+ function writeOk(response) {
2100
+ response.writeHead(200, { "content-type": "text/plain" });
2101
+ response.end("ok");
2102
+ }
2103
+ /** Whether a request body claims to be JSON. */
2104
+ function isJson(contentType) {
2105
+ if (contentType === void 0) return false;
2106
+ return contentType.split(";")[0].trim().toLowerCase() === "application/json";
2107
+ }
2108
+ /** Message of any caught value, for a log line. */
2109
+ function messageOf$1(error) {
2110
+ return error instanceof Error ? error.message : String(error);
2111
+ }
2112
+ /** The Events API transport of one bot. */
2113
+ var SlackWebhook = class {
2114
+ bot;
2115
+ dispose;
2116
+ constructor(bot) {
2117
+ this.bot = bot;
2118
+ }
2119
+ /** Register the route; a profile without a web server fails with an actionable message. */
2120
+ async start() {
2121
+ const webServer = this.bot.ctx.get("webServer");
2122
+ if (webServer === void 0) throw this.failStart("slack: protocol \"http\" needs a profile-provided webServer; use protocol \"ws\" instead");
2123
+ this.dispose = webServer.register({
2124
+ kind: "exact",
2125
+ path: routePath(this.bot.config.path),
2126
+ auth: "anonymous",
2127
+ handler: (request, response) => this.handle(request, response)
2128
+ });
2129
+ this.bot.online();
2130
+ }
2131
+ /** Release the route. The platform keeps posting to it until the app's Request URL changes. */
2132
+ async stop() {
2133
+ this.dispose?.();
2134
+ this.dispose = void 0;
2135
+ }
2136
+ /**
2137
+ * Log a fatal start failure before the caller throws it, because `Bot.start` only stores a connect failure on
2138
+ * `bot.error`.
2139
+ * @param message - error text that also names the corrective action.
2140
+ * @returns the error for the caller to throw.
2141
+ */
2142
+ failStart(message) {
2143
+ this.bot.ctx.logger.error(message);
2144
+ return new Error(message);
2145
+ }
2146
+ async handle(request, response) {
2147
+ try {
2148
+ if (request.method !== "POST") {
2149
+ writeStatus(response, 405, { allow: "POST" });
2150
+ return;
2151
+ }
2152
+ if (!isJson(headerOf(request, "content-type"))) {
2153
+ writeStatus(response, 400);
2154
+ return;
2155
+ }
2156
+ const timestamp = headerOf(request, "x-slack-request-timestamp");
2157
+ const signature = headerOf(request, "x-slack-signature");
2158
+ if (timestamp === void 0 || signature === void 0) {
2159
+ writeStatus(response, 401);
2160
+ return;
2161
+ }
2162
+ const seconds = Number(timestamp);
2163
+ const now = Math.floor(Date.now() / 1e3);
2164
+ if (!Number.isFinite(seconds) || Math.abs(now - seconds) > TIMESTAMP_WINDOW_SECONDS) {
2165
+ writeStatus(response, 403);
2166
+ return;
2167
+ }
2168
+ const body = await readBody(request);
2169
+ if (!matchesSignature(signatureOf(this.bot.config.signing, timestamp, body), signature)) {
2170
+ writeStatus(response, 403);
2171
+ return;
2172
+ }
2173
+ let parsed;
2174
+ try {
2175
+ parsed = JSON.parse(body);
2176
+ } catch (error) {
2177
+ this.bot.ctx.logger.warn("slack: cannot parse an Events API request: %s", messageOf$1(error));
2178
+ writeStatus(response, 400);
2179
+ return;
2180
+ }
2181
+ if (typeof parsed !== "object" || parsed === null) {
2182
+ writeStatus(response, 400);
2183
+ return;
2184
+ }
2185
+ const retryNum = headerOf(request, "x-slack-retry-num");
2186
+ if (retryNum !== void 0) this.bot.ctx.logger.debug("slack: redelivery #%s (%s)", retryNum, headerOf(request, "x-slack-retry-reason") ?? "no reason given");
2187
+ const type = parsed.type;
2188
+ if (type === "url_verification") {
2189
+ const challenge = parsed.challenge;
2190
+ response.writeHead(200, { "content-type": "application/json" });
2191
+ response.end(JSON.stringify({ challenge: typeof challenge === "string" ? challenge : "" }));
2192
+ return;
2193
+ }
2194
+ if (type === "event_callback") {
2195
+ writeOk(response);
2196
+ await this.deliver(parsed);
2197
+ return;
2198
+ }
2199
+ writeOk(response);
2200
+ this.bot.ctx.logger.debug("slack: ignored an Events API request of type \"%s\"", String(type ?? "unknown"));
2201
+ } catch (error) {
2202
+ this.bot.ctx.logger.warn("slack: Events API delivery failed: %s", messageOf$1(error));
2203
+ if (!response.headersSent) writeStatus(response, 500);
2204
+ else response.end();
2205
+ }
2206
+ }
2207
+ /** Hand one confirmed event to intake; a failed intake is logged because the confirmation already went out. */
2208
+ async deliver(envelope) {
2209
+ let session;
2210
+ try {
2211
+ session = decodeEvent(this.bot, envelope);
2212
+ } catch (error) {
2213
+ this.bot.ctx.logger.error("slack: cannot decode an event: %s", messageOf$1(error));
2214
+ return;
2215
+ }
2216
+ if (session === void 0) {
2217
+ this.bot.ctx.logger.debug("slack: ignored an %s event", envelope.event?.type ?? "unknown");
2218
+ return;
2219
+ }
2220
+ try {
2221
+ await this.bot.receive(session);
2222
+ } catch (error) {
2223
+ this.bot.ctx.logger.error("slack: intake failed: %s", messageOf$1(error));
2224
+ }
2225
+ }
2226
+ };
2227
+ // lib/types/types/internal.js
2228
+ var Token;
2229
+ (function(Token) {
2230
+ Token[Token["BOT"] = 0] = "BOT";
2231
+ Token[Token["APP"] = 1] = "APP";
2232
+ })(Token || (Token = {}));
2233
+ var Internal = class Internal {
2234
+ bot;
2235
+ http;
2236
+ constructor(bot, http) {
2237
+ this.bot = bot;
2238
+ this.http = http;
2239
+ }
2240
+ static define(routes) {
2241
+ for (const path in routes) for (const key in routes[path]) {
2242
+ const method = key;
2243
+ for (const name of Object.keys(routes[path][method])) Reflect.set(Internal.prototype, name, async function(...args) {
2244
+ const headers = {};
2245
+ const config = { headers };
2246
+ let token = "";
2247
+ if (typeof args[0] === "string") token = args[0];
2248
+ else token = args[0] === Token.BOT ? this.bot.config.botToken : this.bot.config.token;
2249
+ headers.Authorization = `Bearer ${token}`;
2250
+ const supportJson = routes[path][method][name];
2251
+ if (method === "GET") config.params = args[1];
2252
+ else if (supportJson && !(args[1] instanceof FormData)) {
2253
+ headers["content-type"] = "application/json; charset=utf-8";
2254
+ config.data = JSON.stringify(args[1]);
2255
+ } else {
2256
+ headers["content-type"] = "application/x-www-form-urlencoded";
2257
+ config.data = args[1] instanceof FormData ? args[1] : encodeForm(args[1] ?? {});
2258
+ }
2259
+ try {
2260
+ return await (await this.http(path.replace(/^\/+/, ""), {
2261
+ ...config,
2262
+ method
2263
+ })).json();
2264
+ } catch (error) {
2265
+ if (!this.http.isError(error) || !error.response) throw error;
2266
+ throw new Error(`[${error.response.status}] ${await error.response.text()}`);
2267
+ }
2268
+ });
2269
+ }
2270
+ }
2271
+ };
2272
+ // lib/types/types/admin.js
2273
+ Internal.define({
2274
+ "/admin.apps.approve": { POST: { "adminAppsApprove": true } },
2275
+ "/admin.apps.approved.list": { GET: { "adminAppsApprovedList": false } },
2276
+ "/admin.apps.requests.list": { GET: { "adminAppsRequestsList": false } },
2277
+ "/admin.apps.restrict": { POST: { "adminAppsRestrict": true } },
2278
+ "/admin.apps.restricted.list": { GET: { "adminAppsRestrictedList": false } },
2279
+ "/admin.conversations.archive": { POST: { "adminConversationsArchive": true } },
2280
+ "/admin.conversations.convertToPrivate": { POST: { "adminConversationsConvertToPrivate": true } },
2281
+ "/admin.conversations.create": { POST: { "adminConversationsCreate": true } },
2282
+ "/admin.conversations.delete": { POST: { "adminConversationsDelete": true } },
2283
+ "/admin.conversations.disconnectShared": { POST: { "adminConversationsDisconnectShared": true } },
2284
+ "/admin.conversations.ekm.listOriginalConnectedChannelInfo": { GET: { "adminConversationsEkmListOriginalConnectedChannelInfo": false } },
2285
+ "/admin.conversations.getConversationPrefs": { GET: { "adminConversationsGetConversationPrefs": true } },
2286
+ "/admin.conversations.getTeams": { GET: { "adminConversationsGetTeams": true } },
2287
+ "/admin.conversations.invite": { POST: { "adminConversationsInvite": true } },
2288
+ "/admin.conversations.rename": { POST: { "adminConversationsRename": true } },
2289
+ "/admin.conversations.restrictAccess.addGroup": { POST: { "adminConversationsRestrictAccessAddGroup": false } },
2290
+ "/admin.conversations.restrictAccess.listGroups": { GET: { "adminConversationsRestrictAccessListGroups": false } },
2291
+ "/admin.conversations.restrictAccess.removeGroup": { POST: { "adminConversationsRestrictAccessRemoveGroup": false } },
2292
+ "/admin.conversations.search": { GET: { "adminConversationsSearch": true } },
2293
+ "/admin.conversations.setConversationPrefs": { POST: { "adminConversationsSetConversationPrefs": true } },
2294
+ "/admin.conversations.setTeams": { POST: { "adminConversationsSetTeams": true } },
2295
+ "/admin.conversations.unarchive": { POST: { "adminConversationsUnarchive": true } },
2296
+ "/admin.emoji.add": { POST: { "adminEmojiAdd": false } },
2297
+ "/admin.emoji.addAlias": { POST: { "adminEmojiAddAlias": false } },
2298
+ "/admin.emoji.list": { GET: { "adminEmojiList": false } },
2299
+ "/admin.emoji.remove": { POST: { "adminEmojiRemove": false } },
2300
+ "/admin.emoji.rename": { POST: { "adminEmojiRename": false } },
2301
+ "/admin.inviteRequests.approve": { POST: { "adminInviteRequestsApprove": true } },
2302
+ "/admin.inviteRequests.approved.list": { GET: { "adminInviteRequestsApprovedList": true } },
2303
+ "/admin.inviteRequests.denied.list": { GET: { "adminInviteRequestsDeniedList": true } },
2304
+ "/admin.inviteRequests.deny": { POST: { "adminInviteRequestsDeny": true } },
2305
+ "/admin.inviteRequests.list": { GET: { "adminInviteRequestsList": true } },
2306
+ "/admin.teams.admins.list": { GET: { "adminTeamsAdminsList": false } },
2307
+ "/admin.teams.create": { POST: { "adminTeamsCreate": true } },
2308
+ "/admin.teams.list": { GET: { "adminTeamsList": true } },
2309
+ "/admin.teams.owners.list": { GET: { "adminTeamsOwnersList": false } },
2310
+ "/admin.teams.settings.info": { GET: { "adminTeamsSettingsInfo": true } },
2311
+ "/admin.teams.settings.setDefaultChannels": { POST: { "adminTeamsSettingsSetDefaultChannels": false } },
2312
+ "/admin.teams.settings.setDescription": { POST: { "adminTeamsSettingsSetDescription": true } },
2313
+ "/admin.teams.settings.setDiscoverability": { POST: { "adminTeamsSettingsSetDiscoverability": true } },
2314
+ "/admin.teams.settings.setIcon": { POST: { "adminTeamsSettingsSetIcon": false } },
2315
+ "/admin.teams.settings.setName": { POST: { "adminTeamsSettingsSetName": true } },
2316
+ "/admin.usergroups.addChannels": { POST: { "adminUsergroupsAddChannels": true } },
2317
+ "/admin.usergroups.addTeams": { POST: { "adminUsergroupsAddTeams": true } },
2318
+ "/admin.usergroups.listChannels": { GET: { "adminUsergroupsListChannels": true } },
2319
+ "/admin.usergroups.removeChannels": { POST: { "adminUsergroupsRemoveChannels": true } },
2320
+ "/admin.users.assign": { POST: { "adminUsersAssign": true } },
2321
+ "/admin.users.invite": { POST: { "adminUsersInvite": true } },
2322
+ "/admin.users.list": { GET: { "adminUsersList": true } },
2323
+ "/admin.users.remove": { POST: { "adminUsersRemove": true } },
2324
+ "/admin.users.session.invalidate": { POST: { "adminUsersSessionInvalidate": true } },
2325
+ "/admin.users.session.reset": { POST: { "adminUsersSessionReset": true } },
2326
+ "/admin.users.setAdmin": { POST: { "adminUsersSetAdmin": true } },
2327
+ "/admin.users.setExpiration": { POST: { "adminUsersSetExpiration": true } },
2328
+ "/admin.users.setOwner": { POST: { "adminUsersSetOwner": true } },
2329
+ "/admin.users.setRegular": { POST: { "adminUsersSetRegular": true } }
2330
+ });
2331
+ // lib/types/types/api.js
2332
+ Internal.define({ "/api.test": { GET: { "apiTest": true } } });
2333
+ // lib/types/types/apps.js
2334
+ Internal.define({
2335
+ "/apps.event.authorizations.list": { GET: { "appsEventAuthorizationsList": true } },
2336
+ "/apps.permissions.info": { GET: { "appsPermissionsInfo": false } },
2337
+ "/apps.permissions.request": { GET: { "appsPermissionsRequest": false } },
2338
+ "/apps.permissions.resources.list": { GET: { "appsPermissionsResourcesList": false } },
2339
+ "/apps.permissions.scopes.list": { GET: { "appsPermissionsScopesList": false } },
2340
+ "/apps.permissions.users.list": { GET: { "appsPermissionsUsersList": false } },
2341
+ "/apps.permissions.users.request": { GET: { "appsPermissionsUsersRequest": false } },
2342
+ "/apps.uninstall": { GET: { "appsUninstall": false } }
2343
+ });
2344
+ // lib/types/types/auth.js
2345
+ Internal.define({
2346
+ "/auth.revoke": { GET: { "authRevoke": false } },
2347
+ "/auth.test": { GET: { "authTest": true } }
2348
+ });
2349
+ // lib/types/types/bots.js
2350
+ Internal.define({ "/bots.info": { GET: { "botsInfo": false } } });
2351
+ // lib/types/types/calls.js
2352
+ Internal.define({
2353
+ "/calls.add": { POST: { "callsAdd": true } },
2354
+ "/calls.end": { POST: { "callsEnd": true } },
2355
+ "/calls.info": { GET: { "callsInfo": true } },
2356
+ "/calls.participants.add": { POST: { "callsParticipantsAdd": true } },
2357
+ "/calls.participants.remove": { POST: { "callsParticipantsRemove": true } },
2358
+ "/calls.update": { POST: { "callsUpdate": true } }
2359
+ });
2360
+ // lib/types/types/chat.js
2361
+ Internal.define({
2362
+ "/chat.delete": { POST: { "chatDelete": true } },
2363
+ "/chat.deleteScheduledMessage": { POST: { "chatDeleteScheduledMessage": true } },
2364
+ "/chat.getPermalink": { GET: { "chatGetPermalink": false } },
2365
+ "/chat.meMessage": { POST: { "chatMeMessage": true } },
2366
+ "/chat.postEphemeral": { POST: { "chatPostEphemeral": true } },
2367
+ "/chat.postMessage": { POST: { "chatPostMessage": true } },
2368
+ "/chat.scheduleMessage": { POST: { "chatScheduleMessage": true } },
2369
+ "/chat.scheduledMessages.list": { GET: { "chatScheduledMessagesList": true } },
2370
+ "/chat.unfurl": { POST: { "chatUnfurl": true } },
2371
+ "/chat.update": { POST: { "chatUpdate": true } }
2372
+ });
2373
+ // lib/types/types/conversations.js
2374
+ Internal.define({
2375
+ "/conversations.archive": { POST: { "conversationsArchive": true } },
2376
+ "/conversations.close": { POST: { "conversationsClose": true } },
2377
+ "/conversations.create": { POST: { "conversationsCreate": true } },
2378
+ "/conversations.history": { GET: { "conversationsHistory": true } },
2379
+ "/conversations.info": { GET: { "conversationsInfo": false } },
2380
+ "/conversations.invite": { POST: { "conversationsInvite": true } },
2381
+ "/conversations.join": { POST: { "conversationsJoin": true } },
2382
+ "/conversations.kick": { POST: { "conversationsKick": true } },
2383
+ "/conversations.leave": { POST: { "conversationsLeave": true } },
2384
+ "/conversations.list": { GET: { "conversationsList": false } },
2385
+ "/conversations.mark": { POST: { "conversationsMark": true } },
2386
+ "/conversations.members": { GET: { "conversationsMembers": false } },
2387
+ "/conversations.open": { POST: { "conversationsOpen": true } },
2388
+ "/conversations.rename": { POST: { "conversationsRename": true } },
2389
+ "/conversations.replies": { GET: { "conversationsReplies": false } },
2390
+ "/conversations.setPurpose": { POST: { "conversationsSetPurpose": true } },
2391
+ "/conversations.setTopic": { POST: { "conversationsSetTopic": true } },
2392
+ "/conversations.unarchive": { POST: { "conversationsUnarchive": true } }
2393
+ });
2394
+ // lib/types/types/dialog.js
2395
+ Internal.define({ "/dialog.open": { GET: { "dialogOpen": true } } });
2396
+ // lib/types/types/dnd.js
2397
+ Internal.define({
2398
+ "/dnd.endDnd": { POST: { "dndEndDnd": true } },
2399
+ "/dnd.endSnooze": { POST: { "dndEndSnooze": true } },
2400
+ "/dnd.info": { GET: { "dndInfo": false } },
2401
+ "/dnd.setSnooze": { POST: { "dndSetSnooze": false } },
2402
+ "/dnd.teamInfo": { GET: { "dndTeamInfo": false } }
2403
+ });
2404
+ // lib/types/types/emoji.js
2405
+ Internal.define({ "/emoji.list": { GET: { "emojiList": false } } });
2406
+ // lib/types/types/files.js
2407
+ Internal.define({
2408
+ "/files.comments.delete": { POST: { "filesCommentsDelete": true } },
2409
+ "/files.delete": { POST: { "filesDelete": true } },
2410
+ "/files.info": { GET: { "filesInfo": false } },
2411
+ "/files.list": { GET: { "filesList": false } },
2412
+ "/files.remote.add": { POST: { "filesRemoteAdd": false } },
2413
+ "/files.remote.info": { GET: { "filesRemoteInfo": false } },
2414
+ "/files.remote.list": { GET: { "filesRemoteList": false } },
2415
+ "/files.remote.remove": { POST: { "filesRemoteRemove": false } },
2416
+ "/files.remote.share": { GET: { "filesRemoteShare": false } },
2417
+ "/files.remote.update": { POST: { "filesRemoteUpdate": false } },
2418
+ "/files.revokePublicURL": { POST: { "filesRevokePublicURL": true } },
2419
+ "/files.sharedPublicURL": { POST: { "filesSharedPublicURL": true } },
2420
+ "/files.upload": { POST: { "filesUpload": false } }
2421
+ });
2422
+ // lib/types/types/migration.js
2423
+ Internal.define({ "/migration.exchange": { GET: { "migrationExchange": false } } });
2424
+ // lib/types/types/oauth.js
2425
+ Internal.define({
2426
+ "/oauth.access": { GET: { "oauthAccess": false } },
2427
+ "/oauth.token": { GET: { "oauthToken": false } },
2428
+ "/oauth.v2.access": { GET: { "oauthV2Access": false } }
2429
+ });
2430
+ // lib/types/types/pins.js
2431
+ Internal.define({
2432
+ "/pins.add": { POST: { "pinsAdd": true } },
2433
+ "/pins.list": { GET: { "pinsList": false } },
2434
+ "/pins.remove": { POST: { "pinsRemove": true } }
2435
+ });
2436
+ // lib/types/types/reactions.js
2437
+ Internal.define({
2438
+ "/reactions.add": { POST: { "reactionsAdd": true } },
2439
+ "/reactions.get": { GET: { "reactionsGet": false } },
2440
+ "/reactions.list": { GET: { "reactionsList": false } },
2441
+ "/reactions.remove": { POST: { "reactionsRemove": true } }
2442
+ });
2443
+ // lib/types/types/reminders.js
2444
+ Internal.define({
2445
+ "/reminders.add": { POST: { "remindersAdd": true } },
2446
+ "/reminders.complete": { POST: { "remindersComplete": true } },
2447
+ "/reminders.delete": { POST: { "remindersDelete": true } },
2448
+ "/reminders.info": { GET: { "remindersInfo": false } },
2449
+ "/reminders.list": { GET: { "remindersList": false } }
2450
+ });
2451
+ // lib/types/types/rtm.js
2452
+ Internal.define({ "/rtm.connect": { GET: { "rtmConnect": false } } });
2453
+ // lib/types/types/search.js
2454
+ Internal.define({ "/search.messages": { GET: { "searchMessages": false } } });
2455
+ // lib/types/types/stars.js
2456
+ Internal.define({
2457
+ "/stars.add": { POST: { "starsAdd": true } },
2458
+ "/stars.list": { GET: { "starsList": false } },
2459
+ "/stars.remove": { POST: { "starsRemove": true } }
2460
+ });
2461
+ // lib/types/types/team.js
2462
+ Internal.define({
2463
+ "/team.accessLogs": { GET: { "teamAccessLogs": false } },
2464
+ "/team.billableInfo": { GET: { "teamBillableInfo": false } },
2465
+ "/team.info": { GET: { "teamInfo": false } },
2466
+ "/team.integrationLogs": { GET: { "teamIntegrationLogs": false } },
2467
+ "/team.profile.get": { GET: { "teamProfileGet": false } }
2468
+ });
2469
+ // lib/types/types/usergroups.js
2470
+ Internal.define({
2471
+ "/usergroups.create": { POST: { "usergroupsCreate": true } },
2472
+ "/usergroups.disable": { POST: { "usergroupsDisable": true } },
2473
+ "/usergroups.enable": { POST: { "usergroupsEnable": true } },
2474
+ "/usergroups.list": { GET: { "usergroupsList": false } },
2475
+ "/usergroups.update": { POST: { "usergroupsUpdate": true } },
2476
+ "/usergroups.users.list": { GET: { "usergroupsUsersList": false } },
2477
+ "/usergroups.users.update": { POST: { "usergroupsUsersUpdate": true } }
2478
+ });
2479
+ // lib/types/types/users.js
2480
+ Internal.define({
2481
+ "/users.conversations": { GET: { "usersConversations": false } },
2482
+ "/users.deletePhoto": { POST: { "usersDeletePhoto": false } },
2483
+ "/users.getPresence": { GET: { "usersGetPresence": false } },
2484
+ "/users.identity": { GET: { "usersIdentity": false } },
2485
+ "/users.info": { GET: { "usersInfo": false } },
2486
+ "/users.list": { GET: { "usersList": false } },
2487
+ "/users.lookupByEmail": { GET: { "usersLookupByEmail": false } },
2488
+ "/users.profile.get": { GET: { "usersProfileGet": false } },
2489
+ "/users.profile.set": { POST: { "usersProfileSet": true } },
2490
+ "/users.setActive": { POST: { "usersSetActive": true } },
2491
+ "/users.setPhoto": { POST: { "usersSetPhoto": false } },
2492
+ "/users.setPresence": { POST: { "usersSetPresence": true } }
2493
+ });
2494
+ // lib/types/types/views.js
2495
+ Internal.define({
2496
+ "/views.open": { GET: { "viewsOpen": true } },
2497
+ "/views.publish": { GET: { "viewsPublish": true } },
2498
+ "/views.push": { GET: { "viewsPush": true } },
2499
+ "/views.update": { GET: { "viewsUpdate": true } }
2500
+ });
2501
+ // lib/types/types/workflows.js
2502
+ Internal.define({
2503
+ "/workflows.stepCompleted": { GET: { "workflowsStepCompleted": true } },
2504
+ "/workflows.stepFailed": { GET: { "workflowsStepFailed": true } },
2505
+ "/workflows.updateStep": { GET: { "workflowsUpdateStep": true } }
2506
+ });
2507
+ // lib/types/types/index.js
2508
+ var types_exports = /* @__PURE__ */ __exportAll({
2509
+ Internal: () => Internal,
2510
+ Token: () => Token
2511
+ });
2512
+ // lib/types/bot.js
2513
+ /** Message of any caught value, for a log line. */
2514
+ function messageOf(error) {
2515
+ return error instanceof Error ? error.message : String(error);
2516
+ }
2517
+ /**
2518
+ * Name of an attachment whose element declared none.
2519
+ * @param ref - the unresolved resource.
2520
+ * @returns the source's file name, else one naming the kind.
2521
+ */
2522
+ function uploadName(ref) {
2523
+ const named = fileName(void 0, ref.src);
2524
+ return named === "file" ? `slack-${ref.kind}` : named;
2525
+ }
2526
+ /**
2527
+ * Slack adapter.
2528
+ *
2529
+ * Identity is the configured `selfId`, checked against `auth.test` on connect; Socket Mode and the Events API are the
2530
+ * two transports; `mrkdwn` is the only mode, because Slack message text is the only way the upstream adapter ever
2531
+ * rendered content. Inbound media is served from the bot's own `satori:` route, because `url_private` needs the bot
2532
+ * token and the host does not have it.
2533
+ */
2534
+ var SlackBot = class extends Adapter {
2535
+ /** The adapter needs the Satori service and the isolated `http` service. */
2536
+ static inject = ["satori", "http"];
2537
+ /** The Loader applies this schema to a profile row's `config` before the constructor runs. */
2538
+ static Config = Config;
2539
+ modes;
2540
+ modeOrder = ["mrkdwn"];
2541
+ /** Endpoints shared by every Web API call of this bot. */
2542
+ api;
2543
+ /** Full typed Slack Web API surface registered by the migrated declarations. */
2544
+ internal;
2545
+ /** `team_id` of the installation, once `auth.test` answered. */
2546
+ teamId;
2547
+ transport;
2548
+ constructor(ctx, config) {
2549
+ const invalid = configError(config);
2550
+ if (invalid !== void 0) throw invalid;
2551
+ super(ctx, config, {
2552
+ id: `slack:${config.selfId}`,
2553
+ platform: "slack",
2554
+ adapter: "slack"
2555
+ });
2556
+ this.selfId = config.selfId;
2557
+ this.api = createSlackApi(ctx, config);
2558
+ this.internal = new Internal(this, this.ctx.http.extend({ baseUrl: `${this.api.base}/` }));
2559
+ this.modes = { mrkdwn: createMrkdwnMode(config.replyBroadcast) };
2560
+ this.defineInternalRoute("/files/:fileId", async ({ params }) => this.serveFile(params.fileId));
2561
+ }
2562
+ async connect() {
2563
+ try {
2564
+ const identity = await verifyIdentity(this.api, this.config.selfId);
2565
+ this.selfId = identity.userId;
2566
+ this.teamId = identity.teamId;
2567
+ this.user = {
2568
+ id: identity.userId,
2569
+ name: identity.userName === "" ? identity.userId : identity.userName,
2570
+ isBot: true
2571
+ };
2572
+ } catch (error) {
2573
+ this.ctx.logger.error("slack: connect failed: %s", messageOf(error));
2574
+ throw error;
2575
+ }
2576
+ this.transport = this.config.protocol === "http" ? new SlackWebhook(this) : new SlackSocketMode(this);
2577
+ await this.transport.start();
2578
+ }
2579
+ async disconnect() {
2580
+ const transport = this.transport;
2581
+ this.transport = void 0;
2582
+ await transport?.stop();
2583
+ }
2584
+ /**
2585
+ * Upload one outbound attachment through the two-step file API.
2586
+ *
2587
+ * `files.upload` is retired, so the bytes go to a pre-signed URL and the returned file id is what
2588
+ * `files.completeUploadExternal` shares into the channel.
2589
+ */
2590
+ async upload(ref, _scope, ctx) {
2591
+ const fetched = await ctx.fetch(ref.src, ctx.signal);
2592
+ const name = ref.meta.name ?? fetched.name ?? uploadName(ref);
2593
+ const ticket = await startUpload(this.api, {
2594
+ name,
2595
+ length: fetched.data.byteLength
2596
+ }, ctx.signal);
2597
+ await putUploadBytes(this.api, ticket, fetched.data, ctx.signal);
2598
+ return {
2599
+ key: ticket.fileId,
2600
+ extra: { name }
2601
+ };
2602
+ }
2603
+ resourceScope(_target, _kind) {
2604
+ return this.id;
2605
+ }
2606
+ async sendPayload(payload, target, ctx) {
2607
+ return await sendPayload(this.sendDeps(), payload, target, ctx);
2608
+ }
2609
+ async deletePart(part, handle) {
2610
+ await deletePart(this.sendDeps(), part, handle);
2611
+ }
2612
+ async members(chat, cursor, limit) {
2613
+ return await members(this.sendDeps(), chat, cursor, limit);
2614
+ }
2615
+ async getMessage(chat, id) {
2616
+ return await getMessage(this.sendDeps(), this, chat, id);
2617
+ }
2618
+ async createReaction(message, emoji) {
2619
+ await createReaction(this.sendDeps(), message, emoji);
2620
+ }
2621
+ async deleteReaction(message, emoji) {
2622
+ await deleteReaction(this.sendDeps(), message, emoji);
2623
+ }
2624
+ classify(error) {
2625
+ return classifySlackError(error);
2626
+ }
2627
+ sendDeps() {
2628
+ return {
2629
+ api: this.api,
2630
+ teamId: this.teamId
2631
+ };
2632
+ }
2633
+ /**
2634
+ * Resolve one `satori:` file route.
2635
+ *
2636
+ * `files.info` names the download URL, which is fetched with the bot token only when its host belongs to Slack; the
2637
+ * bytes are streamed back to the host without buffering.
2638
+ */
2639
+ async serveFile(fileId) {
2640
+ try {
2641
+ const src = (await callApi(this.api, "filesInfo", { file: fileId })).file?.url_private;
2642
+ if (src === void 0 || src === "") return new Response(null, { status: 404 });
2643
+ const response = await downloadFile(this.api, src);
2644
+ const headers = new Headers();
2645
+ const mime = response.headers.get("content-type");
2646
+ if (mime !== null) headers.set("content-type", mime);
2647
+ return new Response(response.body, {
2648
+ status: response.status,
2649
+ headers
2650
+ });
2651
+ } catch (error) {
2652
+ this.ctx.logger.warn("slack: file %s could not be served: %s", fileId, messageOf(error));
2653
+ return new Response(null, { status: 502 });
2654
+ }
2655
+ }
2656
+ };
2657
+ export { Config, Internal, SLACK_LIMITS, types_exports as Slack, SlackApiError, SlackBot, SlackBot as default, SlackFatalError, SlackIdentityError, SlackSocketMode, SlackWebhook, callApi, classifyCode, classifySlackError, configError, createMrkdwnMode, createSlackApi, decodeEvent, decodeMessage, downloadFile, ensureOk, escape, finishUpload, isSlackFileUrl, matchesSignature, parseMrkdwn, putUploadBytes, retryAfterOf, routePath, signatureOf, startUpload, unescape, verifyIdentity };
2658
+
2659
+ //# sourceMappingURL=index.js.map