@desplega.ai/slack-mock 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.
- package/README.md +113 -0
- package/dist/body.d.ts +6 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +94 -0
- package/dist/events.d.ts +36 -0
- package/dist/ids.d.ts +8 -0
- package/dist/index-thgwpw70.js +3693 -0
- package/dist/index-v7mbr1cx.js +48 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +17 -0
- package/dist/render/blocks.d.ts +7 -0
- package/dist/render/index.d.ts +25 -0
- package/dist/render/mrkdwn.d.ts +16 -0
- package/dist/screenshot.d.ts +13 -0
- package/dist/screenshot.js +9 -0
- package/dist/server.d.ts +240 -0
- package/dist/socket-mode.d.ts +73 -0
- package/dist/store.d.ts +150 -0
- package/dist/types.d.ts +211 -0
- package/dist/web-api.d.ts +26 -0
- package/package.json +60 -0
- package/src/body.ts +84 -0
- package/src/cli.ts +89 -0
- package/src/events.ts +281 -0
- package/src/ids.ts +29 -0
- package/src/index.ts +13 -0
- package/src/render/blocks.ts +392 -0
- package/src/render/index.ts +846 -0
- package/src/render/mrkdwn.ts +321 -0
- package/src/screenshot.ts +59 -0
- package/src/server.ts +1198 -0
- package/src/socket-mode.ts +261 -0
- package/src/store.ts +654 -0
- package/src/types.ts +159 -0
- package/src/web-api.ts +694 -0
|
@@ -0,0 +1,3693 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/store.ts
|
|
3
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "fs";
|
|
4
|
+
import { dirname } from "path";
|
|
5
|
+
|
|
6
|
+
// src/ids.ts
|
|
7
|
+
var ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ0123456789";
|
|
8
|
+
function slackId(prefix, length = 8) {
|
|
9
|
+
let out = prefix;
|
|
10
|
+
for (let i = 0;i < length; i++)
|
|
11
|
+
out += ALPHABET[Math.floor(Math.random() * ALPHABET.length)];
|
|
12
|
+
return out;
|
|
13
|
+
}
|
|
14
|
+
var lastMicros = 0;
|
|
15
|
+
function nextTs() {
|
|
16
|
+
let micros = Date.now() * 1000;
|
|
17
|
+
if (micros <= lastMicros)
|
|
18
|
+
micros = lastMicros + 1;
|
|
19
|
+
lastMicros = micros;
|
|
20
|
+
const seconds = Math.floor(micros / 1e6);
|
|
21
|
+
const fraction = (micros % 1e6).toString().padStart(6, "0");
|
|
22
|
+
return `${seconds}.${fraction}`;
|
|
23
|
+
}
|
|
24
|
+
function nowUnix() {
|
|
25
|
+
return Math.floor(Date.now() / 1000);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// src/store.ts
|
|
29
|
+
class SlackApiError extends Error {
|
|
30
|
+
code;
|
|
31
|
+
extra;
|
|
32
|
+
constructor(code, extra = {}) {
|
|
33
|
+
super(code);
|
|
34
|
+
this.code = code;
|
|
35
|
+
this.extra = extra;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
class Store {
|
|
40
|
+
team;
|
|
41
|
+
app;
|
|
42
|
+
bot;
|
|
43
|
+
users = new Map;
|
|
44
|
+
channels = new Map;
|
|
45
|
+
messages = new Map;
|
|
46
|
+
files = new Map;
|
|
47
|
+
views = new Map;
|
|
48
|
+
ephemerals = [];
|
|
49
|
+
apiCalls = [];
|
|
50
|
+
assistantThreads = new Map;
|
|
51
|
+
listeners = new Set;
|
|
52
|
+
dataFile;
|
|
53
|
+
replaying = false;
|
|
54
|
+
constructor(opts = {}) {
|
|
55
|
+
this.team = {
|
|
56
|
+
id: opts.teamId ?? "T0MOCK0000",
|
|
57
|
+
name: opts.teamName ?? "Mock Workspace",
|
|
58
|
+
domain: opts.teamDomain ?? "mock"
|
|
59
|
+
};
|
|
60
|
+
this.app = { id: opts.appId ?? "A0MOCK0000", name: opts.appName ?? "mock-bot" };
|
|
61
|
+
this.bot = {
|
|
62
|
+
userId: opts.botUserId ?? "U0BOT00000",
|
|
63
|
+
botId: opts.botId ?? "B0BOT00000",
|
|
64
|
+
token: opts.botToken ?? "xoxb-mock-bot-token",
|
|
65
|
+
appToken: opts.appToken ?? "xapp-mock-app-token",
|
|
66
|
+
userToken: opts.userToken
|
|
67
|
+
};
|
|
68
|
+
this.dataFile = opts.dataFile;
|
|
69
|
+
if (this.dataFile && existsSync(this.dataFile))
|
|
70
|
+
this.replay(this.dataFile);
|
|
71
|
+
if (!this.users.has(this.bot.userId)) {
|
|
72
|
+
this.addUser({
|
|
73
|
+
id: this.bot.userId,
|
|
74
|
+
name: this.app.name,
|
|
75
|
+
real_name: this.app.name,
|
|
76
|
+
is_bot: true
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
onChange(listener) {
|
|
81
|
+
this.listeners.add(listener);
|
|
82
|
+
return () => this.listeners.delete(listener);
|
|
83
|
+
}
|
|
84
|
+
onChangeEmit(change) {
|
|
85
|
+
this.emit(change);
|
|
86
|
+
}
|
|
87
|
+
emit(change) {
|
|
88
|
+
if (this.dataFile && !this.replaying && change.kind !== "api.call") {
|
|
89
|
+
appendFileSync(this.dataFile, `${JSON.stringify({ at: new Date().toISOString(), ...stripBytes(change) })}
|
|
90
|
+
`);
|
|
91
|
+
}
|
|
92
|
+
for (const l of this.listeners)
|
|
93
|
+
l(change);
|
|
94
|
+
}
|
|
95
|
+
replay(file) {
|
|
96
|
+
this.replaying = true;
|
|
97
|
+
try {
|
|
98
|
+
let lineNo = 0;
|
|
99
|
+
for (const line of readFileSync(file, "utf8").split(`
|
|
100
|
+
`)) {
|
|
101
|
+
lineNo += 1;
|
|
102
|
+
if (!line.trim())
|
|
103
|
+
continue;
|
|
104
|
+
try {
|
|
105
|
+
this.applyReplayed(JSON.parse(line));
|
|
106
|
+
} catch (e) {
|
|
107
|
+
console.warn(`[slack-mock] skipping corrupt journal line ${lineNo} in ${file}: ${e instanceof Error ? e.message : e}`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
} finally {
|
|
111
|
+
this.replaying = false;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
applyReplayed(change) {
|
|
115
|
+
switch (change.kind) {
|
|
116
|
+
case "user.add":
|
|
117
|
+
this.users.set(change.user.id, change.user);
|
|
118
|
+
break;
|
|
119
|
+
case "channel.add":
|
|
120
|
+
case "channel.update":
|
|
121
|
+
this.channels.set(change.channel.id, change.channel);
|
|
122
|
+
break;
|
|
123
|
+
case "member.join": {
|
|
124
|
+
const c = this.channels.get(change.channel.id);
|
|
125
|
+
if (c && !c.members.includes(change.user))
|
|
126
|
+
c.members.push(change.user);
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
case "message.add":
|
|
130
|
+
this.insertMessage(change.message);
|
|
131
|
+
break;
|
|
132
|
+
case "message.update":
|
|
133
|
+
case "reaction.add":
|
|
134
|
+
case "reaction.remove": {
|
|
135
|
+
const list = this.messages.get(change.message.channel);
|
|
136
|
+
const i = list?.findIndex((m) => m.ts === change.message.ts) ?? -1;
|
|
137
|
+
if (list && i >= 0)
|
|
138
|
+
list[i] = change.message;
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
case "message.delete": {
|
|
142
|
+
const list = this.messages.get(change.message.channel);
|
|
143
|
+
const i = list?.findIndex((m) => m.ts === change.message.ts) ?? -1;
|
|
144
|
+
if (list && i >= 0)
|
|
145
|
+
list.splice(i, 1);
|
|
146
|
+
break;
|
|
147
|
+
}
|
|
148
|
+
case "file.add":
|
|
149
|
+
this.files.set(change.file.id, change.file);
|
|
150
|
+
break;
|
|
151
|
+
default:
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
addUser(input) {
|
|
156
|
+
const id = input.id ?? slackId("U");
|
|
157
|
+
const realName = input.real_name ?? input.name;
|
|
158
|
+
const user = {
|
|
159
|
+
id,
|
|
160
|
+
team_id: this.team.id,
|
|
161
|
+
name: input.name,
|
|
162
|
+
real_name: realName,
|
|
163
|
+
deleted: false,
|
|
164
|
+
is_bot: input.is_bot ?? false,
|
|
165
|
+
is_admin: input.is_admin ?? false,
|
|
166
|
+
is_app_user: false,
|
|
167
|
+
tz: input.tz ?? "UTC",
|
|
168
|
+
profile: {
|
|
169
|
+
real_name: realName,
|
|
170
|
+
display_name: input.name,
|
|
171
|
+
real_name_normalized: realName,
|
|
172
|
+
display_name_normalized: input.name,
|
|
173
|
+
email: input.email,
|
|
174
|
+
team: this.team.id
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
this.users.set(id, user);
|
|
178
|
+
this.emit({ kind: "user.add", user });
|
|
179
|
+
return user;
|
|
180
|
+
}
|
|
181
|
+
user(id) {
|
|
182
|
+
const u = this.users.get(id);
|
|
183
|
+
if (!u)
|
|
184
|
+
throw new SlackApiError("user_not_found");
|
|
185
|
+
return u;
|
|
186
|
+
}
|
|
187
|
+
userByEmail(email) {
|
|
188
|
+
for (const u of this.users.values())
|
|
189
|
+
if (u.profile.email === email)
|
|
190
|
+
return u;
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
isBotUser(userId) {
|
|
194
|
+
return userId === this.bot.userId;
|
|
195
|
+
}
|
|
196
|
+
addChannel(input) {
|
|
197
|
+
const name = input.name.replace(/^#/, "");
|
|
198
|
+
for (const c of this.channels.values()) {
|
|
199
|
+
if (c.name === name && !c.is_im)
|
|
200
|
+
throw new SlackApiError("name_taken");
|
|
201
|
+
}
|
|
202
|
+
const id = input.id ?? slackId(input.is_private ? "G" : "C");
|
|
203
|
+
const creator = input.creator ?? this.bot.userId;
|
|
204
|
+
const members = [...new Set([creator, ...input.members ?? []])];
|
|
205
|
+
const channel = {
|
|
206
|
+
id,
|
|
207
|
+
name,
|
|
208
|
+
is_channel: !input.is_private,
|
|
209
|
+
is_group: !!input.is_private,
|
|
210
|
+
is_im: false,
|
|
211
|
+
is_mpim: false,
|
|
212
|
+
is_private: !!input.is_private,
|
|
213
|
+
is_archived: false,
|
|
214
|
+
is_general: name === "general",
|
|
215
|
+
created: nowUnix(),
|
|
216
|
+
creator,
|
|
217
|
+
topic: { value: input.topic ?? "", creator, last_set: 0 },
|
|
218
|
+
purpose: { value: input.purpose ?? "", creator, last_set: 0 },
|
|
219
|
+
members
|
|
220
|
+
};
|
|
221
|
+
this.channels.set(id, channel);
|
|
222
|
+
this.messages.set(id, []);
|
|
223
|
+
this.emit({ kind: "channel.add", channel });
|
|
224
|
+
return channel;
|
|
225
|
+
}
|
|
226
|
+
openDm(userId) {
|
|
227
|
+
this.user(userId);
|
|
228
|
+
for (const c of this.channels.values())
|
|
229
|
+
if (c.is_im && c.user === userId)
|
|
230
|
+
return c;
|
|
231
|
+
const id = slackId("D");
|
|
232
|
+
const channel = {
|
|
233
|
+
id,
|
|
234
|
+
name: id,
|
|
235
|
+
is_channel: false,
|
|
236
|
+
is_group: false,
|
|
237
|
+
is_im: true,
|
|
238
|
+
is_mpim: false,
|
|
239
|
+
is_private: true,
|
|
240
|
+
is_archived: false,
|
|
241
|
+
is_general: false,
|
|
242
|
+
created: nowUnix(),
|
|
243
|
+
creator: userId,
|
|
244
|
+
user: userId,
|
|
245
|
+
topic: { value: "", creator: "", last_set: 0 },
|
|
246
|
+
purpose: { value: "", creator: "", last_set: 0 },
|
|
247
|
+
members: [userId, this.bot.userId]
|
|
248
|
+
};
|
|
249
|
+
this.channels.set(id, channel);
|
|
250
|
+
this.messages.set(id, []);
|
|
251
|
+
this.emit({ kind: "channel.add", channel });
|
|
252
|
+
return channel;
|
|
253
|
+
}
|
|
254
|
+
channel(id) {
|
|
255
|
+
const c = this.channels.get(id);
|
|
256
|
+
if (!c)
|
|
257
|
+
throw new SlackApiError("channel_not_found");
|
|
258
|
+
return c;
|
|
259
|
+
}
|
|
260
|
+
channelByName(name) {
|
|
261
|
+
const n = name.replace(/^#/, "");
|
|
262
|
+
for (const c of this.channels.values())
|
|
263
|
+
if (c.name === n)
|
|
264
|
+
return c;
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
channelType(c) {
|
|
268
|
+
if (c.is_im)
|
|
269
|
+
return "im";
|
|
270
|
+
if (c.is_mpim)
|
|
271
|
+
return "mpim";
|
|
272
|
+
if (c.is_private)
|
|
273
|
+
return "group";
|
|
274
|
+
return "channel";
|
|
275
|
+
}
|
|
276
|
+
join(channelId, userId, inviter) {
|
|
277
|
+
const channel = this.channel(channelId);
|
|
278
|
+
if (channel.is_archived)
|
|
279
|
+
throw new SlackApiError("is_archived");
|
|
280
|
+
if (channel.members.includes(userId))
|
|
281
|
+
return { alreadyMember: true };
|
|
282
|
+
channel.members.push(userId);
|
|
283
|
+
this.emit({ kind: "member.join", channel, user: userId, inviter });
|
|
284
|
+
return { alreadyMember: false };
|
|
285
|
+
}
|
|
286
|
+
archive(channelId) {
|
|
287
|
+
const channel = this.channel(channelId);
|
|
288
|
+
if (channel.is_archived)
|
|
289
|
+
throw new SlackApiError("already_archived");
|
|
290
|
+
if (channel.is_general)
|
|
291
|
+
throw new SlackApiError("cant_archive_general");
|
|
292
|
+
channel.is_archived = true;
|
|
293
|
+
this.emit({ kind: "channel.update", channel });
|
|
294
|
+
}
|
|
295
|
+
insertMessage(message) {
|
|
296
|
+
const list = this.messages.get(message.channel) ?? [];
|
|
297
|
+
this.messages.set(message.channel, list);
|
|
298
|
+
let i = list.length;
|
|
299
|
+
while (i > 0 && Number(list[i - 1].ts) > Number(message.ts))
|
|
300
|
+
i--;
|
|
301
|
+
list.splice(i, 0, message);
|
|
302
|
+
if (message.thread_ts && message.thread_ts !== message.ts) {
|
|
303
|
+
const parent = this.findMessage(message.channel, message.thread_ts);
|
|
304
|
+
if (parent) {
|
|
305
|
+
parent.reply_count = (parent.reply_count ?? 0) + 1;
|
|
306
|
+
const users = new Set(parent.reply_users ?? []);
|
|
307
|
+
if (message.user)
|
|
308
|
+
users.add(message.user);
|
|
309
|
+
parent.reply_users = [...users];
|
|
310
|
+
parent.reply_users_count = users.size;
|
|
311
|
+
parent.latest_reply = message.ts;
|
|
312
|
+
if (parent.user)
|
|
313
|
+
message.parent_user_id = parent.user;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
findMessage(channelId, ts) {
|
|
318
|
+
return this.messages.get(channelId)?.find((m) => m.ts === ts);
|
|
319
|
+
}
|
|
320
|
+
findAnyMessage(channelId, ts) {
|
|
321
|
+
return this.findMessage(channelId, ts) ?? this.ephemerals.find((m) => m.channel === channelId && m.ts === ts);
|
|
322
|
+
}
|
|
323
|
+
updateEphemeral(channelId, ts, patch) {
|
|
324
|
+
const m = this.ephemerals.find((x) => x.channel === channelId && x.ts === ts);
|
|
325
|
+
if (!m)
|
|
326
|
+
throw new SlackApiError("message_not_found");
|
|
327
|
+
Object.assign(m, patch);
|
|
328
|
+
return m;
|
|
329
|
+
}
|
|
330
|
+
deleteEphemeral(channelId, ts) {
|
|
331
|
+
const i = this.ephemerals.findIndex((x) => x.channel === channelId && x.ts === ts);
|
|
332
|
+
if (i < 0)
|
|
333
|
+
throw new SlackApiError("message_not_found");
|
|
334
|
+
this.ephemerals.splice(i, 1);
|
|
335
|
+
}
|
|
336
|
+
message(channelId, ts) {
|
|
337
|
+
const m = this.findMessage(channelId, ts);
|
|
338
|
+
if (!m)
|
|
339
|
+
throw new SlackApiError("message_not_found");
|
|
340
|
+
return m;
|
|
341
|
+
}
|
|
342
|
+
addMessage(input) {
|
|
343
|
+
const channel = this.channel(input.channel);
|
|
344
|
+
if (channel.is_archived)
|
|
345
|
+
throw new SlackApiError("is_archived");
|
|
346
|
+
if (input.thread_ts && !this.findMessage(input.channel, input.thread_ts)) {
|
|
347
|
+
throw new SlackApiError("thread_not_found");
|
|
348
|
+
}
|
|
349
|
+
const message = {
|
|
350
|
+
type: "message",
|
|
351
|
+
team: this.team.id,
|
|
352
|
+
ts: input.ts ?? nextTs(),
|
|
353
|
+
...input
|
|
354
|
+
};
|
|
355
|
+
if (message.ephemeral_user)
|
|
356
|
+
this.ephemerals.push(message);
|
|
357
|
+
else
|
|
358
|
+
this.insertMessage(message);
|
|
359
|
+
this.emit({ kind: "message.add", message });
|
|
360
|
+
return message;
|
|
361
|
+
}
|
|
362
|
+
updateMessage(channelId, ts, patch, editor) {
|
|
363
|
+
const message = this.message(channelId, ts);
|
|
364
|
+
const previous = structuredClone(message);
|
|
365
|
+
Object.assign(message, patch, { edited: { user: editor, ts: nextTs() } });
|
|
366
|
+
this.emit({ kind: "message.update", message, previous });
|
|
367
|
+
return message;
|
|
368
|
+
}
|
|
369
|
+
deleteMessage(channelId, ts) {
|
|
370
|
+
const list = this.messages.get(channelId);
|
|
371
|
+
const i = list?.findIndex((m) => m.ts === ts) ?? -1;
|
|
372
|
+
if (!list || i < 0)
|
|
373
|
+
throw new SlackApiError("message_not_found");
|
|
374
|
+
const [message] = list.splice(i, 1);
|
|
375
|
+
if (message.thread_ts && message.thread_ts !== ts) {
|
|
376
|
+
const parent = this.findMessage(channelId, message.thread_ts);
|
|
377
|
+
if (parent?.reply_count)
|
|
378
|
+
parent.reply_count -= 1;
|
|
379
|
+
}
|
|
380
|
+
this.emit({ kind: "message.delete", message });
|
|
381
|
+
return message;
|
|
382
|
+
}
|
|
383
|
+
addReaction(channelId, ts, name, userId) {
|
|
384
|
+
const message = this.message(channelId, ts);
|
|
385
|
+
message.reactions ??= [];
|
|
386
|
+
let reaction = message.reactions.find((r) => r.name === name);
|
|
387
|
+
if (reaction?.users.includes(userId))
|
|
388
|
+
throw new SlackApiError("already_reacted");
|
|
389
|
+
if (!reaction) {
|
|
390
|
+
reaction = { name, users: [], count: 0 };
|
|
391
|
+
message.reactions.push(reaction);
|
|
392
|
+
}
|
|
393
|
+
reaction.users.push(userId);
|
|
394
|
+
reaction.count = reaction.users.length;
|
|
395
|
+
this.emit({ kind: "reaction.add", message, name, user: userId });
|
|
396
|
+
return message;
|
|
397
|
+
}
|
|
398
|
+
removeReaction(channelId, ts, name, userId) {
|
|
399
|
+
const message = this.message(channelId, ts);
|
|
400
|
+
const reaction = message.reactions?.find((r) => r.name === name);
|
|
401
|
+
if (!reaction?.users.includes(userId))
|
|
402
|
+
throw new SlackApiError("no_reaction");
|
|
403
|
+
reaction.users = reaction.users.filter((u) => u !== userId);
|
|
404
|
+
reaction.count = reaction.users.length;
|
|
405
|
+
message.reactions = message.reactions.filter((r) => r.count > 0);
|
|
406
|
+
if (message.reactions.length === 0)
|
|
407
|
+
message.reactions = undefined;
|
|
408
|
+
this.emit({ kind: "reaction.remove", message, name, user: userId });
|
|
409
|
+
return message;
|
|
410
|
+
}
|
|
411
|
+
history(channelId, q = {}) {
|
|
412
|
+
this.channel(channelId);
|
|
413
|
+
const all = (this.messages.get(channelId) ?? []).filter((m) => !m.thread_ts || m.thread_ts === m.ts || m.subtype === "thread_broadcast");
|
|
414
|
+
return paginate(all, q);
|
|
415
|
+
}
|
|
416
|
+
replies(channelId, threadTs, q = {}) {
|
|
417
|
+
const parent = this.message(channelId, threadTs);
|
|
418
|
+
const all = [
|
|
419
|
+
parent,
|
|
420
|
+
...(this.messages.get(channelId) ?? []).filter((m) => m.thread_ts === threadTs && m.ts !== threadTs)
|
|
421
|
+
];
|
|
422
|
+
return paginate(all, q);
|
|
423
|
+
}
|
|
424
|
+
addFile(input) {
|
|
425
|
+
const id = input.id ?? slackId("F");
|
|
426
|
+
const ext = input.name.includes(".") ? input.name.split(".").pop().toLowerCase() : "";
|
|
427
|
+
const mimetype = input.mimetype ?? guessMime(ext);
|
|
428
|
+
const now = nowUnix();
|
|
429
|
+
const file = {
|
|
430
|
+
id,
|
|
431
|
+
created: now,
|
|
432
|
+
timestamp: now,
|
|
433
|
+
name: input.name,
|
|
434
|
+
title: input.title ?? input.name,
|
|
435
|
+
mimetype,
|
|
436
|
+
filetype: ext || "binary",
|
|
437
|
+
pretty_type: ext ? ext.toUpperCase() : "Binary",
|
|
438
|
+
user: input.user,
|
|
439
|
+
size: input.bytes.byteLength,
|
|
440
|
+
mode: "hosted",
|
|
441
|
+
is_external: false,
|
|
442
|
+
is_public: false,
|
|
443
|
+
url_private: `${input.baseUrl}/files-pri/${this.team.id}-${id}/${encodeURIComponent(input.name)}`,
|
|
444
|
+
url_private_download: `${input.baseUrl}/files-pri/${this.team.id}-${id}/download/${encodeURIComponent(input.name)}`,
|
|
445
|
+
permalink: `${input.baseUrl}/files/${input.user}/${id}/${encodeURIComponent(input.name)}`,
|
|
446
|
+
channels: [],
|
|
447
|
+
bytes: input.bytes
|
|
448
|
+
};
|
|
449
|
+
if (mimetype.startsWith("image/")) {
|
|
450
|
+
const thumbs = file;
|
|
451
|
+
for (const size of [64, 80, 160, 360, 480])
|
|
452
|
+
thumbs[`thumb_${size}`] = file.url_private;
|
|
453
|
+
}
|
|
454
|
+
this.files.set(id, file);
|
|
455
|
+
this.emit({ kind: "file.add", file });
|
|
456
|
+
return file;
|
|
457
|
+
}
|
|
458
|
+
file(id) {
|
|
459
|
+
const f = this.files.get(id);
|
|
460
|
+
if (!f)
|
|
461
|
+
throw new SlackApiError("file_not_found");
|
|
462
|
+
return f;
|
|
463
|
+
}
|
|
464
|
+
openView(view) {
|
|
465
|
+
const id = view.id ?? slackId("V");
|
|
466
|
+
const full = {
|
|
467
|
+
...view,
|
|
468
|
+
id,
|
|
469
|
+
team_id: this.team.id,
|
|
470
|
+
app_id: this.app.id,
|
|
471
|
+
bot_id: this.bot.botId,
|
|
472
|
+
hash: `${nowUnix()}.${slackId("", 6).toLowerCase()}`,
|
|
473
|
+
root_view_id: id
|
|
474
|
+
};
|
|
475
|
+
this.views.set(id, full);
|
|
476
|
+
this.emit({ kind: "view.open", view: full });
|
|
477
|
+
return full;
|
|
478
|
+
}
|
|
479
|
+
recordApiCall(call) {
|
|
480
|
+
this.apiCalls.push(call);
|
|
481
|
+
this.emit({ kind: "api.call", call });
|
|
482
|
+
}
|
|
483
|
+
assistantThread(channel, threadTs) {
|
|
484
|
+
const key = `${channel}:${threadTs}`;
|
|
485
|
+
let t = this.assistantThreads.get(key);
|
|
486
|
+
if (!t) {
|
|
487
|
+
t = {};
|
|
488
|
+
this.assistantThreads.set(key, t);
|
|
489
|
+
}
|
|
490
|
+
return t;
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
function paginate(all, q) {
|
|
494
|
+
let items = all;
|
|
495
|
+
if (q.oldest)
|
|
496
|
+
items = items.filter((m) => q.inclusive ? Number(m.ts) >= Number(q.oldest) : Number(m.ts) > Number(q.oldest));
|
|
497
|
+
if (q.latest)
|
|
498
|
+
items = items.filter((m) => q.inclusive ? Number(m.ts) <= Number(q.latest) : Number(m.ts) < Number(q.latest));
|
|
499
|
+
const start = q.cursor ? Number.parseInt(Buffer.from(q.cursor, "base64").toString("utf8").replace("offset:", ""), 10) || 0 : 0;
|
|
500
|
+
const limit = Math.max(1, Math.min(q.limit ?? 100, 1000));
|
|
501
|
+
const page = items.slice(start, start + limit);
|
|
502
|
+
const has_more = start + limit < items.length;
|
|
503
|
+
return {
|
|
504
|
+
items: page,
|
|
505
|
+
has_more,
|
|
506
|
+
next_cursor: has_more ? Buffer.from(`offset:${start + limit}`).toString("base64") : ""
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
function guessMime(ext) {
|
|
510
|
+
const map = {
|
|
511
|
+
png: "image/png",
|
|
512
|
+
jpg: "image/jpeg",
|
|
513
|
+
jpeg: "image/jpeg",
|
|
514
|
+
gif: "image/gif",
|
|
515
|
+
webp: "image/webp",
|
|
516
|
+
svg: "image/svg+xml",
|
|
517
|
+
txt: "text/plain",
|
|
518
|
+
md: "text/markdown",
|
|
519
|
+
log: "text/plain",
|
|
520
|
+
json: "application/json",
|
|
521
|
+
csv: "text/csv",
|
|
522
|
+
pdf: "application/pdf",
|
|
523
|
+
html: "text/html",
|
|
524
|
+
zip: "application/zip"
|
|
525
|
+
};
|
|
526
|
+
return map[ext] ?? "application/octet-stream";
|
|
527
|
+
}
|
|
528
|
+
function wireMessage(m) {
|
|
529
|
+
const { ephemeral_user: _e, ...rest } = m;
|
|
530
|
+
if (rest.files)
|
|
531
|
+
rest.files = rest.files.map(wireFile);
|
|
532
|
+
return rest;
|
|
533
|
+
}
|
|
534
|
+
function wireFile(f) {
|
|
535
|
+
const { bytes: _b, ...rest } = f;
|
|
536
|
+
return rest;
|
|
537
|
+
}
|
|
538
|
+
function stripBytes(change) {
|
|
539
|
+
if (change.kind === "file.add")
|
|
540
|
+
return { ...change, file: wireFile(change.file) };
|
|
541
|
+
if ("message" in change && change.message.files) {
|
|
542
|
+
return {
|
|
543
|
+
...change,
|
|
544
|
+
message: { ...change.message, files: change.message.files.map(wireFile) }
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
return change;
|
|
548
|
+
}
|
|
549
|
+
function ensureDir(file) {
|
|
550
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// src/server.ts
|
|
554
|
+
import { readFileSync as readFileSync2 } from "fs";
|
|
555
|
+
|
|
556
|
+
// src/body.ts
|
|
557
|
+
var JSON_FIELDS = new Set([
|
|
558
|
+
"blocks",
|
|
559
|
+
"attachments",
|
|
560
|
+
"metadata",
|
|
561
|
+
"files",
|
|
562
|
+
"view",
|
|
563
|
+
"prompts",
|
|
564
|
+
"icons",
|
|
565
|
+
"user_ids",
|
|
566
|
+
"types",
|
|
567
|
+
"chunks",
|
|
568
|
+
"loading_messages"
|
|
569
|
+
]);
|
|
570
|
+
function coerce(key, value) {
|
|
571
|
+
if (JSON_FIELDS.has(key)) {
|
|
572
|
+
try {
|
|
573
|
+
return JSON.parse(value);
|
|
574
|
+
} catch {
|
|
575
|
+
return value;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
if (value === "true")
|
|
579
|
+
return true;
|
|
580
|
+
if (value === "false")
|
|
581
|
+
return false;
|
|
582
|
+
return value;
|
|
583
|
+
}
|
|
584
|
+
async function parseArgs(req) {
|
|
585
|
+
const url = new URL(req.url);
|
|
586
|
+
const args = {};
|
|
587
|
+
for (const [k, v] of url.searchParams)
|
|
588
|
+
args[k] = coerce(k, v);
|
|
589
|
+
if (req.method !== "POST")
|
|
590
|
+
return args;
|
|
591
|
+
const contentType = req.headers.get("content-type") ?? "";
|
|
592
|
+
if (contentType.includes("application/json")) {
|
|
593
|
+
const text2 = await req.text();
|
|
594
|
+
if (text2.trim())
|
|
595
|
+
Object.assign(args, JSON.parse(text2));
|
|
596
|
+
return args;
|
|
597
|
+
}
|
|
598
|
+
if (contentType.includes("multipart/form-data")) {
|
|
599
|
+
const form = await req.formData();
|
|
600
|
+
form.forEach((v, k) => {
|
|
601
|
+
args[k] = typeof v === "string" ? coerce(k, v) : v;
|
|
602
|
+
});
|
|
603
|
+
return args;
|
|
604
|
+
}
|
|
605
|
+
const text = await req.text();
|
|
606
|
+
if (!text)
|
|
607
|
+
return args;
|
|
608
|
+
for (const [k, v] of new URLSearchParams(text))
|
|
609
|
+
args[k] = coerce(k, v);
|
|
610
|
+
return args;
|
|
611
|
+
}
|
|
612
|
+
function bearerToken(req, args) {
|
|
613
|
+
const header = req.headers.get("authorization");
|
|
614
|
+
if (header?.toLowerCase().startsWith("bearer "))
|
|
615
|
+
return header.slice(7).trim();
|
|
616
|
+
if (typeof args.token === "string")
|
|
617
|
+
return args.token;
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
function str(args, key) {
|
|
621
|
+
const v = args[key];
|
|
622
|
+
return typeof v === "string" ? v : v == null ? undefined : String(v);
|
|
623
|
+
}
|
|
624
|
+
function num(args, key, fallback) {
|
|
625
|
+
const v = args[key];
|
|
626
|
+
const n = typeof v === "number" ? v : typeof v === "string" ? Number.parseInt(v, 10) : Number.NaN;
|
|
627
|
+
return Number.isFinite(n) ? n : fallback;
|
|
628
|
+
}
|
|
629
|
+
function bool(args, key) {
|
|
630
|
+
const v = args[key];
|
|
631
|
+
if (typeof v === "boolean")
|
|
632
|
+
return v;
|
|
633
|
+
if (v === "true" || v === "1" || v === 1)
|
|
634
|
+
return true;
|
|
635
|
+
if (v === "false" || v === "0" || v === 0)
|
|
636
|
+
return false;
|
|
637
|
+
return;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
// src/events.ts
|
|
641
|
+
var VERIFICATION_TOKEN = "mock-verification-token";
|
|
642
|
+
function eventCallback(store, event) {
|
|
643
|
+
return {
|
|
644
|
+
token: VERIFICATION_TOKEN,
|
|
645
|
+
team_id: store.team.id,
|
|
646
|
+
context_team_id: store.team.id,
|
|
647
|
+
context_enterprise_id: null,
|
|
648
|
+
api_app_id: store.app.id,
|
|
649
|
+
event,
|
|
650
|
+
type: "event_callback",
|
|
651
|
+
event_id: slackId("Ev", 9),
|
|
652
|
+
event_time: nowUnix(),
|
|
653
|
+
authorizations: [
|
|
654
|
+
{
|
|
655
|
+
enterprise_id: null,
|
|
656
|
+
team_id: store.team.id,
|
|
657
|
+
user_id: store.bot.userId,
|
|
658
|
+
is_bot: true,
|
|
659
|
+
is_enterprise_install: false
|
|
660
|
+
}
|
|
661
|
+
],
|
|
662
|
+
is_ext_shared_channel: false,
|
|
663
|
+
event_context: Buffer.from(`${store.team.id}:${store.app.id}:${event.channel ?? ""}`).toString("base64")
|
|
664
|
+
};
|
|
665
|
+
}
|
|
666
|
+
function messageEvent(store, m, channel) {
|
|
667
|
+
const {
|
|
668
|
+
channel: _c,
|
|
669
|
+
team,
|
|
670
|
+
...rest
|
|
671
|
+
} = wireMessage(m);
|
|
672
|
+
const event = {
|
|
673
|
+
...rest,
|
|
674
|
+
type: "message",
|
|
675
|
+
channel: m.channel,
|
|
676
|
+
event_ts: m.ts,
|
|
677
|
+
channel_type: store.channelType(channel),
|
|
678
|
+
team
|
|
679
|
+
};
|
|
680
|
+
if (m.files?.length && !m.subtype)
|
|
681
|
+
event.subtype = "file_share";
|
|
682
|
+
if (m.files?.length) {
|
|
683
|
+
event.upload = false;
|
|
684
|
+
event.display_as_bot = false;
|
|
685
|
+
}
|
|
686
|
+
return event;
|
|
687
|
+
}
|
|
688
|
+
function appMentionEvent(store, m) {
|
|
689
|
+
const { channel_type: _ct, ...event } = messageEvent(store, m, store.channel(m.channel));
|
|
690
|
+
return { ...event, type: "app_mention" };
|
|
691
|
+
}
|
|
692
|
+
function messageChangedEvent(store, m, previous) {
|
|
693
|
+
const channel = store.channel(m.channel);
|
|
694
|
+
const ts = nextTs();
|
|
695
|
+
return {
|
|
696
|
+
type: "message",
|
|
697
|
+
subtype: "message_changed",
|
|
698
|
+
channel: m.channel,
|
|
699
|
+
channel_type: store.channelType(channel),
|
|
700
|
+
hidden: true,
|
|
701
|
+
ts,
|
|
702
|
+
event_ts: ts,
|
|
703
|
+
message: {
|
|
704
|
+
...wireMessage(m),
|
|
705
|
+
channel: undefined,
|
|
706
|
+
source_team: store.team.id,
|
|
707
|
+
user_team: store.team.id
|
|
708
|
+
},
|
|
709
|
+
previous_message: { ...wireMessage(previous), channel: undefined }
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
function messageDeletedEvent(store, m) {
|
|
713
|
+
const channel = store.channel(m.channel);
|
|
714
|
+
const ts = nextTs();
|
|
715
|
+
return {
|
|
716
|
+
type: "message",
|
|
717
|
+
subtype: "message_deleted",
|
|
718
|
+
channel: m.channel,
|
|
719
|
+
channel_type: store.channelType(channel),
|
|
720
|
+
hidden: true,
|
|
721
|
+
deleted_ts: m.ts,
|
|
722
|
+
ts,
|
|
723
|
+
event_ts: ts,
|
|
724
|
+
previous_message: { ...wireMessage(m), channel: undefined }
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
function reactionEvent(kind, m, name, user) {
|
|
728
|
+
return {
|
|
729
|
+
type: kind,
|
|
730
|
+
user,
|
|
731
|
+
reaction: name,
|
|
732
|
+
item_user: m.user,
|
|
733
|
+
item: { type: "message", channel: m.channel, ts: m.ts },
|
|
734
|
+
event_ts: nextTs()
|
|
735
|
+
};
|
|
736
|
+
}
|
|
737
|
+
function memberJoinedEvent(store, channel, user, inviter) {
|
|
738
|
+
return {
|
|
739
|
+
type: "member_joined_channel",
|
|
740
|
+
user,
|
|
741
|
+
channel: channel.id,
|
|
742
|
+
channel_type: store.channelType(channel) === "channel" ? "C" : "G",
|
|
743
|
+
team: store.team.id,
|
|
744
|
+
inviter,
|
|
745
|
+
event_ts: nextTs()
|
|
746
|
+
};
|
|
747
|
+
}
|
|
748
|
+
function assistantThreadStartedEvent(store, dm, user, threadTs, context = {}) {
|
|
749
|
+
return {
|
|
750
|
+
type: "assistant_thread_started",
|
|
751
|
+
assistant_thread: {
|
|
752
|
+
user_id: user,
|
|
753
|
+
context: { team_id: store.team.id, enterprise_id: null, ...context },
|
|
754
|
+
channel_id: dm.id,
|
|
755
|
+
thread_ts: threadTs
|
|
756
|
+
},
|
|
757
|
+
event_ts: nextTs()
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
function assistantThreadContextChangedEvent(store, dm, user, threadTs, context) {
|
|
761
|
+
return {
|
|
762
|
+
type: "assistant_thread_context_changed",
|
|
763
|
+
assistant_thread: {
|
|
764
|
+
user_id: user,
|
|
765
|
+
context: { team_id: store.team.id, enterprise_id: null, ...context },
|
|
766
|
+
channel_id: dm.id,
|
|
767
|
+
thread_ts: threadTs
|
|
768
|
+
},
|
|
769
|
+
event_ts: nextTs()
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
function slashCommandPayload(store, input) {
|
|
773
|
+
return {
|
|
774
|
+
token: VERIFICATION_TOKEN,
|
|
775
|
+
team_id: store.team.id,
|
|
776
|
+
team_domain: store.team.domain,
|
|
777
|
+
channel_id: input.channel.id,
|
|
778
|
+
channel_name: input.channel.is_im ? "directmessage" : input.channel.name,
|
|
779
|
+
user_id: input.user.id,
|
|
780
|
+
user_name: input.user.name,
|
|
781
|
+
command: input.command,
|
|
782
|
+
text: input.text,
|
|
783
|
+
api_app_id: store.app.id,
|
|
784
|
+
is_enterprise_install: "false",
|
|
785
|
+
response_url: input.responseUrl,
|
|
786
|
+
trigger_id: input.triggerId
|
|
787
|
+
};
|
|
788
|
+
}
|
|
789
|
+
function blockActionsPayload(store, input) {
|
|
790
|
+
return {
|
|
791
|
+
type: "block_actions",
|
|
792
|
+
user: {
|
|
793
|
+
id: input.user.id,
|
|
794
|
+
username: input.user.name,
|
|
795
|
+
name: input.user.name,
|
|
796
|
+
team_id: store.team.id
|
|
797
|
+
},
|
|
798
|
+
api_app_id: store.app.id,
|
|
799
|
+
token: VERIFICATION_TOKEN,
|
|
800
|
+
container: {
|
|
801
|
+
type: "message",
|
|
802
|
+
message_ts: input.message.ts,
|
|
803
|
+
channel_id: input.channel.id,
|
|
804
|
+
is_ephemeral: !!input.message.ephemeral_user,
|
|
805
|
+
...input.message.thread_ts ? { thread_ts: input.message.thread_ts } : {}
|
|
806
|
+
},
|
|
807
|
+
trigger_id: input.triggerId,
|
|
808
|
+
team: { id: store.team.id, domain: store.team.domain },
|
|
809
|
+
enterprise: null,
|
|
810
|
+
is_enterprise_install: false,
|
|
811
|
+
channel: { id: input.channel.id, name: input.channel.name },
|
|
812
|
+
message: wireMessage(input.message),
|
|
813
|
+
state: { values: {} },
|
|
814
|
+
response_url: input.responseUrl,
|
|
815
|
+
actions: input.actions.map((a) => ({ action_ts: nextTs(), ...a }))
|
|
816
|
+
};
|
|
817
|
+
}
|
|
818
|
+
function viewSubmissionPayload(store, input) {
|
|
819
|
+
const { opened_by: _o, trigger_id: _t, ...view } = input.view;
|
|
820
|
+
return {
|
|
821
|
+
type: "view_submission",
|
|
822
|
+
team: { id: store.team.id, domain: store.team.domain },
|
|
823
|
+
user: {
|
|
824
|
+
id: input.user.id,
|
|
825
|
+
username: input.user.name,
|
|
826
|
+
name: input.user.name,
|
|
827
|
+
team_id: store.team.id
|
|
828
|
+
},
|
|
829
|
+
api_app_id: store.app.id,
|
|
830
|
+
token: VERIFICATION_TOKEN,
|
|
831
|
+
trigger_id: input.triggerId,
|
|
832
|
+
view: { ...view, state: { values: input.values } },
|
|
833
|
+
response_urls: [],
|
|
834
|
+
is_enterprise_install: false,
|
|
835
|
+
enterprise: null
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
// src/render/mrkdwn.ts
|
|
840
|
+
function escapeHtml(s) {
|
|
841
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
842
|
+
}
|
|
843
|
+
function unescapeSlack(s) {
|
|
844
|
+
return s.replace(/&(amp|lt|gt|quot);/g, (_m, name) => name === "amp" ? "&" : name === "lt" ? "<" : name === "gt" ? ">" : '"');
|
|
845
|
+
}
|
|
846
|
+
function reEscape(s) {
|
|
847
|
+
return escapeHtml(unescapeSlack(s));
|
|
848
|
+
}
|
|
849
|
+
var EMOJI = {
|
|
850
|
+
eyes: "\uD83D\uDC40",
|
|
851
|
+
white_check_mark: "\u2705",
|
|
852
|
+
x: "\u274C",
|
|
853
|
+
heavy_plus_sign: "\u2795",
|
|
854
|
+
heavy_minus_sign: "\u2796",
|
|
855
|
+
heavy_multiplication_x: "\u2716\uFE0F",
|
|
856
|
+
zap: "\u26A1",
|
|
857
|
+
speech_balloon: "\uD83D\uDCAC",
|
|
858
|
+
robot_face: "\uD83E\uDD16",
|
|
859
|
+
gear: "\u2699\uFE0F",
|
|
860
|
+
rocket: "\uD83D\uDE80",
|
|
861
|
+
star: "\u2B50",
|
|
862
|
+
crystal_ball: "\uD83D\uDD2E",
|
|
863
|
+
bulb: "\uD83D\uDCA1",
|
|
864
|
+
wrench: "\uD83D\uDD27",
|
|
865
|
+
hammer: "\uD83D\uDD28",
|
|
866
|
+
crown: "\uD83D\uDC51",
|
|
867
|
+
tada: "\uD83C\uDF89",
|
|
868
|
+
warning: "\u26A0\uFE0F",
|
|
869
|
+
hourglass: "\u231B",
|
|
870
|
+
hourglass_flowing_sand: "\u23F3",
|
|
871
|
+
thumbsup: "\uD83D\uDC4D",
|
|
872
|
+
thumbsdown: "\uD83D\uDC4E",
|
|
873
|
+
"+1": "\uD83D\uDC4D",
|
|
874
|
+
"-1": "\uD83D\uDC4E",
|
|
875
|
+
heavy_check_mark: "\u2714\uFE0F",
|
|
876
|
+
question: "\u2753",
|
|
877
|
+
grey_question: "\u2754",
|
|
878
|
+
exclamation: "\u2757",
|
|
879
|
+
white_circle: "\u26AA",
|
|
880
|
+
large_blue_circle: "\uD83D\uDD35",
|
|
881
|
+
black_circle: "\u26AB",
|
|
882
|
+
red_circle: "\uD83D\uDD34",
|
|
883
|
+
large_green_circle: "\uD83D\uDFE2",
|
|
884
|
+
large_yellow_circle: "\uD83D\uDFE1",
|
|
885
|
+
fire: "\uD83D\uDD25",
|
|
886
|
+
sparkles: "\u2728",
|
|
887
|
+
memo: "\uD83D\uDCDD",
|
|
888
|
+
clipboard: "\uD83D\uDCCB",
|
|
889
|
+
mag: "\uD83D\uDD0D",
|
|
890
|
+
mag_right: "\uD83D\uDD0E",
|
|
891
|
+
link: "\uD83D\uDD17",
|
|
892
|
+
lock: "\uD83D\uDD12",
|
|
893
|
+
unlock: "\uD83D\uDD13",
|
|
894
|
+
bell: "\uD83D\uDD14",
|
|
895
|
+
package: "\uD83D\uDCE6",
|
|
896
|
+
construction: "\uD83D\uDEA7",
|
|
897
|
+
bug: "\uD83D\uDC1B",
|
|
898
|
+
boom: "\uD83D\uDCA5",
|
|
899
|
+
pencil2: "\u270F\uFE0F",
|
|
900
|
+
scroll: "\uD83D\uDCDC",
|
|
901
|
+
page_facing_up: "\uD83D\uDCC4",
|
|
902
|
+
file_folder: "\uD83D\uDCC1",
|
|
903
|
+
card_index_dividers: "\uD83D\uDDC2\uFE0F",
|
|
904
|
+
paperclip: "\uD83D\uDCCE",
|
|
905
|
+
bar_chart: "\uD83D\uDCCA",
|
|
906
|
+
chart_with_upwards_trend: "\uD83D\uDCC8",
|
|
907
|
+
calendar: "\uD83D\uDCC5",
|
|
908
|
+
clock1: "\uD83D\uDD50",
|
|
909
|
+
arrow_right: "\u27A1\uFE0F",
|
|
910
|
+
arrow_left: "\u2B05\uFE0F",
|
|
911
|
+
arrow_up: "\u2B06\uFE0F",
|
|
912
|
+
arrow_down: "\u2B07\uFE0F",
|
|
913
|
+
arrow_right_hook: "\u21AA\uFE0F",
|
|
914
|
+
repeat: "\uD83D\uDD01",
|
|
915
|
+
arrows_counterclockwise: "\uD83D\uDD04",
|
|
916
|
+
recycle: "\u267B\uFE0F",
|
|
917
|
+
no_entry: "\u26D4",
|
|
918
|
+
no_entry_sign: "\uD83D\uDEAB",
|
|
919
|
+
stop_sign: "\uD83D\uDED1",
|
|
920
|
+
pause_button: "\u23F8\uFE0F",
|
|
921
|
+
information_source: "\u2139\uFE0F",
|
|
922
|
+
wave: "\uD83D\uDC4B",
|
|
923
|
+
pray: "\uD83D\uDE4F",
|
|
924
|
+
muscle: "\uD83D\uDCAA",
|
|
925
|
+
brain: "\uD83E\uDDE0",
|
|
926
|
+
dart: "\uD83C\uDFAF",
|
|
927
|
+
trophy: "\uD83C\uDFC6",
|
|
928
|
+
medal: "\uD83C\uDFC5",
|
|
929
|
+
checkered_flag: "\uD83C\uDFC1",
|
|
930
|
+
ok_hand: "\uD83D\uDC4C",
|
|
931
|
+
point_right: "\uD83D\uDC49",
|
|
932
|
+
clap: "\uD83D\uDC4F",
|
|
933
|
+
raised_hands: "\uD83D\uDE4C",
|
|
934
|
+
thinking_face: "\uD83E\uDD14",
|
|
935
|
+
"100": "\uD83D\uDCAF",
|
|
936
|
+
green_heart: "\uD83D\uDC9A",
|
|
937
|
+
thread: "\uD83E\uDDF5",
|
|
938
|
+
satellite_antenna: "\uD83D\uDCE1",
|
|
939
|
+
inbox_tray: "\uD83D\uDCE5",
|
|
940
|
+
outbox_tray: "\uD83D\uDCE4",
|
|
941
|
+
incoming_envelope: "\uD83D\uDCE8",
|
|
942
|
+
mailbox_with_no_mail: "\uD83D\uDCED",
|
|
943
|
+
envelope: "\u2709\uFE0F",
|
|
944
|
+
test_tube: "\uD83E\uDDEA",
|
|
945
|
+
ship: "\uD83D\uDEA2",
|
|
946
|
+
sos: "\uD83C\uDD98",
|
|
947
|
+
small_blue_diamond: "\uD83D\uDD39",
|
|
948
|
+
small_orange_diamond: "\uD83D\uDD38",
|
|
949
|
+
black_small_square: "\u25AA\uFE0F",
|
|
950
|
+
white_small_square: "\u25AB\uFE0F"
|
|
951
|
+
};
|
|
952
|
+
function emojiChar(name) {
|
|
953
|
+
return EMOJI[name.replace(/^:|:$/g, "").replace(/::skin-tone-\d$/, "")];
|
|
954
|
+
}
|
|
955
|
+
function emojiFromUnicode(code) {
|
|
956
|
+
const points = code.split("-").map((p) => Number.parseInt(p, 16));
|
|
957
|
+
if (points.some((p) => !Number.isFinite(p)))
|
|
958
|
+
return;
|
|
959
|
+
try {
|
|
960
|
+
return String.fromCodePoint(...points);
|
|
961
|
+
} catch {
|
|
962
|
+
return;
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
function renderEmoji(html) {
|
|
966
|
+
return html.replace(/:([a-z][a-z0-9_+'-]*|\+1|-1|100):/g, (m, name) => {
|
|
967
|
+
const char = emojiChar(name);
|
|
968
|
+
return char ?? `<span class="sm-emoji-name">${m}</span>`;
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
function displayName(user) {
|
|
972
|
+
return user.profile.display_name || user.real_name || user.name;
|
|
973
|
+
}
|
|
974
|
+
function pill(text) {
|
|
975
|
+
return `<span class="sm-pill">${escapeHtml(text)}</span>`;
|
|
976
|
+
}
|
|
977
|
+
function isSafeUrl(url) {
|
|
978
|
+
return /^(https?:\/\/|mailto:|tel:)/i.test(url);
|
|
979
|
+
}
|
|
980
|
+
function renderControl(inner, ctx) {
|
|
981
|
+
const bar = inner.indexOf("|");
|
|
982
|
+
const head = bar >= 0 ? inner.slice(0, bar) : inner;
|
|
983
|
+
const label = bar >= 0 ? inner.slice(bar + 1) : "";
|
|
984
|
+
if (head.startsWith("@")) {
|
|
985
|
+
const id = head.slice(1);
|
|
986
|
+
const user = ctx.users.get(id);
|
|
987
|
+
return pill(`@${user ? displayName(user) : label || id}`);
|
|
988
|
+
}
|
|
989
|
+
if (head.startsWith("#")) {
|
|
990
|
+
const id = head.slice(1);
|
|
991
|
+
const channel = ctx.channels.get(id);
|
|
992
|
+
return pill(`#${channel ? channel.name : label.replace(/^#/, "") || id}`);
|
|
993
|
+
}
|
|
994
|
+
if (head.startsWith("!")) {
|
|
995
|
+
const cmd = head.slice(1);
|
|
996
|
+
if (cmd === "here" || cmd === "channel" || cmd === "everyone")
|
|
997
|
+
return pill(`@${cmd}`);
|
|
998
|
+
if (cmd.startsWith("subteam^")) {
|
|
999
|
+
const handle = label || cmd.slice("subteam^".length);
|
|
1000
|
+
return pill(handle.startsWith("@") ? handle : `@${handle}`);
|
|
1001
|
+
}
|
|
1002
|
+
if (cmd.startsWith("date^")) {
|
|
1003
|
+
if (label)
|
|
1004
|
+
return renderEmoji(reEscape(label));
|
|
1005
|
+
const secs = Number(cmd.split("^")[1]);
|
|
1006
|
+
return Number.isFinite(secs) ? escapeHtml(new Date(secs * 1000).toISOString()) : "";
|
|
1007
|
+
}
|
|
1008
|
+
return pill(`@${cmd}`);
|
|
1009
|
+
}
|
|
1010
|
+
if (isSafeUrl(head)) {
|
|
1011
|
+
const shown = label || head.replace(/^mailto:/i, "");
|
|
1012
|
+
const attrs = /^mailto:/i.test(head) ? "" : ' target="_blank" rel="noopener"';
|
|
1013
|
+
return `<a class="sm-link" href="${escapeHtml(head)}"${attrs}>${renderEmoji(reEscape(shown))}</a>`;
|
|
1014
|
+
}
|
|
1015
|
+
return escapeHtml(`<${unescapeSlack(inner)}>`);
|
|
1016
|
+
}
|
|
1017
|
+
function preHtml(body) {
|
|
1018
|
+
let code = body.replace(/^\n/, "").replace(/\n$/, "");
|
|
1019
|
+
if (code.includes(`
|
|
1020
|
+
`))
|
|
1021
|
+
code = code.replace(/^[a-z][a-z0-9+#-]{0,11}\n/, "");
|
|
1022
|
+
return `<pre class="sm-pre">${reEscape(code)}</pre>`;
|
|
1023
|
+
}
|
|
1024
|
+
var BOUND_L = `(^|[\\s(\\[{'"\\uE000\\uE001])`;
|
|
1025
|
+
var BOUND_R = `(?=$|[\\s.,;:!?)\\]}'"\\uE000\\uE001])`;
|
|
1026
|
+
function styleRule(marker) {
|
|
1027
|
+
const m = marker.replace(/[*]/g, "\\*");
|
|
1028
|
+
return new RegExp(`${BOUND_L}${m}(?![\\s${m}])([^${m}\\n]*[^\\s${m}])${m}${BOUND_R}`, "g");
|
|
1029
|
+
}
|
|
1030
|
+
var RULES = [
|
|
1031
|
+
[styleRule("*"), "strong"],
|
|
1032
|
+
[styleRule("~"), "s"],
|
|
1033
|
+
[styleRule("_"), "em"]
|
|
1034
|
+
];
|
|
1035
|
+
function inlineStyles(s) {
|
|
1036
|
+
let out = s;
|
|
1037
|
+
for (const [re, tag] of RULES)
|
|
1038
|
+
out = out.replace(re, `$1<${tag}>$2</${tag}>`);
|
|
1039
|
+
return out;
|
|
1040
|
+
}
|
|
1041
|
+
var QUOTE = /^\s*(?:>|>)\s?/;
|
|
1042
|
+
var BULLET = /^(\s*)(?:\u2022|-|\*)\s+(.*)$/;
|
|
1043
|
+
var NUMBER = /^(\s*)\d+[.)]\s+(.*)$/;
|
|
1044
|
+
function blockify(text) {
|
|
1045
|
+
const groups = [];
|
|
1046
|
+
const push = (kind, html, indent = 0) => {
|
|
1047
|
+
const last = groups[groups.length - 1];
|
|
1048
|
+
if (last?.kind === kind)
|
|
1049
|
+
last.items.push({ html, indent });
|
|
1050
|
+
else
|
|
1051
|
+
groups.push({ kind, items: [{ html, indent }] });
|
|
1052
|
+
};
|
|
1053
|
+
for (const line of text.split(`
|
|
1054
|
+
`)) {
|
|
1055
|
+
const bullet = BULLET.exec(line);
|
|
1056
|
+
const numbered = bullet ? null : NUMBER.exec(line);
|
|
1057
|
+
if (QUOTE.test(line))
|
|
1058
|
+
push("quote", line.replace(QUOTE, ""));
|
|
1059
|
+
else if (bullet)
|
|
1060
|
+
push("ul", bullet[2] ?? "", Math.min(4, Math.floor((bullet[1]?.length ?? 0) / 2)));
|
|
1061
|
+
else if (numbered)
|
|
1062
|
+
push("ol", numbered[2] ?? "", Math.min(4, Math.floor((numbered[1]?.length ?? 0) / 2)));
|
|
1063
|
+
else
|
|
1064
|
+
push("p", line);
|
|
1065
|
+
}
|
|
1066
|
+
return groups.map((g) => {
|
|
1067
|
+
if (g.kind === "p")
|
|
1068
|
+
return g.items.map((i) => i.html).join("<br>");
|
|
1069
|
+
const inner = g.items.map((i) => `<li${i.indent ? ` style="margin-left:${i.indent * 18}px"` : ""}>${i.html}</li>`).join("");
|
|
1070
|
+
if (g.kind === "quote")
|
|
1071
|
+
return `<blockquote class="sm-quote">${g.items.map((i) => i.html).join("<br>")}</blockquote>`;
|
|
1072
|
+
return `<${g.kind} class="sm-list">${inner}</${g.kind}>`;
|
|
1073
|
+
}).join("");
|
|
1074
|
+
}
|
|
1075
|
+
var BLOCK_TAGS = "pre|blockquote|ul|ol";
|
|
1076
|
+
function tidy(html) {
|
|
1077
|
+
return html.replace(new RegExp(`<br>\\s*(<(?:${BLOCK_TAGS})\\b)`, "g"), "$1").replace(new RegExp(`(</(?:${BLOCK_TAGS})>)\\s*<br>`, "g"), "$1");
|
|
1078
|
+
}
|
|
1079
|
+
function mrkdwnToHtml(text, ctx) {
|
|
1080
|
+
if (!text)
|
|
1081
|
+
return "";
|
|
1082
|
+
const tokens = [];
|
|
1083
|
+
const hold = (html) => {
|
|
1084
|
+
tokens.push(html);
|
|
1085
|
+
return `\uE000${tokens.length - 1}\uE001`;
|
|
1086
|
+
};
|
|
1087
|
+
let s = text.replace(/\r\n/g, `
|
|
1088
|
+
`);
|
|
1089
|
+
s = s.replace(/```([\s\S]*?)```/g, (_m, body) => hold(preHtml(body)));
|
|
1090
|
+
s = s.replace(/`([^`\n]+)`/g, (_m, body) => hold(`<code class="sm-code">${reEscape(body)}</code>`));
|
|
1091
|
+
s = s.replace(/<([^<>\n]*)>/g, (_m, inner) => hold(renderControl(inner, ctx)));
|
|
1092
|
+
s = renderEmoji(reEscape(s));
|
|
1093
|
+
s = inlineStyles(s);
|
|
1094
|
+
s = blockify(s);
|
|
1095
|
+
const expand = (html) => html.replace(/\uE000(\d+)\uE001/g, (_m, i) => expand(tokens[Number(i)] ?? ""));
|
|
1096
|
+
return tidy(expand(s));
|
|
1097
|
+
}
|
|
1098
|
+
function plainTextToHtml(text) {
|
|
1099
|
+
if (!text)
|
|
1100
|
+
return "";
|
|
1101
|
+
return renderEmoji(reEscape(text.replace(/\r\n/g, `
|
|
1102
|
+
`))).replace(/\n/g, "<br>");
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
// src/render/blocks.ts
|
|
1106
|
+
function rec(v) {
|
|
1107
|
+
return typeof v === "object" && v !== null && !Array.isArray(v) ? v : undefined;
|
|
1108
|
+
}
|
|
1109
|
+
function str2(v) {
|
|
1110
|
+
return typeof v === "string" ? v : "";
|
|
1111
|
+
}
|
|
1112
|
+
function arr(v) {
|
|
1113
|
+
return Array.isArray(v) ? v : [];
|
|
1114
|
+
}
|
|
1115
|
+
function safeUrl(url) {
|
|
1116
|
+
return /^(https?:\/\/|\/)/i.test(url) ? escapeHtml(url) : undefined;
|
|
1117
|
+
}
|
|
1118
|
+
function unsupported(what) {
|
|
1119
|
+
return `<div class="sm-unsupported">unsupported: ${escapeHtml(what || "unknown")}</div>`;
|
|
1120
|
+
}
|
|
1121
|
+
function textObject(v, ctx) {
|
|
1122
|
+
if (typeof v === "string")
|
|
1123
|
+
return plainTextToHtml(v);
|
|
1124
|
+
const o = rec(v);
|
|
1125
|
+
if (!o)
|
|
1126
|
+
return "";
|
|
1127
|
+
const text = str2(o.text);
|
|
1128
|
+
return o.type === "mrkdwn" ? mrkdwnToHtml(text, ctx) : plainTextToHtml(text);
|
|
1129
|
+
}
|
|
1130
|
+
function plainOf(v) {
|
|
1131
|
+
const o = rec(v);
|
|
1132
|
+
return plainTextToHtml(o ? str2(o.text) : str2(v));
|
|
1133
|
+
}
|
|
1134
|
+
function image(url, alt, cls) {
|
|
1135
|
+
const src = safeUrl(url);
|
|
1136
|
+
if (!src)
|
|
1137
|
+
return unsupported("image url");
|
|
1138
|
+
return `<img class="${cls}" src="${src}" alt="${escapeHtml(alt)}">`;
|
|
1139
|
+
}
|
|
1140
|
+
function imageSrcOf(block) {
|
|
1141
|
+
const direct = str2(block.image_url);
|
|
1142
|
+
if (direct)
|
|
1143
|
+
return direct;
|
|
1144
|
+
const file = rec(block.slack_file);
|
|
1145
|
+
return file ? str2(file.url) || str2(file.url_private) : "";
|
|
1146
|
+
}
|
|
1147
|
+
function button(el, ctx) {
|
|
1148
|
+
const style = str2(el.style);
|
|
1149
|
+
const cls = `sm-btn${style === "primary" ? " sm-btn-primary" : style === "danger" ? " sm-btn-danger" : ""}`;
|
|
1150
|
+
const label = textObject(el.text, ctx) || "Button";
|
|
1151
|
+
const url = safeUrl(str2(el.url));
|
|
1152
|
+
const confirm = rec(el.confirm) ? '<span class="sm-btn-confirm" title="confirmation dialog">\u26A0</span>' : "";
|
|
1153
|
+
return url ? `<a class="${cls}" href="${url}" target="_blank" rel="noopener">${label}${confirm}</a>` : `<span class="${cls}">${label}${confirm}</span>`;
|
|
1154
|
+
}
|
|
1155
|
+
function selectPill(el, ctx, glyph = "\u25BE") {
|
|
1156
|
+
const initial = rec(el.initial_option);
|
|
1157
|
+
const label = initial && textObject(initial.text, ctx) || textObject(el.placeholder, ctx) || plainTextToHtml(str2(el.type).replace(/_/g, " "));
|
|
1158
|
+
return `<span class="sm-select">${label}<span class="sm-select-caret">${glyph}</span></span>`;
|
|
1159
|
+
}
|
|
1160
|
+
function inputBox(el, ctx) {
|
|
1161
|
+
const multiline = el.multiline === true;
|
|
1162
|
+
const value = str2(el.initial_value);
|
|
1163
|
+
const inner = value ? plainTextToHtml(value) : `<span class="sm-input-ph">${textObject(el.placeholder, ctx)}</span>`;
|
|
1164
|
+
return `<div class="sm-input${multiline ? " sm-input-multi" : ""}">${inner}</div>`;
|
|
1165
|
+
}
|
|
1166
|
+
function renderElement(v, ctx) {
|
|
1167
|
+
const el = rec(v);
|
|
1168
|
+
if (!el)
|
|
1169
|
+
return "";
|
|
1170
|
+
const type = str2(el.type);
|
|
1171
|
+
switch (type) {
|
|
1172
|
+
case "button":
|
|
1173
|
+
return button(el, ctx);
|
|
1174
|
+
case "image":
|
|
1175
|
+
return image(imageSrcOf(el), str2(el.alt_text), "sm-acc-img");
|
|
1176
|
+
case "overflow":
|
|
1177
|
+
return `<span class="sm-select sm-overflow">\u22EF</span>`;
|
|
1178
|
+
case "datepicker":
|
|
1179
|
+
return selectPill({ ...el, placeholder: el.placeholder ?? "Select a date" }, ctx, "\uD83D\uDCC5");
|
|
1180
|
+
case "timepicker":
|
|
1181
|
+
return selectPill({ ...el, placeholder: el.placeholder ?? "Select a time" }, ctx, "\uD83D\uDD50");
|
|
1182
|
+
case "plain_text_input":
|
|
1183
|
+
return inputBox(el, ctx);
|
|
1184
|
+
case "checkboxes":
|
|
1185
|
+
case "radio_buttons":
|
|
1186
|
+
return `<div class="sm-options">${arr(el.options).map((o) => {
|
|
1187
|
+
const opt = rec(o);
|
|
1188
|
+
const mark = type === "checkboxes" ? "\u2610" : "\u25EF";
|
|
1189
|
+
return `<div class="sm-option">${mark} ${opt ? textObject(opt.text, ctx) : ""}</div>`;
|
|
1190
|
+
}).join("")}</div>`;
|
|
1191
|
+
default:
|
|
1192
|
+
if (type.endsWith("_select") || type.startsWith("multi_"))
|
|
1193
|
+
return selectPill(el, ctx);
|
|
1194
|
+
return unsupported(type);
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
function richStyle(html, style) {
|
|
1198
|
+
if (!html || !style)
|
|
1199
|
+
return html;
|
|
1200
|
+
let out = html;
|
|
1201
|
+
if (style.code === true)
|
|
1202
|
+
out = `<code class="sm-code">${out}</code>`;
|
|
1203
|
+
if (style.bold === true)
|
|
1204
|
+
out = `<strong>${out}</strong>`;
|
|
1205
|
+
if (style.italic === true)
|
|
1206
|
+
out = `<em>${out}</em>`;
|
|
1207
|
+
if (style.strike === true)
|
|
1208
|
+
out = `<s>${out}</s>`;
|
|
1209
|
+
return out;
|
|
1210
|
+
}
|
|
1211
|
+
function richElement(v, ctx) {
|
|
1212
|
+
const el = rec(v);
|
|
1213
|
+
if (!el)
|
|
1214
|
+
return "";
|
|
1215
|
+
const style = rec(el.style);
|
|
1216
|
+
switch (str2(el.type)) {
|
|
1217
|
+
case "text":
|
|
1218
|
+
return richStyle(plainTextToHtml(str2(el.text)).replace(/\n/g, "<br>"), style);
|
|
1219
|
+
case "link": {
|
|
1220
|
+
const url = safeUrl(str2(el.url));
|
|
1221
|
+
const label = plainTextToHtml(str2(el.text) || str2(el.url));
|
|
1222
|
+
if (!url)
|
|
1223
|
+
return label;
|
|
1224
|
+
return richStyle(`<a class="sm-link" href="${url}" target="_blank" rel="noopener">${label}</a>`, style);
|
|
1225
|
+
}
|
|
1226
|
+
case "user": {
|
|
1227
|
+
const user = ctx.users.get(str2(el.user_id));
|
|
1228
|
+
return `<span class="sm-pill">@${escapeHtml(user ? displayName(user) : str2(el.user_id))}</span>`;
|
|
1229
|
+
}
|
|
1230
|
+
case "usergroup":
|
|
1231
|
+
return `<span class="sm-pill">@${escapeHtml(str2(el.usergroup_id))}</span>`;
|
|
1232
|
+
case "channel": {
|
|
1233
|
+
const channel = ctx.channels.get(str2(el.channel_id));
|
|
1234
|
+
return `<span class="sm-pill">#${escapeHtml(channel ? channel.name : str2(el.channel_id))}</span>`;
|
|
1235
|
+
}
|
|
1236
|
+
case "broadcast":
|
|
1237
|
+
return `<span class="sm-pill">@${escapeHtml(str2(el.range) || "channel")}</span>`;
|
|
1238
|
+
case "emoji": {
|
|
1239
|
+
const char = emojiChar(str2(el.name)) ?? (el.unicode ? emojiFromUnicode(str2(el.unicode)) : undefined);
|
|
1240
|
+
return char ?? `<span class="sm-emoji-name">:${escapeHtml(str2(el.name))}:</span>`;
|
|
1241
|
+
}
|
|
1242
|
+
case "date":
|
|
1243
|
+
return plainTextToHtml(str2(el.fallback) || str2(el.timestamp));
|
|
1244
|
+
case "color":
|
|
1245
|
+
return plainTextToHtml(str2(el.value));
|
|
1246
|
+
default:
|
|
1247
|
+
return "";
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
function richSection(v, ctx) {
|
|
1251
|
+
const block = rec(v);
|
|
1252
|
+
if (!block)
|
|
1253
|
+
return "";
|
|
1254
|
+
const inner = arr(block.elements).map((e) => richElement(e, ctx)).join("");
|
|
1255
|
+
switch (str2(block.type)) {
|
|
1256
|
+
case "rich_text_section":
|
|
1257
|
+
return `<div class="sm-rt-section">${inner}</div>`;
|
|
1258
|
+
case "rich_text_quote":
|
|
1259
|
+
return `<blockquote class="sm-quote">${inner}</blockquote>`;
|
|
1260
|
+
case "rich_text_preformatted":
|
|
1261
|
+
return `<pre class="sm-pre">${inner}</pre>`;
|
|
1262
|
+
case "rich_text_list": {
|
|
1263
|
+
const tag = str2(block.style) === "ordered" ? "ol" : "ul";
|
|
1264
|
+
const indent = Number(block.indent) || 0;
|
|
1265
|
+
const items = arr(block.elements).map((item) => `<li>${richSection(item, ctx)}</li>`).join("");
|
|
1266
|
+
const margin = indent ? ` style="margin-left:${indent * 18}px"` : "";
|
|
1267
|
+
return `<${tag} class="sm-list"${margin}>${items}</${tag}>`;
|
|
1268
|
+
}
|
|
1269
|
+
default:
|
|
1270
|
+
return inner;
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
function sectionBlock(block, ctx) {
|
|
1274
|
+
const parts = [];
|
|
1275
|
+
if (block.text)
|
|
1276
|
+
parts.push(`<div class="sm-section-text">${textObject(block.text, ctx)}</div>`);
|
|
1277
|
+
const fields = arr(block.fields);
|
|
1278
|
+
if (fields.length) {
|
|
1279
|
+
parts.push(`<div class="sm-fields">${fields.map((f) => `<div class="sm-field">${textObject(f, ctx)}</div>`).join("")}</div>`);
|
|
1280
|
+
}
|
|
1281
|
+
const accessory = block.accessory ? renderElement(block.accessory, ctx) : "";
|
|
1282
|
+
const body = parts.join("");
|
|
1283
|
+
if (!accessory)
|
|
1284
|
+
return `<div class="sm-block sm-section">${body}</div>`;
|
|
1285
|
+
return `<div class="sm-block sm-section sm-section-split"><div class="sm-section-main">${body}</div><div class="sm-section-acc">${accessory}</div></div>`;
|
|
1286
|
+
}
|
|
1287
|
+
function contextBlock(block, ctx) {
|
|
1288
|
+
const inner = arr(block.elements).map((e) => {
|
|
1289
|
+
const el = rec(e);
|
|
1290
|
+
if (!el)
|
|
1291
|
+
return "";
|
|
1292
|
+
if (str2(el.type) === "image")
|
|
1293
|
+
return image(imageSrcOf(el), str2(el.alt_text), "sm-context-img");
|
|
1294
|
+
return `<span class="sm-context-text">${textObject(el, ctx)}</span>`;
|
|
1295
|
+
}).join("");
|
|
1296
|
+
return `<div class="sm-block sm-context">${inner}</div>`;
|
|
1297
|
+
}
|
|
1298
|
+
function imageBlock(block, ctx) {
|
|
1299
|
+
const title = block.title ? `<div class="sm-img-title">${textObject(block.title, ctx)}</div>` : "";
|
|
1300
|
+
const src = imageSrcOf(block);
|
|
1301
|
+
const alt = str2(block.alt_text);
|
|
1302
|
+
if (!src) {
|
|
1303
|
+
const file = rec(block.slack_file);
|
|
1304
|
+
return `<div class="sm-block">${title}${unsupported(`image (file ${str2(file?.id) || "?"})`)}</div>`;
|
|
1305
|
+
}
|
|
1306
|
+
return `<div class="sm-block sm-image">${title}${image(src, alt, "sm-img")}</div>`;
|
|
1307
|
+
}
|
|
1308
|
+
function inputBlock(block, ctx) {
|
|
1309
|
+
const label = block.label ? `<div class="sm-label">${plainOf(block.label)}</div>` : "";
|
|
1310
|
+
const element = block.element ? renderElement(block.element, ctx) : "";
|
|
1311
|
+
const hint = block.hint ? `<div class="sm-hint">${plainOf(block.hint)}</div>` : "";
|
|
1312
|
+
return `<div class="sm-block sm-input-block">${label}${element}${hint}</div>`;
|
|
1313
|
+
}
|
|
1314
|
+
function videoBlock(block, ctx) {
|
|
1315
|
+
const thumb = safeUrl(str2(block.thumbnail_url));
|
|
1316
|
+
const url = safeUrl(str2(block.title_url) || str2(block.video_url));
|
|
1317
|
+
const title = textObject(block.title, ctx) || plainTextToHtml(str2(block.alt_text));
|
|
1318
|
+
const inner = `${thumb ? `<img class="sm-video-thumb" src="${thumb}" alt="${escapeHtml(str2(block.alt_text))}">` : ""}<div class="sm-video-title">\u25B6 ${title}</div>`;
|
|
1319
|
+
return `<div class="sm-block sm-video">${url ? `<a class="sm-video-link" href="${url}" target="_blank" rel="noopener">${inner}</a>` : inner}</div>`;
|
|
1320
|
+
}
|
|
1321
|
+
function renderBlock(v, ctx) {
|
|
1322
|
+
const block = rec(v);
|
|
1323
|
+
if (!block)
|
|
1324
|
+
return unsupported("block");
|
|
1325
|
+
switch (str2(block.type)) {
|
|
1326
|
+
case "header":
|
|
1327
|
+
return `<div class="sm-block sm-header-block">${textObject(block.text, ctx)}</div>`;
|
|
1328
|
+
case "section":
|
|
1329
|
+
return sectionBlock(block, ctx);
|
|
1330
|
+
case "divider":
|
|
1331
|
+
return `<div class="sm-block"><hr class="sm-hr"></div>`;
|
|
1332
|
+
case "context":
|
|
1333
|
+
return contextBlock(block, ctx);
|
|
1334
|
+
case "actions":
|
|
1335
|
+
return `<div class="sm-block sm-actions">${arr(block.elements).map((e) => renderElement(e, ctx)).join("")}</div>`;
|
|
1336
|
+
case "image":
|
|
1337
|
+
return imageBlock(block, ctx);
|
|
1338
|
+
case "rich_text":
|
|
1339
|
+
return `<div class="sm-block sm-rich-text">${arr(block.elements).map((e) => richSection(e, ctx)).join("")}</div>`;
|
|
1340
|
+
case "input":
|
|
1341
|
+
return inputBlock(block, ctx);
|
|
1342
|
+
case "file":
|
|
1343
|
+
return `<div class="sm-block sm-file-block">\uD83D\uDCCE ${escapeHtml(str2(block.external_id) || str2(block.file_id) || "file")}</div>`;
|
|
1344
|
+
case "video":
|
|
1345
|
+
return videoBlock(block, ctx);
|
|
1346
|
+
default:
|
|
1347
|
+
return `<div class="sm-block">${unsupported(str2(block.type))}</div>`;
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
function renderBlocks(blocks, ctx) {
|
|
1351
|
+
const list = arr(blocks);
|
|
1352
|
+
if (!list.length)
|
|
1353
|
+
return "";
|
|
1354
|
+
return `<div class="sm-blocks">${list.map((b) => renderBlock(b, ctx)).join("")}</div>`;
|
|
1355
|
+
}
|
|
1356
|
+
var NAMED_COLORS = {
|
|
1357
|
+
good: "#2eb67d",
|
|
1358
|
+
warning: "#ecb22e",
|
|
1359
|
+
danger: "#e01e5a"
|
|
1360
|
+
};
|
|
1361
|
+
function barColor(v) {
|
|
1362
|
+
const raw = str2(v).trim();
|
|
1363
|
+
if (!raw)
|
|
1364
|
+
return "#dddddd";
|
|
1365
|
+
const named = NAMED_COLORS[raw.toLowerCase()];
|
|
1366
|
+
if (named)
|
|
1367
|
+
return named;
|
|
1368
|
+
const hex = raw.startsWith("#") ? raw : `#${raw}`;
|
|
1369
|
+
return /^#[0-9a-fA-F]{3,8}$/.test(hex) ? hex : "#dddddd";
|
|
1370
|
+
}
|
|
1371
|
+
function attachmentFields(fields, ctx) {
|
|
1372
|
+
if (!fields.length)
|
|
1373
|
+
return "";
|
|
1374
|
+
return `<div class="sm-fields">${fields.map((f) => {
|
|
1375
|
+
const field = rec(f);
|
|
1376
|
+
if (!field)
|
|
1377
|
+
return "";
|
|
1378
|
+
const wide = field.short === true ? "" : " sm-field-wide";
|
|
1379
|
+
return `<div class="sm-field${wide}"><div class="sm-field-title">${plainTextToHtml(str2(field.title))}</div><div>${mrkdwnToHtml(str2(field.value), ctx)}</div></div>`;
|
|
1380
|
+
}).join("")}</div>`;
|
|
1381
|
+
}
|
|
1382
|
+
function attachment(v, ctx) {
|
|
1383
|
+
const att = rec(v);
|
|
1384
|
+
if (!att)
|
|
1385
|
+
return "";
|
|
1386
|
+
const parts = [];
|
|
1387
|
+
const author = str2(att.author_name);
|
|
1388
|
+
if (author) {
|
|
1389
|
+
const icon = safeUrl(str2(att.author_icon));
|
|
1390
|
+
parts.push(`<div class="sm-att-author">${icon ? `<img class="sm-att-author-icon" src="${icon}" alt="">` : ""}${plainTextToHtml(author)}</div>`);
|
|
1391
|
+
}
|
|
1392
|
+
const title = str2(att.title);
|
|
1393
|
+
if (title) {
|
|
1394
|
+
const link = safeUrl(str2(att.title_link));
|
|
1395
|
+
const inner = plainTextToHtml(title);
|
|
1396
|
+
parts.push(`<div class="sm-att-title">${link ? `<a class="sm-link" href="${link}" target="_blank" rel="noopener">${inner}</a>` : inner}</div>`);
|
|
1397
|
+
}
|
|
1398
|
+
const text = str2(att.text) || (parts.length ? "" : str2(att.fallback));
|
|
1399
|
+
if (text)
|
|
1400
|
+
parts.push(`<div class="sm-att-text">${mrkdwnToHtml(text, ctx)}</div>`);
|
|
1401
|
+
parts.push(attachmentFields(arr(att.fields), ctx));
|
|
1402
|
+
const img = safeUrl(str2(att.image_url));
|
|
1403
|
+
if (img)
|
|
1404
|
+
parts.push(`<img class="sm-att-img" src="${img}" alt="">`);
|
|
1405
|
+
const thumb = !img ? safeUrl(str2(att.thumb_url)) : undefined;
|
|
1406
|
+
if (thumb)
|
|
1407
|
+
parts.push(`<img class="sm-att-thumb" src="${thumb}" alt="">`);
|
|
1408
|
+
const blocks = arr(att.blocks);
|
|
1409
|
+
if (blocks.length)
|
|
1410
|
+
parts.push(renderBlocks(blocks, ctx));
|
|
1411
|
+
const footer = str2(att.footer);
|
|
1412
|
+
const ts = att.ts ? formatAttachmentTs(att.ts) : "";
|
|
1413
|
+
if (footer || ts) {
|
|
1414
|
+
const icon = safeUrl(str2(att.footer_icon));
|
|
1415
|
+
parts.push(`<div class="sm-att-footer">${icon ? `<img class="sm-att-footer-icon" src="${icon}" alt="">` : ""}${plainTextToHtml(footer)}${footer && ts ? " | " : ""}${escapeHtml(ts)}</div>`);
|
|
1416
|
+
}
|
|
1417
|
+
const pretext = str2(att.pretext);
|
|
1418
|
+
const box = `<div class="sm-att" style="border-left-color:${barColor(att.color)}">${parts.join("")}</div>`;
|
|
1419
|
+
return pretext ? `<div class="sm-att-pretext">${mrkdwnToHtml(pretext, ctx)}</div>${box}` : box;
|
|
1420
|
+
}
|
|
1421
|
+
function formatAttachmentTs(v) {
|
|
1422
|
+
const secs = Number(v);
|
|
1423
|
+
if (!Number.isFinite(secs) || secs <= 0)
|
|
1424
|
+
return str2(v);
|
|
1425
|
+
const d = new Date(secs * 1000);
|
|
1426
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
1427
|
+
return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
|
1428
|
+
}
|
|
1429
|
+
function renderAttachments(attachments, ctx) {
|
|
1430
|
+
const list = arr(attachments);
|
|
1431
|
+
if (!list.length)
|
|
1432
|
+
return "";
|
|
1433
|
+
return `<div class="sm-atts">${list.map((a) => attachment(a, ctx)).join("")}</div>`;
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
// src/render/index.ts
|
|
1437
|
+
var DEFAULT_PANEL_WIDTH = "50%";
|
|
1438
|
+
var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
|
1439
|
+
var AVATAR_COLORS = [
|
|
1440
|
+
"#4a154b",
|
|
1441
|
+
"#1264a3",
|
|
1442
|
+
"#2eb67d",
|
|
1443
|
+
"#e01e5a",
|
|
1444
|
+
"#e8912d",
|
|
1445
|
+
"#007a5a",
|
|
1446
|
+
"#7c3aed",
|
|
1447
|
+
"#00a2ac",
|
|
1448
|
+
"#df10a5",
|
|
1449
|
+
"#3d5afe"
|
|
1450
|
+
];
|
|
1451
|
+
var CSS = `
|
|
1452
|
+
*{box-sizing:border-box}
|
|
1453
|
+
html,body{margin:0;padding:0;height:100%}
|
|
1454
|
+
body{font-family:Lato,-apple-system,BlinkMacSystemFont,"Segoe UI",system-ui,Helvetica,Arial,sans-serif;font-size:15px;line-height:1.46668;color:#1d1c1d;background:#fff;-webkit-font-smoothing:antialiased}
|
|
1455
|
+
a{color:#1264a3;text-decoration:none}
|
|
1456
|
+
a:hover{text-decoration:underline}
|
|
1457
|
+
.sm-app{display:flex;height:100vh;overflow:hidden}
|
|
1458
|
+
.sm-side{width:230px;flex:none;background:#3f0e40;color:#d9d0d9;padding:16px 0;overflow-y:auto}
|
|
1459
|
+
.sm-side-title{color:#fff;font-weight:900;font-size:17px;padding:0 16px 12px;border-bottom:1px solid #522653;margin-bottom:10px}
|
|
1460
|
+
.sm-side-team{display:block;font-weight:400;font-size:12px;color:#bda9bd}
|
|
1461
|
+
.sm-side-h{font-size:13px;color:#bda9bd;padding:10px 16px 4px}
|
|
1462
|
+
.sm-side a{display:block;color:#d9d0d9;padding:3px 16px;font-size:15px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
1463
|
+
.sm-side a:hover{background:#522653;color:#fff;text-decoration:none}
|
|
1464
|
+
.sm-side a.sm-active,.sm-side a.sm-active:hover{background:#1164a3;color:#fff}
|
|
1465
|
+
.sm-side-title a:hover{background:none;text-decoration:underline}
|
|
1466
|
+
.sm-main{flex:1;min-width:280px;display:flex;flex-direction:column;overflow:hidden}
|
|
1467
|
+
.sm-shot{width:760px;padding:16px;background:#fff}
|
|
1468
|
+
.sm-top{border-bottom:1px solid #e8e8e8;padding:12px 20px;display:flex;align-items:baseline;gap:12px;flex:none}
|
|
1469
|
+
.sm-top h1{font-size:18px;font-weight:900;margin:0}
|
|
1470
|
+
.sm-top .sm-sub{font-size:13px;color:#616061;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
1471
|
+
.sm-back{font-size:13px;font-weight:700;color:#616061;flex:none}
|
|
1472
|
+
.sm-back:hover{color:#1264a3}
|
|
1473
|
+
.sm-page{padding:12px 20px 32px}
|
|
1474
|
+
.sm-main .sm-page{flex:1;overflow-y:auto}
|
|
1475
|
+
.sm-shot .sm-page{padding:0}
|
|
1476
|
+
.sm-shot .sm-top{padding:0 0 10px;margin-bottom:8px}
|
|
1477
|
+
|
|
1478
|
+
.sm-panel{width:var(--sm-panel-w,50%);min-width:360px;flex:0 1 auto;display:flex;flex-direction:column;border-left:1px solid #e8e8e8;background:#fff;overflow:hidden}
|
|
1479
|
+
.sm-panel-top{display:flex;align-items:flex-start;gap:10px;padding:12px 16px;border-bottom:1px solid #e8e8e8;flex:none}
|
|
1480
|
+
.sm-panel-heading{flex:1;min-width:0}
|
|
1481
|
+
.sm-panel-title{font-size:18px;font-weight:900;margin:0;line-height:22px}
|
|
1482
|
+
.sm-panel-sub{font-size:13px;color:#616061}
|
|
1483
|
+
.sm-panel-close,.sm-panel-expand{font-size:16px;line-height:22px;color:#616061;padding:0 6px;border-radius:4px;flex:none}
|
|
1484
|
+
.sm-panel-close{font-size:20px}
|
|
1485
|
+
.sm-panel-close:hover,.sm-panel-expand:hover{background:#f0f0f0;color:#1d1c1d;text-decoration:none}
|
|
1486
|
+
.sm-panel-back{display:none;padding:8px 16px;font-size:13px;font-weight:700;border-bottom:1px solid #e8e8e8;flex:none}
|
|
1487
|
+
.sm-panel-body{flex:1;overflow-y:auto;padding:12px 16px 32px}
|
|
1488
|
+
.sm-resize{width:6px;flex:none;cursor:col-resize;background:#f2f2f2;border-left:1px solid #e8e8e8}
|
|
1489
|
+
.sm-resize:hover,.sm-resize.sm-dragging{background:#1264a3;border-left-color:#1264a3}
|
|
1490
|
+
.sm-icon-btn{display:inline-block;font-size:16px;line-height:22px;color:#616061;padding:0 6px;border-radius:4px;cursor:pointer}
|
|
1491
|
+
.sm-icon-btn:hover{background:#f0f0f0;color:#1d1c1d;text-decoration:none}
|
|
1492
|
+
.sm-composer{position:relative;flex:none;border-top:1px solid #e8e8e8;padding:10px 20px 12px;background:#fff}
|
|
1493
|
+
.sm-panel .sm-composer{padding:10px 16px 12px}
|
|
1494
|
+
.sm-composer-box{border:1px solid #bbb;border-radius:8px;padding:8px 10px;background:#fff}
|
|
1495
|
+
.sm-composer-box:focus-within{border-color:#1264a3;box-shadow:0 0 0 1px #1264a3}
|
|
1496
|
+
.sm-composer-row{display:flex;align-items:center;gap:8px;margin-top:6px}
|
|
1497
|
+
.sm-composer-user{flex:0 1 auto;min-width:0;max-width:170px;border:0;border-radius:4px;background:#f0f0f0;color:#1d1c1d;font-family:inherit;font-size:12px;padding:4px 6px}
|
|
1498
|
+
.sm-composer-user:hover{background:#e8e8e8}
|
|
1499
|
+
.sm-composer-text{display:block;width:100%;border:0;outline:none;resize:vertical;font-family:inherit;font-size:15px;line-height:20px;color:#1d1c1d;padding:0;background:none}
|
|
1500
|
+
.sm-composer-send{flex:none;margin-left:auto;border:0;border-radius:4px;background:#007a5a;color:#fff;font-family:inherit;font-weight:700;font-size:13px;padding:6px 14px;cursor:pointer}
|
|
1501
|
+
.sm-composer-send:hover{background:#148567;color:#fff}
|
|
1502
|
+
.sm-composer-hint{font-size:11px;color:#616061;margin-top:4px}
|
|
1503
|
+
.sm-mentions{display:none;position:absolute;left:20px;right:20px;bottom:100%;margin-bottom:6px;max-height:260px;overflow-y:auto;background:#fff;border:1px solid #ddd;border-radius:8px;box-shadow:0 4px 16px rgba(0,0,0,.16);z-index:5}
|
|
1504
|
+
.sm-panel .sm-mentions{left:16px;right:16px}
|
|
1505
|
+
.sm-mention{display:flex;align-items:center;gap:8px;padding:6px 10px;font-size:14px;cursor:pointer;color:#1d1c1d}
|
|
1506
|
+
.sm-mention-on{background:#1264a3;color:#fff}
|
|
1507
|
+
.sm-mention-on .sm-mention-real{color:#dbe9f5}
|
|
1508
|
+
.sm-mention-av{width:20px;height:20px;border-radius:3px;flex:none;display:inline-flex;align-items:center;justify-content:center;color:#fff;font-size:10px;font-weight:700}
|
|
1509
|
+
.sm-mention-name{font-weight:700}
|
|
1510
|
+
.sm-mention-real{color:#616061;font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
1511
|
+
|
|
1512
|
+
.sm-side a,.sm-btn,.sm-select,.sm-reaction,.sm-file-card,.sm-prompt,.sm-replies,.sm-back,.sm-panel-close,.sm-panel-expand,.sm-composer-send,.sm-composer-user,.sm-top-actions a{cursor:pointer}
|
|
1513
|
+
.sm-composer-text{cursor:text}
|
|
1514
|
+
.sm-badge,.sm-time,.sm-daydiv,.sm-pill,.sm-emoji-name,.sm-avatar,.sm-name,.sm-composer-hint,.sm-unsupported,.sm-tag,.sm-card{cursor:default}
|
|
1515
|
+
.sm-top-actions{margin-left:auto;display:flex;gap:12px;align-items:baseline;flex:none}
|
|
1516
|
+
.sm-top-actions a{font-size:13px;font-weight:700;color:#616061}
|
|
1517
|
+
.sm-top-actions a:hover{color:#1264a3}
|
|
1518
|
+
@media (max-width:900px){
|
|
1519
|
+
.sm-side{display:none}
|
|
1520
|
+
.sm-app-thread .sm-main{display:none}
|
|
1521
|
+
.sm-panel{width:100%;min-width:0;border-left:0}
|
|
1522
|
+
.sm-panel-back{display:block}
|
|
1523
|
+
.sm-panel-expand,.sm-resize{display:none}
|
|
1524
|
+
}
|
|
1525
|
+
|
|
1526
|
+
.sm-daydiv{display:flex;align-items:center;gap:10px;margin:14px 0 8px}
|
|
1527
|
+
.sm-daydiv:before,.sm-daydiv:after{content:"";flex:1;height:1px;background:#e8e8e8}
|
|
1528
|
+
.sm-daydiv span{border:1px solid #e8e8e8;border-radius:12px;padding:2px 12px;font-size:13px;font-weight:700;color:#454245;background:#fff}
|
|
1529
|
+
|
|
1530
|
+
.sm-msg{display:flex;gap:12px;padding:8px 8px;border-radius:6px}
|
|
1531
|
+
.sm-msg:hover{background:#f8f8f8}
|
|
1532
|
+
.sm-msg-eph{background:#fffbe6}
|
|
1533
|
+
.sm-msg-eph:hover{background:#fff7d1}
|
|
1534
|
+
.sm-msg-open,.sm-msg-open:hover{background:#fff8e2;box-shadow:inset 3px 0 0 #ecb22e}
|
|
1535
|
+
.sm-avatar{width:36px;height:36px;flex:none;border-radius:4px;display:flex;align-items:center;justify-content:center;color:#fff;font-weight:700;font-size:14px;overflow:hidden}
|
|
1536
|
+
.sm-avatar img{width:36px;height:36px;object-fit:cover}
|
|
1537
|
+
.sm-avatar-emoji{font-size:20px;background:#f0f0f0}
|
|
1538
|
+
.sm-msg-body{min-width:0;flex:1}
|
|
1539
|
+
.sm-msg-head{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap;margin-bottom:1px}
|
|
1540
|
+
.sm-name{font-weight:700;font-size:15px;color:#1d1c1d}
|
|
1541
|
+
.sm-badge{background:#e8e8e8;color:#616061;font-size:10px;font-weight:700;border-radius:2px;padding:1px 4px;letter-spacing:.4px;text-transform:uppercase}
|
|
1542
|
+
.sm-time{font-size:12px;color:#616061}
|
|
1543
|
+
.sm-text{font-size:15px;line-height:22px;word-wrap:break-word;overflow-wrap:anywhere}
|
|
1544
|
+
.sm-edited{font-size:12px;color:#616061}
|
|
1545
|
+
.sm-eph-note{font-size:12px;color:#8a6d1a;margin-top:4px}
|
|
1546
|
+
.sm-stream{display:inline-block;margin-left:4px;color:#616061;font-weight:700;animation:sm-pulse 1s ease-in-out infinite}
|
|
1547
|
+
@keyframes sm-pulse{0%,100%{opacity:.25}50%{opacity:1}}
|
|
1548
|
+
|
|
1549
|
+
.sm-pill{background:#e8f5fa;color:#1264a3;border-radius:3px;padding:0 2px}
|
|
1550
|
+
.sm-link{color:#1264a3}
|
|
1551
|
+
.sm-emoji-name{color:#616061}
|
|
1552
|
+
.sm-code{font-family:Monaco,Menlo,Consolas,"Courier New",monospace;font-size:12px;background:#f8f8f8;border:1px solid #ddd;border-radius:3px;padding:1px 3px;color:#e01e5a}
|
|
1553
|
+
.sm-pre{font-family:Monaco,Menlo,Consolas,"Courier New",monospace;font-size:12px;line-height:18px;background:#f8f8f8;border:1px solid #ddd;border-radius:4px;padding:8px;margin:4px 0;white-space:pre-wrap;word-break:break-word;color:#1d1c1d}
|
|
1554
|
+
.sm-quote{border-left:4px solid #ddd;margin:4px 0;padding:0 0 0 12px;color:#1d1c1d}
|
|
1555
|
+
.sm-list{margin:2px 0;padding-left:22px}
|
|
1556
|
+
.sm-list li{margin:1px 0}
|
|
1557
|
+
|
|
1558
|
+
.sm-blocks{margin:2px 0}
|
|
1559
|
+
.sm-block{margin:6px 0}
|
|
1560
|
+
.sm-header-block{font-size:18px;font-weight:900;line-height:24px}
|
|
1561
|
+
.sm-section-split{display:flex;gap:12px;align-items:flex-start}
|
|
1562
|
+
.sm-section-main{flex:1;min-width:0}
|
|
1563
|
+
.sm-section-acc{flex:none}
|
|
1564
|
+
.sm-fields{display:flex;flex-wrap:wrap;gap:8px 16px;margin-top:6px}
|
|
1565
|
+
.sm-field{flex:1 1 40%;min-width:0;font-size:14px;line-height:20px}
|
|
1566
|
+
.sm-field-wide{flex-basis:100%}
|
|
1567
|
+
.sm-field-title{font-weight:700}
|
|
1568
|
+
.sm-context{display:flex;flex-wrap:wrap;align-items:center;gap:8px;font-size:13px;line-height:18px;color:#616061}
|
|
1569
|
+
.sm-context .sm-pre,.sm-context .sm-code{font-size:11px}
|
|
1570
|
+
.sm-context-img{width:16px;height:16px;border-radius:2px;object-fit:cover}
|
|
1571
|
+
.sm-hr{border:0;border-top:1px solid #ddd;margin:10px 0}
|
|
1572
|
+
.sm-actions{display:flex;flex-wrap:wrap;gap:8px;align-items:center}
|
|
1573
|
+
.sm-btn{display:inline-block;border:1px solid #bbb;border-radius:4px;padding:6px 12px;font-size:14px;font-weight:700;color:#1d1c1d;background:#fff;line-height:16px}
|
|
1574
|
+
.sm-btn:hover{text-decoration:none;background:#f8f8f8;color:#1d1c1d}
|
|
1575
|
+
.sm-btn-primary{background:#007a5a;border-color:#007a5a;color:#fff}
|
|
1576
|
+
.sm-btn-primary:hover{background:#148567;border-color:#148567;color:#fff}
|
|
1577
|
+
.sm-btn-danger{background:#e01e5a;border-color:#e01e5a;color:#fff}
|
|
1578
|
+
.sm-btn-danger:hover{background:#c31f4c;border-color:#c31f4c;color:#fff}
|
|
1579
|
+
.sm-btn-confirm{margin-left:6px;opacity:.7;font-weight:400}
|
|
1580
|
+
.sm-select{display:inline-flex;align-items:center;gap:6px;border:1px solid #bbb;border-radius:4px;padding:6px 10px;font-size:14px;color:#1d1c1d;background:#fff;line-height:16px}
|
|
1581
|
+
.sm-select-caret{color:#616061;font-size:12px}
|
|
1582
|
+
.sm-options{display:flex;flex-direction:column;gap:4px;font-size:14px}
|
|
1583
|
+
.sm-acc-img{max-width:88px;max-height:88px;border-radius:4px;display:block}
|
|
1584
|
+
.sm-img{max-width:100%;border-radius:6px;display:block;margin-top:4px}
|
|
1585
|
+
.sm-img-title{font-size:13px;font-weight:700;color:#454245}
|
|
1586
|
+
.sm-label{font-weight:700;font-size:14px;margin-bottom:4px}
|
|
1587
|
+
.sm-hint{font-size:12px;color:#616061;margin-top:4px}
|
|
1588
|
+
.sm-input{border:1px solid #bbb;border-radius:4px;padding:8px 10px;font-size:14px;min-height:36px;background:#fff}
|
|
1589
|
+
.sm-input-multi{min-height:76px}
|
|
1590
|
+
.sm-input-ph{color:#8d8d8e}
|
|
1591
|
+
.sm-file-block{font-size:14px;color:#454245}
|
|
1592
|
+
.sm-video-thumb{max-width:320px;border-radius:6px;display:block}
|
|
1593
|
+
.sm-video-title{font-size:14px;font-weight:700;margin-top:4px}
|
|
1594
|
+
.sm-unsupported{display:inline-block;background:#f4f4f4;border:1px solid #ddd;border-radius:4px;padding:4px 8px;font-size:12px;color:#616061;font-family:Monaco,Menlo,monospace}
|
|
1595
|
+
.sm-rt-section{margin:2px 0}
|
|
1596
|
+
|
|
1597
|
+
.sm-atts{margin-top:4px}
|
|
1598
|
+
.sm-att{border-left:4px solid #ddd;border-radius:2px;padding:2px 0 2px 12px;margin:6px 0;max-width:600px}
|
|
1599
|
+
.sm-att-pretext{font-size:15px;line-height:22px;margin-top:4px}
|
|
1600
|
+
.sm-att-author{display:flex;align-items:center;gap:6px;font-size:13px;font-weight:700;color:#454245}
|
|
1601
|
+
.sm-att-author-icon{width:16px;height:16px;border-radius:2px}
|
|
1602
|
+
.sm-att-title{font-size:15px;font-weight:700;margin:2px 0}
|
|
1603
|
+
.sm-att-text{font-size:15px;line-height:21px}
|
|
1604
|
+
.sm-att-img{max-width:360px;border-radius:6px;display:block;margin-top:6px}
|
|
1605
|
+
.sm-att-thumb{max-width:80px;border-radius:4px;display:block;margin-top:6px}
|
|
1606
|
+
.sm-att-footer{display:flex;align-items:center;gap:6px;font-size:12px;color:#616061;margin-top:6px}
|
|
1607
|
+
.sm-att-footer-icon{width:14px;height:14px;border-radius:2px}
|
|
1608
|
+
|
|
1609
|
+
.sm-files{margin-top:6px;display:flex;flex-direction:column;gap:6px;align-items:flex-start}
|
|
1610
|
+
.sm-file-img{max-width:480px;max-height:420px;border-radius:8px;border:1px solid #e8e8e8;display:block}
|
|
1611
|
+
.sm-file-card{display:flex;gap:10px;align-items:center;border:1px solid #ddd;border-radius:8px;padding:8px 12px;max-width:420px}
|
|
1612
|
+
.sm-file-icon{font-size:20px}
|
|
1613
|
+
.sm-file-name{font-weight:700;font-size:14px}
|
|
1614
|
+
.sm-file-meta{font-size:12px;color:#616061}
|
|
1615
|
+
|
|
1616
|
+
.sm-reactions{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px}
|
|
1617
|
+
.sm-reaction{display:inline-flex;align-items:center;gap:5px;background:#f0f0f0;border:1px solid #f0f0f0;border-radius:12px;padding:1px 8px;font-size:12px;line-height:18px;color:#454245}
|
|
1618
|
+
.sm-reaction:hover{background:#e8f5fa;border-color:#1264a3;color:#1d1c1d}
|
|
1619
|
+
.sm-reaction-count{font-weight:700;font-size:12px}
|
|
1620
|
+
.sm-file-card:hover{background:#f8f8f8}
|
|
1621
|
+
|
|
1622
|
+
.sm-replies{display:inline-flex;align-items:center;gap:8px;margin-top:4px;font-size:13px;font-weight:700;color:#1264a3}
|
|
1623
|
+
.sm-replies:hover{color:#0b4c81}
|
|
1624
|
+
.sm-replies-time{font-weight:400;color:#616061}
|
|
1625
|
+
.sm-empty{color:#616061;font-size:14px;padding:16px 0}
|
|
1626
|
+
|
|
1627
|
+
.sm-assist{border:1px solid #e8e8e8;border-radius:8px;padding:10px 12px;margin-bottom:10px;background:#fafafa}
|
|
1628
|
+
.sm-assist-title{font-weight:700;font-size:14px}
|
|
1629
|
+
.sm-assist-status{font-size:13px;color:#616061;margin-top:2px}
|
|
1630
|
+
.sm-assist-status .sm-stream{margin-left:2px}
|
|
1631
|
+
.sm-prompts{display:flex;flex-wrap:wrap;gap:8px;margin-top:8px}
|
|
1632
|
+
.sm-prompt{border:1px solid #ddd;border-radius:16px;padding:5px 12px;font-size:13px;background:#fff}
|
|
1633
|
+
|
|
1634
|
+
.sm-cards{display:flex;flex-wrap:wrap;gap:12px;margin-bottom:16px}
|
|
1635
|
+
.sm-card{border:1px solid #e8e8e8;border-radius:8px;padding:10px 14px;min-width:150px}
|
|
1636
|
+
.sm-card-k{font-size:12px;color:#616061;text-transform:uppercase;letter-spacing:.4px}
|
|
1637
|
+
.sm-card-v{font-size:16px;font-weight:700;margin-top:2px}
|
|
1638
|
+
.sm-h2{font-size:15px;font-weight:900;margin:18px 0 6px}
|
|
1639
|
+
.sm-table{border-collapse:collapse;width:100%;max-width:900px;font-size:14px}
|
|
1640
|
+
.sm-table th{text-align:left;font-size:12px;color:#616061;font-weight:700;text-transform:uppercase;letter-spacing:.4px;padding:4px 10px 4px 0;border-bottom:1px solid #e8e8e8}
|
|
1641
|
+
.sm-table td{padding:6px 10px 6px 0;border-bottom:1px solid #f2f2f2;vertical-align:top}
|
|
1642
|
+
.sm-tag{display:inline-block;background:#f0f0f0;color:#454245;border-radius:10px;padding:0 8px;font-size:11px;font-weight:700}
|
|
1643
|
+
.sm-muted{color:#616061}
|
|
1644
|
+
`;
|
|
1645
|
+
function ctxOf(store) {
|
|
1646
|
+
return { users: store.users, channels: store.channels, botUserId: store.bot.userId };
|
|
1647
|
+
}
|
|
1648
|
+
function panelWidth(opts) {
|
|
1649
|
+
const raw = (opts.panelWidth ?? "").trim();
|
|
1650
|
+
return /^\d{1,4}(%|px|vw|rem)$/.test(raw) ? raw : DEFAULT_PANEL_WIDTH;
|
|
1651
|
+
}
|
|
1652
|
+
function panelParam(opts) {
|
|
1653
|
+
const width = (opts.panelWidth ?? "").trim();
|
|
1654
|
+
if (!/^\d{1,4}(%|px|vw|rem)$/.test(width) || width === DEFAULT_PANEL_WIDTH)
|
|
1655
|
+
return "";
|
|
1656
|
+
return width.endsWith("%") ? width.slice(0, -1) : width;
|
|
1657
|
+
}
|
|
1658
|
+
function query(opts, over = {}) {
|
|
1659
|
+
if (opts.screenshot)
|
|
1660
|
+
return "?screenshot";
|
|
1661
|
+
const parts = [];
|
|
1662
|
+
if (opts.refreshSec)
|
|
1663
|
+
parts.push(`refresh=${opts.refreshSec}`);
|
|
1664
|
+
const panel = panelParam(opts);
|
|
1665
|
+
if (panel)
|
|
1666
|
+
parts.push(`panel=${panel}`);
|
|
1667
|
+
if (over.full ?? opts.threadView === "full")
|
|
1668
|
+
parts.push("full");
|
|
1669
|
+
return parts.length ? `?${parts.join("&")}` : "";
|
|
1670
|
+
}
|
|
1671
|
+
function channelHref(channelId, opts) {
|
|
1672
|
+
return `/c/${encodeURIComponent(channelId)}${query(opts, { full: false })}`;
|
|
1673
|
+
}
|
|
1674
|
+
function homeHref(opts) {
|
|
1675
|
+
return `/${query(opts, { full: false })}`;
|
|
1676
|
+
}
|
|
1677
|
+
function threadHref(channelId, ts, opts, over = {}) {
|
|
1678
|
+
return `/c/${encodeURIComponent(channelId)}/t/${encodeURIComponent(ts)}${query(opts, over)}`;
|
|
1679
|
+
}
|
|
1680
|
+
function pad(n) {
|
|
1681
|
+
return String(n).padStart(2, "0");
|
|
1682
|
+
}
|
|
1683
|
+
function timeOf(ts) {
|
|
1684
|
+
const d = new Date(Number(ts) * 1000);
|
|
1685
|
+
if (Number.isNaN(d.getTime()))
|
|
1686
|
+
return "";
|
|
1687
|
+
return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
|
1688
|
+
}
|
|
1689
|
+
function dayKey(d) {
|
|
1690
|
+
return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
|
|
1691
|
+
}
|
|
1692
|
+
function dayLabel(ts) {
|
|
1693
|
+
const d = new Date(Number(ts) * 1000);
|
|
1694
|
+
if (Number.isNaN(d.getTime()))
|
|
1695
|
+
return "";
|
|
1696
|
+
const now = new Date;
|
|
1697
|
+
if (dayKey(d) === dayKey(now))
|
|
1698
|
+
return "Today";
|
|
1699
|
+
const yesterday = new Date(now.getTime() - 86400000);
|
|
1700
|
+
if (dayKey(d) === dayKey(yesterday))
|
|
1701
|
+
return "Yesterday";
|
|
1702
|
+
return `${MONTHS[d.getMonth()]} ${d.getDate()}, ${d.getFullYear()}`;
|
|
1703
|
+
}
|
|
1704
|
+
function fileSize(bytes) {
|
|
1705
|
+
if (bytes < 1024)
|
|
1706
|
+
return `${bytes} B`;
|
|
1707
|
+
if (bytes < 1024 * 1024)
|
|
1708
|
+
return `${(bytes / 1024).toFixed(1)} KB`;
|
|
1709
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
1710
|
+
}
|
|
1711
|
+
function hashIndex(s, buckets) {
|
|
1712
|
+
let h = 0;
|
|
1713
|
+
for (let i = 0;i < s.length; i++)
|
|
1714
|
+
h = h * 31 + s.charCodeAt(i) >>> 0;
|
|
1715
|
+
return h % buckets;
|
|
1716
|
+
}
|
|
1717
|
+
function initials(name) {
|
|
1718
|
+
const words = name.replace(/[^\p{L}\p{N} ]/gu, " ").trim().split(/\s+/);
|
|
1719
|
+
const letters = words.slice(0, 2).map((w) => w[0] ?? "").join("");
|
|
1720
|
+
return (letters || name.slice(0, 2) || "?").toUpperCase();
|
|
1721
|
+
}
|
|
1722
|
+
function channelLabel(store, c) {
|
|
1723
|
+
if (!c.is_im)
|
|
1724
|
+
return `#${c.name}`;
|
|
1725
|
+
const peer = c.user ? store.users.get(c.user) : undefined;
|
|
1726
|
+
return peer ? displayName(peer) : c.name;
|
|
1727
|
+
}
|
|
1728
|
+
function channelIcon(c) {
|
|
1729
|
+
if (c.is_im)
|
|
1730
|
+
return "@";
|
|
1731
|
+
if (c.is_private)
|
|
1732
|
+
return "\uD83D\uDD12";
|
|
1733
|
+
return "#";
|
|
1734
|
+
}
|
|
1735
|
+
function channelKind(c) {
|
|
1736
|
+
if (c.is_im)
|
|
1737
|
+
return "DM";
|
|
1738
|
+
if (c.is_private)
|
|
1739
|
+
return "private";
|
|
1740
|
+
return "public";
|
|
1741
|
+
}
|
|
1742
|
+
function authorName(store, m) {
|
|
1743
|
+
if (m.username)
|
|
1744
|
+
return m.username;
|
|
1745
|
+
const user = m.user ? store.users.get(m.user) : undefined;
|
|
1746
|
+
if (user)
|
|
1747
|
+
return user.real_name || user.name;
|
|
1748
|
+
return m.bot_profile?.name ?? m.user ?? "unknown";
|
|
1749
|
+
}
|
|
1750
|
+
function avatarHtml(m, name) {
|
|
1751
|
+
const emojiName = m.icons?.emoji;
|
|
1752
|
+
if (emojiName) {
|
|
1753
|
+
const char = emojiChar(emojiName) ?? emojiName.replace(/:/g, "");
|
|
1754
|
+
return `<div class="sm-avatar sm-avatar-emoji">${escapeHtml(char)}</div>`;
|
|
1755
|
+
}
|
|
1756
|
+
const imageUrl = m.icons?.image_72 ?? m.icons?.image_48 ?? m.icons?.image_64;
|
|
1757
|
+
if (imageUrl && /^(https?:\/\/|\/)/.test(imageUrl)) {
|
|
1758
|
+
return `<div class="sm-avatar"><img src="${escapeHtml(imageUrl)}" alt=""></div>`;
|
|
1759
|
+
}
|
|
1760
|
+
const seed = m.user ?? m.bot_id ?? name;
|
|
1761
|
+
const color = AVATAR_COLORS[hashIndex(seed, AVATAR_COLORS.length)];
|
|
1762
|
+
return `<div class="sm-avatar" style="background:${color}">${escapeHtml(initials(name))}</div>`;
|
|
1763
|
+
}
|
|
1764
|
+
function reactionsHtml(store, m) {
|
|
1765
|
+
if (!m.reactions?.length)
|
|
1766
|
+
return "";
|
|
1767
|
+
const chips = m.reactions.map((r) => {
|
|
1768
|
+
const who = r.users.map((id) => {
|
|
1769
|
+
const user = store.users.get(id);
|
|
1770
|
+
return user ? displayName(user) : id;
|
|
1771
|
+
}).join(", ");
|
|
1772
|
+
const char = emojiChar(r.name) ?? `:${r.name}:`;
|
|
1773
|
+
return `<span class="sm-reaction" title="${escapeHtml(who)}">${escapeHtml(char)}<span class="sm-reaction-count">${r.count}</span></span>`;
|
|
1774
|
+
});
|
|
1775
|
+
return `<div class="sm-reactions">${chips.join("")}</div>`;
|
|
1776
|
+
}
|
|
1777
|
+
function fileUrl(f, token) {
|
|
1778
|
+
if (!f.url_private)
|
|
1779
|
+
return "";
|
|
1780
|
+
return escapeHtml(`${f.url_private}${f.url_private.includes("?") ? "&" : "?"}t=${token}`);
|
|
1781
|
+
}
|
|
1782
|
+
function filesHtml(files, token) {
|
|
1783
|
+
if (!files?.length)
|
|
1784
|
+
return "";
|
|
1785
|
+
const cards = files.map((f) => {
|
|
1786
|
+
if (f.mimetype?.startsWith("image/") && f.url_private) {
|
|
1787
|
+
return `<img class="sm-file-img" src="${fileUrl(f, token)}" alt="${escapeHtml(f.title || f.name)}">`;
|
|
1788
|
+
}
|
|
1789
|
+
const href = fileUrl(f, token);
|
|
1790
|
+
const name = escapeHtml(f.title || f.name);
|
|
1791
|
+
const meta = `${escapeHtml(f.pretty_type || f.filetype || "File")} \xB7 ${fileSize(f.size ?? 0)}`;
|
|
1792
|
+
const label = href ? `<a href="${href}">${name}</a>` : name;
|
|
1793
|
+
return `<div class="sm-file-card"><div class="sm-file-icon">\uD83D\uDCC4</div><div><div class="sm-file-name">${label}</div><div class="sm-file-meta">${meta}</div></div></div>`;
|
|
1794
|
+
});
|
|
1795
|
+
return `<div class="sm-files">${cards.join("")}</div>`;
|
|
1796
|
+
}
|
|
1797
|
+
function renderMessage(store, ctx, m, opts, flags = {}) {
|
|
1798
|
+
const name = authorName(store, m);
|
|
1799
|
+
const isApp = Boolean(m.bot_id);
|
|
1800
|
+
const blocks = Array.isArray(m.blocks) && m.blocks.length ? m.blocks : undefined;
|
|
1801
|
+
const body = [];
|
|
1802
|
+
if (blocks)
|
|
1803
|
+
body.push(renderBlocks(blocks, ctx));
|
|
1804
|
+
else if (m.text)
|
|
1805
|
+
body.push(`<div class="sm-text">${mrkdwnToHtml(m.text, ctx)}</div>`);
|
|
1806
|
+
if (m.edited)
|
|
1807
|
+
body.push(`<div class="sm-edited">(edited)</div>`);
|
|
1808
|
+
if (m.attachments?.length)
|
|
1809
|
+
body.push(renderAttachments(m.attachments, ctx));
|
|
1810
|
+
body.push(filesHtml(m.files, store.bot.token));
|
|
1811
|
+
body.push(reactionsHtml(store, m));
|
|
1812
|
+
if (flags.ephemeral)
|
|
1813
|
+
body.push(`<div class="sm-eph-note">Only visible to you</div>`);
|
|
1814
|
+
if (flags.threadLink && m.reply_count) {
|
|
1815
|
+
const count = `${m.reply_count} ${m.reply_count === 1 ? "reply" : "replies"}`;
|
|
1816
|
+
const last = m.latest_reply ? `<span class="sm-replies-time">Last reply ${timeOf(m.latest_reply)}</span>` : "";
|
|
1817
|
+
body.push(`<a class="sm-replies" href="${threadHref(m.channel, m.thread_ts ?? m.ts, opts)}">${count}${last}</a>`);
|
|
1818
|
+
}
|
|
1819
|
+
const streaming = m.streaming_state === "in_progress" ? `<span class="sm-stream" title="streaming">\u2022\u2022\u2022</span>` : "";
|
|
1820
|
+
const open = flags.openTs && flags.openTs === m.ts ? " sm-msg-open" : "";
|
|
1821
|
+
return `<div class="sm-msg${flags.ephemeral ? " sm-msg-eph" : ""}${open}">${avatarHtml(m, name)}<div class="sm-msg-body"><div class="sm-msg-head"><span class="sm-name">${escapeHtml(name)}</span>${isApp ? `<span class="sm-badge">APP</span>` : ""}<span class="sm-time">${timeOf(m.ts)}</span>${streaming}</div>${body.join("")}</div></div>`;
|
|
1822
|
+
}
|
|
1823
|
+
function renderMessageList(store, ctx, messages, opts, flags = {}) {
|
|
1824
|
+
const out = [];
|
|
1825
|
+
let day = "";
|
|
1826
|
+
for (const m of messages) {
|
|
1827
|
+
const label = flags.dividers === false ? "" : dayLabel(m.ts);
|
|
1828
|
+
if (label && label !== day) {
|
|
1829
|
+
day = label;
|
|
1830
|
+
out.push(`<div class="sm-daydiv"><span>${escapeHtml(label)}</span></div>`);
|
|
1831
|
+
}
|
|
1832
|
+
out.push(renderMessage(store, ctx, m, opts, { ...flags, ephemeral: m._ephemeral === true }));
|
|
1833
|
+
}
|
|
1834
|
+
return out.join("");
|
|
1835
|
+
}
|
|
1836
|
+
function sidebar(store, opts, active) {
|
|
1837
|
+
const channels = [...store.channels.values()].sort((a, b) => channelLabel(store, a).localeCompare(channelLabel(store, b)));
|
|
1838
|
+
const links = channels.map((c) => `<a class="${c.id === active ? "sm-active" : ""}" href="${channelHref(c.id, opts)}">${escapeHtml(channelIcon(c))} ${escapeHtml(c.is_im ? channelLabel(store, c) : c.name)}</a>`).join("");
|
|
1839
|
+
return `<nav class="sm-side"><div class="sm-side-title"><a href="${homeHref(opts)}" style="color:#fff">${escapeHtml(store.team.name)}</a><span class="sm-side-team">${escapeHtml(store.team.id)} \xB7 slack-mock</span></div><div class="sm-side-h">Channels</div>${links}</nav>`;
|
|
1840
|
+
}
|
|
1841
|
+
function shell(store, opts, parts) {
|
|
1842
|
+
const refresh = opts.refreshSec && !opts.screenshot ? `<meta http-equiv="refresh" content="${Math.max(1, Math.floor(opts.refreshSec))}">` : "";
|
|
1843
|
+
const style = opts.screenshot ? "" : ` style="--sm-panel-w:${panelWidth(opts)}"`;
|
|
1844
|
+
const head = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml(parts.title)}</title>${refresh}<style>${CSS}</style></head>`;
|
|
1845
|
+
if (opts.screenshot) {
|
|
1846
|
+
return `${head}<body><div class="sm-shot">${parts.header}<div class="sm-page">${parts.main}</div></div></body></html>`;
|
|
1847
|
+
}
|
|
1848
|
+
const app = `sm-app${parts.panel ? " sm-app-thread" : ""}`;
|
|
1849
|
+
const handle = parts.panel ? `<div class="sm-resize" title="Drag to resize, double-click to reset"></div>` : "";
|
|
1850
|
+
return `${head}<body${style}><div class="${app}">${sidebar(store, opts, parts.active)}<div class="sm-main">${parts.header}<div class="sm-page sm-scroll">${parts.main}</div>${parts.footer ?? ""}</div>${handle}${parts.panel ?? ""}</div>${parts.script ?? ""}</body></html>`;
|
|
1851
|
+
}
|
|
1852
|
+
function topbar(title, sub, back, actions) {
|
|
1853
|
+
const backLink = back ? `<a class="sm-back" href="${back.href}">${escapeHtml(back.label)}</a>` : "";
|
|
1854
|
+
const right = actions ? `<div class="sm-top-actions">${actions}</div>` : "";
|
|
1855
|
+
return `<div class="sm-top">${backLink}<h1>${title}</h1>${sub ? `<div class="sm-sub">${sub}</div>` : ""}${right}</div>`;
|
|
1856
|
+
}
|
|
1857
|
+
function indexView(store, opts) {
|
|
1858
|
+
const cards = [
|
|
1859
|
+
["Workspace", escapeHtml(store.team.name)],
|
|
1860
|
+
["Team id", escapeHtml(store.team.id)],
|
|
1861
|
+
["Bot user", escapeHtml(`${store.app.name} (${store.bot.userId})`)],
|
|
1862
|
+
["Connections", String(opts.connections ?? 0)]
|
|
1863
|
+
].map(([k, v]) => `<div class="sm-card"><div class="sm-card-k">${k}</div><div class="sm-card-v">${v}</div></div>`).join("");
|
|
1864
|
+
const channels = [...store.channels.values()];
|
|
1865
|
+
const channelRows = channels.map((c) => {
|
|
1866
|
+
const count = store.messages.get(c.id)?.length ?? 0;
|
|
1867
|
+
return `<tr><td><a href="${channelHref(c.id, opts)}">${escapeHtml(channelIcon(c))} ${escapeHtml(c.is_im ? channelLabel(store, c) : c.name)}</a></td><td><span class="sm-tag">${channelKind(c)}</span></td><td class="sm-muted">${c.id}</td><td>${count}</td></tr>`;
|
|
1868
|
+
}).join("");
|
|
1869
|
+
const userRows = [...store.users.values()].map((u) => `<tr><td>${escapeHtml(u.name)}</td><td>${escapeHtml(u.real_name)}</td><td class="sm-muted">${escapeHtml(u.profile.email ?? "")}</td><td class="sm-muted">${u.id}</td><td>${u.is_bot ? `<span class="sm-tag">bot</span>` : ""}</td></tr>`).join("");
|
|
1870
|
+
const main = `<div class="sm-cards">${cards}</div>
|
|
1871
|
+
<div class="sm-h2">Channels</div>
|
|
1872
|
+
${channels.length ? `<table class="sm-table"><tr><th>Name</th><th>Type</th><th>Id</th><th>Messages</th></tr>${channelRows}</table>` : `<div class="sm-empty">No channels yet</div>`}
|
|
1873
|
+
<div class="sm-h2">Users</div>
|
|
1874
|
+
<table class="sm-table"><tr><th>Name</th><th>Real name</th><th>Email</th><th>Id</th><th></th></tr>${userRows}</table>`;
|
|
1875
|
+
return shell(store, opts, {
|
|
1876
|
+
title: `${store.team.name} \xB7 slack-mock`,
|
|
1877
|
+
header: topbar(escapeHtml(store.team.name), "slack-mock workspace"),
|
|
1878
|
+
main
|
|
1879
|
+
});
|
|
1880
|
+
}
|
|
1881
|
+
function channelMessages(store, channel) {
|
|
1882
|
+
const history = store.history(channel.id, { limit: 1000 }).items;
|
|
1883
|
+
const ephemerals = store.ephemerals.filter((e) => e.channel === channel.id).map((e) => ({ ...e, _ephemeral: true }));
|
|
1884
|
+
return [...history, ...ephemerals].sort((a, b) => Number(a.ts) - Number(b.ts));
|
|
1885
|
+
}
|
|
1886
|
+
function channelColumn(store, ctx, opts, channel, openTs) {
|
|
1887
|
+
const messages = channelMessages(store, channel);
|
|
1888
|
+
if (!messages.length)
|
|
1889
|
+
return `<div class="sm-empty">No messages yet</div>`;
|
|
1890
|
+
return renderMessageList(store, ctx, messages, opts, {
|
|
1891
|
+
threadLink: true,
|
|
1892
|
+
dividers: true,
|
|
1893
|
+
openTs
|
|
1894
|
+
});
|
|
1895
|
+
}
|
|
1896
|
+
function channelHeader(store, opts, channel) {
|
|
1897
|
+
const sub = [channel.topic.value, channel.purpose.value].filter(Boolean).join(" \xB7 ");
|
|
1898
|
+
const back = opts.screenshot ? undefined : { href: homeHref(opts), label: "\u2190 Workspace" };
|
|
1899
|
+
return topbar(escapeHtml(channelLabel(store, channel)), escapeHtml(sub), back);
|
|
1900
|
+
}
|
|
1901
|
+
function humanUsers(store) {
|
|
1902
|
+
return [...store.users.values()].filter((u) => !u.is_bot && !u.deleted);
|
|
1903
|
+
}
|
|
1904
|
+
function composer(store, opts, channel, threadTs) {
|
|
1905
|
+
if (opts.screenshot)
|
|
1906
|
+
return "";
|
|
1907
|
+
const users = humanUsers(store);
|
|
1908
|
+
if (!users.length)
|
|
1909
|
+
return "";
|
|
1910
|
+
const options = users.map((u, i) => `<option value="${escapeHtml(u.id)}"${i === 0 ? " selected" : ""}>${escapeHtml(u.real_name || u.name)}</option>`).join("");
|
|
1911
|
+
const placeholder = threadTs ? "Reply in thread" : `Message ${channelLabel(store, channel)}`;
|
|
1912
|
+
const thread = threadTs ? ` data-thread="${escapeHtml(threadTs)}"` : "";
|
|
1913
|
+
return `<div class="sm-composer" data-channel="${escapeHtml(channel.id)}"${thread}><div class="sm-mentions"></div><div class="sm-composer-box"><textarea class="sm-composer-text" rows="2" placeholder="${escapeHtml(placeholder)}"></textarea><div class="sm-composer-row"><select class="sm-composer-user" aria-label="Post as">${options}</select><button type="button" class="sm-composer-send">Send</button></div></div><div class="sm-composer-hint">Enter to send, Shift+Enter for a new line, @name to mention</div></div>`;
|
|
1914
|
+
}
|
|
1915
|
+
function mentionData(store) {
|
|
1916
|
+
const users = [...store.users.values()].filter((u) => !u.deleted).map((u) => ({
|
|
1917
|
+
name: u.name,
|
|
1918
|
+
real: u.real_name || u.name,
|
|
1919
|
+
initials: initials(u.real_name || u.name),
|
|
1920
|
+
color: AVATAR_COLORS[hashIndex(u.id, AVATAR_COLORS.length)]
|
|
1921
|
+
}));
|
|
1922
|
+
const json = JSON.stringify(users).replace(/</g, "\\u003c");
|
|
1923
|
+
return `<script type="application/json" id="sm-users">${json}</script>`;
|
|
1924
|
+
}
|
|
1925
|
+
function uiScript(store, opts, closeUrl) {
|
|
1926
|
+
const esc = closeUrl ? `document.addEventListener("keydown",function(e){if(e.key==="Escape"&&!/^(TEXTAREA|INPUT|SELECT)$/.test(document.activeElement&&document.activeElement.tagName||""))location.href=${JSON.stringify(closeUrl)}});` : "";
|
|
1927
|
+
const body = `(function(){
|
|
1928
|
+
var W="sm-panel-w",DEF=${JSON.stringify(panelWidth(opts))},FIXED=${opts.panelWidth ? "true" : "false"};
|
|
1929
|
+
function scroll(){document.querySelectorAll(".sm-scroll").forEach(function(el){el.scrollTop=el.scrollHeight})}
|
|
1930
|
+
scroll();addEventListener("load",scroll);
|
|
1931
|
+
var handle=document.querySelector(".sm-resize");
|
|
1932
|
+
if(handle){
|
|
1933
|
+
var saved=null;try{saved=localStorage.getItem(W)}catch(e){}
|
|
1934
|
+
if(!FIXED&&saved)document.body.style.setProperty("--sm-panel-w",saved);
|
|
1935
|
+
var dragging=false;
|
|
1936
|
+
handle.addEventListener("mousedown",function(e){dragging=true;handle.classList.add("sm-dragging");e.preventDefault()});
|
|
1937
|
+
document.addEventListener("mousemove",function(e){if(!dragging)return;var w=Math.round(Math.min(Math.max(innerWidth-e.clientX,360),Math.max(innerWidth-320,360)));document.body.style.setProperty("--sm-panel-w",w+"px")});
|
|
1938
|
+
document.addEventListener("mouseup",function(){if(!dragging)return;dragging=false;handle.classList.remove("sm-dragging");try{localStorage.setItem(W,document.body.style.getPropertyValue("--sm-panel-w"))}catch(e){}});
|
|
1939
|
+
handle.addEventListener("dblclick",function(){try{localStorage.removeItem(W)}catch(e){}document.body.style.setProperty("--sm-panel-w",DEF)});
|
|
1940
|
+
}
|
|
1941
|
+
var raw=document.getElementById("sm-users");
|
|
1942
|
+
var PEOPLE=(raw?JSON.parse(raw.textContent||"[]"):[]).concat([{name:"here",real:"Notify everyone online",initials:"@",color:"#616061"},{name:"channel",real:"Notify everyone in the channel",initials:"@",color:"#616061"}]);
|
|
1943
|
+
function esc(s){return String(s).replace(/[&<>"]/g,function(c){return c==="&"?"&":c==="<"?"<":c===">"?">":"""})}
|
|
1944
|
+
function send(box){var t=box.querySelector(".sm-composer-text"),text=t.value.trim();if(!text)return;var body={channel:box.dataset.channel,user:box.querySelector(".sm-composer-user").value,text:text};if(box.dataset.thread)body.thread_ts=box.dataset.thread;t.disabled=true;fetch("/mock/messages",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(body)}).then(function(){location.reload()}).catch(function(){t.disabled=false})}
|
|
1945
|
+
document.querySelectorAll(".sm-composer").forEach(function(box){
|
|
1946
|
+
var ta=box.querySelector(".sm-composer-text"),menu=box.querySelector(".sm-mentions"),items=[],active=0;
|
|
1947
|
+
function close(){items=[];menu.style.display="none"}
|
|
1948
|
+
function prefix(){var m=/(?:^|\\s)@(\\w*)$/.exec(ta.value.slice(0,ta.selectionStart));return m?m[1]:null}
|
|
1949
|
+
function paint(){menu.querySelectorAll(".sm-mention").forEach(function(el,i){el.className="sm-mention"+(i===active?" sm-mention-on":"")})}
|
|
1950
|
+
function show(){
|
|
1951
|
+
var q=prefix();if(q===null)return close();
|
|
1952
|
+
var low=q.toLowerCase();
|
|
1953
|
+
var list=PEOPLE.filter(function(u){return !low||u.name.toLowerCase().indexOf(low)===0||u.real.toLowerCase().indexOf(low)===0}).slice(0,8);
|
|
1954
|
+
if(!list.length)return close();
|
|
1955
|
+
items=list;active=0;
|
|
1956
|
+
menu.innerHTML=list.map(function(u,i){return '<div class="sm-mention'+(i?"":" sm-mention-on")+'" data-i="'+i+'"><span class="sm-mention-av" style="background:'+esc(u.color)+'">'+esc(u.initials)+'</span><span class="sm-mention-name">@'+esc(u.name)+'</span><span class="sm-mention-real">'+esc(u.real)+'</span></div>'}).join("");
|
|
1957
|
+
menu.style.display="block";
|
|
1958
|
+
}
|
|
1959
|
+
function pick(i){var u=items[i];if(!u)return;var pos=ta.selectionStart,before=ta.value.slice(0,pos).replace(/@\\w*$/,"@"+u.name+" "),after=ta.value.slice(pos);ta.value=before+after;ta.selectionStart=ta.selectionEnd=before.length;close();ta.focus()}
|
|
1960
|
+
ta.addEventListener("input",show);
|
|
1961
|
+
ta.addEventListener("blur",function(){setTimeout(close,150)});
|
|
1962
|
+
menu.addEventListener("mousedown",function(e){var el=e.target.closest(".sm-mention");if(el){e.preventDefault();pick(Number(el.dataset.i))}});
|
|
1963
|
+
ta.addEventListener("keydown",function(e){
|
|
1964
|
+
if(items.length){
|
|
1965
|
+
if(e.key==="ArrowDown"){e.preventDefault();active=(active+1)%items.length;paint();return}
|
|
1966
|
+
if(e.key==="ArrowUp"){e.preventDefault();active=(active-1+items.length)%items.length;paint();return}
|
|
1967
|
+
if(e.key==="Enter"||e.key==="Tab"){e.preventDefault();pick(active);return}
|
|
1968
|
+
if(e.key==="Escape"){e.preventDefault();e.stopPropagation();close();return}
|
|
1969
|
+
}
|
|
1970
|
+
if(e.key==="Enter"&&!e.shiftKey){e.preventDefault();send(box)}
|
|
1971
|
+
});
|
|
1972
|
+
box.querySelector(".sm-composer-send").addEventListener("click",function(){send(box)});
|
|
1973
|
+
});
|
|
1974
|
+
})();`;
|
|
1975
|
+
return `${mentionData(store)}<script>${body}${esc}</script>`;
|
|
1976
|
+
}
|
|
1977
|
+
function channelView(store, opts, channelId) {
|
|
1978
|
+
const channel = store.channels.get(channelId);
|
|
1979
|
+
const ctx = ctxOf(store);
|
|
1980
|
+
if (!channel)
|
|
1981
|
+
return notFound(store, opts, "Channel not found");
|
|
1982
|
+
const label = channelLabel(store, channel);
|
|
1983
|
+
return shell(store, opts, {
|
|
1984
|
+
title: `${label} \xB7 slack-mock`,
|
|
1985
|
+
header: channelHeader(store, opts, channel),
|
|
1986
|
+
main: channelColumn(store, ctx, opts, channel),
|
|
1987
|
+
active: channel.id,
|
|
1988
|
+
footer: composer(store, opts, channel),
|
|
1989
|
+
script: opts.screenshot ? "" : uiScript(store, opts)
|
|
1990
|
+
});
|
|
1991
|
+
}
|
|
1992
|
+
function assistantPanel(store, channelId, ts) {
|
|
1993
|
+
const thread = store.assistantThreads.get(`${channelId}:${ts}`);
|
|
1994
|
+
if (!thread)
|
|
1995
|
+
return "";
|
|
1996
|
+
const parts = [];
|
|
1997
|
+
if (thread.title)
|
|
1998
|
+
parts.push(`<div class="sm-assist-title">${plainTextToHtml(thread.title)}</div>`);
|
|
1999
|
+
if (thread.status)
|
|
2000
|
+
parts.push(`<div class="sm-assist-status">${plainTextToHtml(thread.status)}<span class="sm-stream">\u2022\u2022\u2022</span></div>`);
|
|
2001
|
+
const prompts = Array.isArray(thread.prompts) ? thread.prompts : [];
|
|
2002
|
+
if (prompts.length) {
|
|
2003
|
+
const chips = prompts.map((p) => {
|
|
2004
|
+
const prompt = typeof p === "object" && p !== null ? p : {};
|
|
2005
|
+
const title = typeof prompt.title === "string" ? prompt.title : "";
|
|
2006
|
+
const message = typeof prompt.message === "string" ? prompt.message : "";
|
|
2007
|
+
return `<span class="sm-prompt" title="${escapeHtml(message)}">${plainTextToHtml(title || message)}</span>`;
|
|
2008
|
+
}).join("");
|
|
2009
|
+
const heading = thread.promptsTitle ? `<div class="sm-assist-status">${plainTextToHtml(thread.promptsTitle)}</div>` : "";
|
|
2010
|
+
parts.push(`${heading}<div class="sm-prompts">${chips}</div>`);
|
|
2011
|
+
}
|
|
2012
|
+
if (!parts.length)
|
|
2013
|
+
return "";
|
|
2014
|
+
return `<div class="sm-assist">${parts.join("")}</div>`;
|
|
2015
|
+
}
|
|
2016
|
+
function threadView(store, opts, channelId, ts) {
|
|
2017
|
+
const channel = store.channels.get(channelId);
|
|
2018
|
+
const ctx = ctxOf(store);
|
|
2019
|
+
if (!channel)
|
|
2020
|
+
return notFound(store, opts, "Channel not found");
|
|
2021
|
+
const parent = store.findMessage(channel.id, ts);
|
|
2022
|
+
if (!parent)
|
|
2023
|
+
return notFound(store, opts, "Message not found");
|
|
2024
|
+
const items = store.replies(channel.id, ts, { limit: 1000 }).items;
|
|
2025
|
+
const replies = items.slice(1);
|
|
2026
|
+
const label = channelLabel(store, channel);
|
|
2027
|
+
const repliesBar = replies.length ? `<div class="sm-daydiv"><span>${replies.length} ${replies.length === 1 ? "reply" : "replies"}</span></div>` : `<div class="sm-empty">No replies yet</div>`;
|
|
2028
|
+
const body = `${assistantPanel(store, channel.id, ts)}${renderMessage(store, ctx, parent, opts)}${repliesBar}${renderMessageList(store, ctx, replies, opts, { dividers: false })}`;
|
|
2029
|
+
if (opts.screenshot) {
|
|
2030
|
+
const header = topbar(`Thread <span class="sm-muted">\xB7</span> <a href="${channelHref(channel.id, opts)}">${escapeHtml(label)}</a>`, "");
|
|
2031
|
+
return shell(store, opts, {
|
|
2032
|
+
title: `Thread \xB7 ${label}`,
|
|
2033
|
+
header,
|
|
2034
|
+
main: body,
|
|
2035
|
+
active: channel.id
|
|
2036
|
+
});
|
|
2037
|
+
}
|
|
2038
|
+
const close = channelHref(channel.id, opts);
|
|
2039
|
+
const title = `Thread \xB7 ${label}`;
|
|
2040
|
+
if (opts.threadView === "full") {
|
|
2041
|
+
const header = topbar(`Thread <span class="sm-muted">\xB7</span> ${escapeHtml(label)}`, "", { href: close, label: `\u2190 ${label}` }, `<a class="sm-icon-btn" href="${threadHref(channel.id, ts, opts, { full: false })}" title="Collapse to panel" aria-label="Collapse to panel">\u2921</a>`);
|
|
2042
|
+
return shell(store, opts, {
|
|
2043
|
+
title,
|
|
2044
|
+
header,
|
|
2045
|
+
main: body,
|
|
2046
|
+
active: channel.id,
|
|
2047
|
+
footer: composer(store, opts, channel, ts),
|
|
2048
|
+
script: uiScript(store, opts, close)
|
|
2049
|
+
});
|
|
2050
|
+
}
|
|
2051
|
+
const expand = threadHref(channel.id, ts, opts, { full: true });
|
|
2052
|
+
const panel = `<aside class="sm-panel"><div class="sm-panel-top"><div class="sm-panel-heading"><h2 class="sm-panel-title">Thread</h2><div class="sm-panel-sub">${escapeHtml(label)}</div></div><a class="sm-panel-expand" href="${expand}" title="Expand thread">\u2922</a><a class="sm-panel-close" href="${close}" title="Close thread">\xD7</a></div><a class="sm-panel-back" href="${close}">\u2190 ${escapeHtml(label)}</a><div class="sm-panel-body sm-scroll">${body}</div>${composer(store, opts, channel, ts)}</aside>`;
|
|
2053
|
+
return shell(store, opts, {
|
|
2054
|
+
title,
|
|
2055
|
+
header: channelHeader(store, opts, channel),
|
|
2056
|
+
main: channelColumn(store, ctx, opts, channel, ts),
|
|
2057
|
+
active: channel.id,
|
|
2058
|
+
panel,
|
|
2059
|
+
footer: composer(store, opts, channel),
|
|
2060
|
+
script: uiScript(store, opts, close)
|
|
2061
|
+
});
|
|
2062
|
+
}
|
|
2063
|
+
function notFound(store, opts, message) {
|
|
2064
|
+
return shell(store, opts, {
|
|
2065
|
+
title: message,
|
|
2066
|
+
header: topbar(escapeHtml(message), ""),
|
|
2067
|
+
main: `<div class="sm-empty">${escapeHtml(message)}</div>`
|
|
2068
|
+
});
|
|
2069
|
+
}
|
|
2070
|
+
function renderPage(store, view, opts = {}) {
|
|
2071
|
+
switch (view.kind) {
|
|
2072
|
+
case "channel":
|
|
2073
|
+
return channelView(store, opts, view.channel);
|
|
2074
|
+
case "thread":
|
|
2075
|
+
return threadView(store, opts, view.channel, view.ts);
|
|
2076
|
+
default:
|
|
2077
|
+
return indexView(store, opts);
|
|
2078
|
+
}
|
|
2079
|
+
}
|
|
2080
|
+
|
|
2081
|
+
// src/socket-mode.ts
|
|
2082
|
+
class SocketModeClosedError extends Error {
|
|
2083
|
+
}
|
|
2084
|
+
function envelopeName(type, payload) {
|
|
2085
|
+
const p = payload;
|
|
2086
|
+
if (type === "events_api")
|
|
2087
|
+
return String(p.event?.type ?? "event");
|
|
2088
|
+
if (type === "slash_commands")
|
|
2089
|
+
return String(p.command ?? "command");
|
|
2090
|
+
return String(p.type ?? "interactive");
|
|
2091
|
+
}
|
|
2092
|
+
|
|
2093
|
+
class SocketModeHub {
|
|
2094
|
+
connections = new Map;
|
|
2095
|
+
pending = new Map;
|
|
2096
|
+
connectionWaiters = [];
|
|
2097
|
+
rr = 0;
|
|
2098
|
+
tickets = new Set;
|
|
2099
|
+
history = [];
|
|
2100
|
+
opts;
|
|
2101
|
+
constructor(opts) {
|
|
2102
|
+
this.opts = {
|
|
2103
|
+
appId: opts.appId,
|
|
2104
|
+
pingIntervalMs: opts.pingIntervalMs ?? 1e4,
|
|
2105
|
+
ackTimeoutMs: opts.ackTimeoutMs ?? 3000,
|
|
2106
|
+
maxRetries: opts.maxRetries ?? 3,
|
|
2107
|
+
log: opts.log ?? (() => {})
|
|
2108
|
+
};
|
|
2109
|
+
}
|
|
2110
|
+
get connectionCount() {
|
|
2111
|
+
return this.connections.size;
|
|
2112
|
+
}
|
|
2113
|
+
issueTicket() {
|
|
2114
|
+
const ticket = crypto.randomUUID().replace(/-/g, "");
|
|
2115
|
+
this.tickets.add(ticket);
|
|
2116
|
+
return ticket;
|
|
2117
|
+
}
|
|
2118
|
+
open(ws) {
|
|
2119
|
+
this.connections.set(ws.data.id, ws);
|
|
2120
|
+
this.opts.log(`socket ${ws.data.id} connected (${this.connections.size} total)`);
|
|
2121
|
+
ws.send(JSON.stringify({
|
|
2122
|
+
type: "hello",
|
|
2123
|
+
num_connections: this.connections.size,
|
|
2124
|
+
debug_info: {
|
|
2125
|
+
host: "slack-mock",
|
|
2126
|
+
build_number: 1,
|
|
2127
|
+
approximate_connection_time: 18060
|
|
2128
|
+
},
|
|
2129
|
+
connection_info: { app_id: this.opts.appId }
|
|
2130
|
+
}));
|
|
2131
|
+
ws.data.pingTimer = setInterval(() => {
|
|
2132
|
+
if (ws.readyState === 1)
|
|
2133
|
+
ws.ping();
|
|
2134
|
+
}, this.opts.pingIntervalMs);
|
|
2135
|
+
for (const w of this.connectionWaiters.splice(0))
|
|
2136
|
+
w();
|
|
2137
|
+
}
|
|
2138
|
+
message(ws, raw) {
|
|
2139
|
+
let msg;
|
|
2140
|
+
try {
|
|
2141
|
+
msg = JSON.parse(String(raw));
|
|
2142
|
+
} catch {
|
|
2143
|
+
this.opts.log(`socket ${ws.data.id} sent non-JSON frame`);
|
|
2144
|
+
return;
|
|
2145
|
+
}
|
|
2146
|
+
if (!msg.envelope_id)
|
|
2147
|
+
return;
|
|
2148
|
+
const p = this.pending.get(msg.envelope_id);
|
|
2149
|
+
if (!p) {
|
|
2150
|
+
this.opts.log(`ack for unknown/expired envelope ${msg.envelope_id}`);
|
|
2151
|
+
return;
|
|
2152
|
+
}
|
|
2153
|
+
clearTimeout(p.timer);
|
|
2154
|
+
this.pending.delete(msg.envelope_id);
|
|
2155
|
+
p.record.acked = true;
|
|
2156
|
+
p.record.ackPayload = msg.payload;
|
|
2157
|
+
p.resolve({ envelope_id: msg.envelope_id, payload: msg.payload, attempts: p.attempts });
|
|
2158
|
+
}
|
|
2159
|
+
close(ws) {
|
|
2160
|
+
clearInterval(ws.data.pingTimer);
|
|
2161
|
+
this.connections.delete(ws.data.id);
|
|
2162
|
+
this.opts.log(`socket ${ws.data.id} closed (${this.connections.size} left)`);
|
|
2163
|
+
}
|
|
2164
|
+
waitForConnection(timeoutMs = 1e4) {
|
|
2165
|
+
if (this.connections.size > 0)
|
|
2166
|
+
return Promise.resolve();
|
|
2167
|
+
return new Promise((resolve, reject) => {
|
|
2168
|
+
const timer = setTimeout(() => {
|
|
2169
|
+
this.connectionWaiters = this.connectionWaiters.filter((w) => w !== done);
|
|
2170
|
+
reject(new Error(`no Socket Mode connection after ${timeoutMs}ms`));
|
|
2171
|
+
}, timeoutMs);
|
|
2172
|
+
const done = () => {
|
|
2173
|
+
clearTimeout(timer);
|
|
2174
|
+
resolve();
|
|
2175
|
+
};
|
|
2176
|
+
this.connectionWaiters.push(done);
|
|
2177
|
+
});
|
|
2178
|
+
}
|
|
2179
|
+
send(type, payload, acceptsResponsePayload = false) {
|
|
2180
|
+
const envelope = {
|
|
2181
|
+
envelope_id: crypto.randomUUID(),
|
|
2182
|
+
type,
|
|
2183
|
+
accepts_response_payload: acceptsResponsePayload,
|
|
2184
|
+
retry_attempt: 0,
|
|
2185
|
+
retry_reason: "",
|
|
2186
|
+
payload
|
|
2187
|
+
};
|
|
2188
|
+
const record = {
|
|
2189
|
+
envelope_id: envelope.envelope_id,
|
|
2190
|
+
type,
|
|
2191
|
+
name: envelopeName(type, payload),
|
|
2192
|
+
sentAt: new Date().toISOString(),
|
|
2193
|
+
attempts: 0,
|
|
2194
|
+
acked: false
|
|
2195
|
+
};
|
|
2196
|
+
this.history.push(record);
|
|
2197
|
+
return new Promise((resolve, reject) => {
|
|
2198
|
+
const p = { envelope, record, resolve, reject, attempts: 0 };
|
|
2199
|
+
this.pending.set(envelope.envelope_id, p);
|
|
2200
|
+
this.attempt(p);
|
|
2201
|
+
});
|
|
2202
|
+
}
|
|
2203
|
+
attempt(p) {
|
|
2204
|
+
const ws = this.pickConnection();
|
|
2205
|
+
if (!ws) {
|
|
2206
|
+
this.pending.delete(p.envelope.envelope_id);
|
|
2207
|
+
p.reject(new SocketModeClosedError("no Socket Mode connection; is the app running?"));
|
|
2208
|
+
return;
|
|
2209
|
+
}
|
|
2210
|
+
p.attempts += 1;
|
|
2211
|
+
p.record.attempts = p.attempts;
|
|
2212
|
+
const wire = { ...p.envelope };
|
|
2213
|
+
if (p.attempts > 1) {
|
|
2214
|
+
wire.retry_attempt = p.attempts - 1;
|
|
2215
|
+
wire.retry_reason = "timeout";
|
|
2216
|
+
}
|
|
2217
|
+
ws.send(JSON.stringify(wire));
|
|
2218
|
+
p.timer = setTimeout(() => {
|
|
2219
|
+
if (p.attempts > this.opts.maxRetries) {
|
|
2220
|
+
this.pending.delete(p.envelope.envelope_id);
|
|
2221
|
+
p.reject(new Error(`envelope ${p.envelope.envelope_id} (${p.envelope.type}) not acked after ${p.attempts} attempts`));
|
|
2222
|
+
return;
|
|
2223
|
+
}
|
|
2224
|
+
this.opts.log(`no ack for ${p.envelope.envelope_id}; redelivering (attempt ${p.attempts + 1})`);
|
|
2225
|
+
this.attempt(p);
|
|
2226
|
+
}, this.opts.ackTimeoutMs);
|
|
2227
|
+
}
|
|
2228
|
+
pickConnection() {
|
|
2229
|
+
const list = [...this.connections.values()];
|
|
2230
|
+
if (list.length === 0)
|
|
2231
|
+
return;
|
|
2232
|
+
this.rr = (this.rr + 1) % list.length;
|
|
2233
|
+
return list[this.rr];
|
|
2234
|
+
}
|
|
2235
|
+
disconnectAll(reason = "refresh_requested", graceMs = 200) {
|
|
2236
|
+
for (const ws of this.connections.values()) {
|
|
2237
|
+
ws.send(JSON.stringify({ type: "disconnect", reason, debug_info: { host: "slack-mock" } }));
|
|
2238
|
+
setTimeout(() => ws.close(1000, reason), graceMs);
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
shutdown() {
|
|
2242
|
+
for (const p of this.pending.values()) {
|
|
2243
|
+
clearTimeout(p.timer);
|
|
2244
|
+
p.reject(new SocketModeClosedError("mock stopped"));
|
|
2245
|
+
}
|
|
2246
|
+
this.pending.clear();
|
|
2247
|
+
for (const ws of this.connections.values()) {
|
|
2248
|
+
clearInterval(ws.data.pingTimer);
|
|
2249
|
+
ws.close(1001, "server shutting down");
|
|
2250
|
+
}
|
|
2251
|
+
this.connections.clear();
|
|
2252
|
+
}
|
|
2253
|
+
}
|
|
2254
|
+
|
|
2255
|
+
// src/web-api.ts
|
|
2256
|
+
function required(args, key) {
|
|
2257
|
+
const v = str(args, key);
|
|
2258
|
+
if (!v)
|
|
2259
|
+
throw new SlackApiError("invalid_arguments", {
|
|
2260
|
+
response_metadata: { messages: [`[ERROR] missing required field: ${key}`] }
|
|
2261
|
+
});
|
|
2262
|
+
return v;
|
|
2263
|
+
}
|
|
2264
|
+
function resolveChannel(store, raw) {
|
|
2265
|
+
if (raw.startsWith("#")) {
|
|
2266
|
+
const c = store.channelByName(raw);
|
|
2267
|
+
if (!c)
|
|
2268
|
+
throw new SlackApiError("channel_not_found");
|
|
2269
|
+
return c;
|
|
2270
|
+
}
|
|
2271
|
+
if (raw.startsWith("U") || raw.startsWith("W"))
|
|
2272
|
+
return store.openDm(raw);
|
|
2273
|
+
return store.channel(raw);
|
|
2274
|
+
}
|
|
2275
|
+
function requireMember(channel, actor) {
|
|
2276
|
+
if (!channel.members.includes(actor.userId))
|
|
2277
|
+
throw new SlackApiError("not_in_channel");
|
|
2278
|
+
}
|
|
2279
|
+
function botFields(ctx) {
|
|
2280
|
+
if (!ctx.actor.isBot)
|
|
2281
|
+
return {};
|
|
2282
|
+
return {
|
|
2283
|
+
bot_id: ctx.store.bot.botId,
|
|
2284
|
+
app_id: ctx.store.app.id,
|
|
2285
|
+
bot_profile: {
|
|
2286
|
+
id: ctx.store.bot.botId,
|
|
2287
|
+
name: ctx.store.app.name,
|
|
2288
|
+
app_id: ctx.store.app.id,
|
|
2289
|
+
team_id: ctx.store.team.id,
|
|
2290
|
+
deleted: false
|
|
2291
|
+
}
|
|
2292
|
+
};
|
|
2293
|
+
}
|
|
2294
|
+
function messageContent(args) {
|
|
2295
|
+
const text = str(args, "text") ?? "";
|
|
2296
|
+
const blocks = Array.isArray(args.blocks) ? args.blocks : undefined;
|
|
2297
|
+
const attachments = Array.isArray(args.attachments) ? args.attachments : undefined;
|
|
2298
|
+
if (!text && !blocks?.length && !attachments?.length)
|
|
2299
|
+
throw new SlackApiError("no_text");
|
|
2300
|
+
if (blocks && blocks.length > 50)
|
|
2301
|
+
throw new SlackApiError("invalid_blocks", {
|
|
2302
|
+
response_metadata: { messages: ["[ERROR] must have at most 50 blocks"] }
|
|
2303
|
+
});
|
|
2304
|
+
const metadata = args.metadata && typeof args.metadata === "object" ? args.metadata : undefined;
|
|
2305
|
+
return { text, blocks, attachments, metadata };
|
|
2306
|
+
}
|
|
2307
|
+
function channelInfo(store, c, actor) {
|
|
2308
|
+
const { members, ...rest } = c;
|
|
2309
|
+
return {
|
|
2310
|
+
...rest,
|
|
2311
|
+
is_member: members.includes(actor.userId),
|
|
2312
|
+
num_members: members.length,
|
|
2313
|
+
context_team_id: store.team.id,
|
|
2314
|
+
shared_team_ids: [store.team.id],
|
|
2315
|
+
is_org_shared: false,
|
|
2316
|
+
is_shared: false,
|
|
2317
|
+
is_ext_shared: false,
|
|
2318
|
+
is_pending_ext_shared: false,
|
|
2319
|
+
unlinked: 0,
|
|
2320
|
+
name_normalized: c.name,
|
|
2321
|
+
updated: c.created * 1000
|
|
2322
|
+
};
|
|
2323
|
+
}
|
|
2324
|
+
var handlers = {
|
|
2325
|
+
"auth.test": ({ store, actor }) => {
|
|
2326
|
+
const user = store.user(actor.userId);
|
|
2327
|
+
return {
|
|
2328
|
+
url: `https://${store.team.domain}.slack.com/`,
|
|
2329
|
+
team: store.team.name,
|
|
2330
|
+
user: user.name,
|
|
2331
|
+
team_id: store.team.id,
|
|
2332
|
+
user_id: user.id,
|
|
2333
|
+
...actor.isBot ? { bot_id: store.bot.botId } : {},
|
|
2334
|
+
is_enterprise_install: false
|
|
2335
|
+
};
|
|
2336
|
+
},
|
|
2337
|
+
"apps.connections.open": ({ hub, wsUrl, store }) => ({
|
|
2338
|
+
url: `${wsUrl}/link/?ticket=${hub.issueTicket()}&app_id=${store.app.id}`
|
|
2339
|
+
}),
|
|
2340
|
+
"bots.info": ({ store }) => ({
|
|
2341
|
+
bot: {
|
|
2342
|
+
id: store.bot.botId,
|
|
2343
|
+
deleted: false,
|
|
2344
|
+
name: store.app.name,
|
|
2345
|
+
updated: nowUnix(),
|
|
2346
|
+
app_id: store.app.id,
|
|
2347
|
+
user_id: store.bot.userId,
|
|
2348
|
+
icons: {}
|
|
2349
|
+
}
|
|
2350
|
+
}),
|
|
2351
|
+
"team.info": ({ store }) => ({
|
|
2352
|
+
team: {
|
|
2353
|
+
id: store.team.id,
|
|
2354
|
+
name: store.team.name,
|
|
2355
|
+
domain: store.team.domain,
|
|
2356
|
+
email_domain: "",
|
|
2357
|
+
icon: {},
|
|
2358
|
+
is_verified: false
|
|
2359
|
+
}
|
|
2360
|
+
}),
|
|
2361
|
+
"chat.postMessage": (ctx, args) => {
|
|
2362
|
+
const channel = resolveChannel(ctx.store, required(args, "channel"));
|
|
2363
|
+
requireMember(channel, ctx.actor);
|
|
2364
|
+
const threadTs = str(args, "thread_ts");
|
|
2365
|
+
const message = ctx.store.addMessage({
|
|
2366
|
+
channel: channel.id,
|
|
2367
|
+
user: ctx.actor.userId,
|
|
2368
|
+
...messageContent(args),
|
|
2369
|
+
...threadTs ? { thread_ts: threadTs } : {},
|
|
2370
|
+
...bool(args, "reply_broadcast") && threadTs ? { subtype: "thread_broadcast" } : {},
|
|
2371
|
+
...str(args, "username") ? { username: str(args, "username") } : {},
|
|
2372
|
+
...str(args, "icon_emoji") || str(args, "icon_url") ? {
|
|
2373
|
+
icons: {
|
|
2374
|
+
...str(args, "icon_emoji") ? { emoji: str(args, "icon_emoji") } : {},
|
|
2375
|
+
...str(args, "icon_url") ? { image_64: str(args, "icon_url") } : {}
|
|
2376
|
+
}
|
|
2377
|
+
} : {},
|
|
2378
|
+
...botFields(ctx)
|
|
2379
|
+
});
|
|
2380
|
+
return { channel: channel.id, ts: message.ts, message: wireMessage(message) };
|
|
2381
|
+
},
|
|
2382
|
+
"chat.postEphemeral": (ctx, args) => {
|
|
2383
|
+
const channel = resolveChannel(ctx.store, required(args, "channel"));
|
|
2384
|
+
const user = required(args, "user");
|
|
2385
|
+
ctx.store.user(user);
|
|
2386
|
+
const threadTs = str(args, "thread_ts");
|
|
2387
|
+
const message = ctx.store.addMessage({
|
|
2388
|
+
channel: channel.id,
|
|
2389
|
+
user: ctx.actor.userId,
|
|
2390
|
+
ephemeral_user: user,
|
|
2391
|
+
...messageContent(args),
|
|
2392
|
+
...threadTs ? { thread_ts: threadTs } : {},
|
|
2393
|
+
...botFields(ctx)
|
|
2394
|
+
});
|
|
2395
|
+
return { message_ts: message.ts };
|
|
2396
|
+
},
|
|
2397
|
+
"chat.update": (ctx, args) => {
|
|
2398
|
+
const channel = resolveChannel(ctx.store, required(args, "channel"));
|
|
2399
|
+
const ts = required(args, "ts");
|
|
2400
|
+
const existing = ctx.store.message(channel.id, ts);
|
|
2401
|
+
if (existing.user !== ctx.actor.userId && !ctx.actor.isBot)
|
|
2402
|
+
throw new SlackApiError("cant_update_message");
|
|
2403
|
+
const patch = {};
|
|
2404
|
+
if (args.text !== undefined)
|
|
2405
|
+
patch.text = str(args, "text") ?? "";
|
|
2406
|
+
if (args.blocks !== undefined)
|
|
2407
|
+
patch.blocks = Array.isArray(args.blocks) ? args.blocks : undefined;
|
|
2408
|
+
if (args.attachments !== undefined)
|
|
2409
|
+
patch.attachments = Array.isArray(args.attachments) ? args.attachments : undefined;
|
|
2410
|
+
if (args.metadata !== undefined)
|
|
2411
|
+
patch.metadata = args.metadata;
|
|
2412
|
+
if (patch.text === "" && !patch.blocks?.length && !patch.attachments?.length && !existing.blocks?.length)
|
|
2413
|
+
throw new SlackApiError("no_text");
|
|
2414
|
+
const message = ctx.store.updateMessage(channel.id, ts, patch, ctx.actor.userId);
|
|
2415
|
+
return { channel: channel.id, ts, text: message.text, message: wireMessage(message) };
|
|
2416
|
+
},
|
|
2417
|
+
"chat.delete": (ctx, args) => {
|
|
2418
|
+
const channel = resolveChannel(ctx.store, required(args, "channel"));
|
|
2419
|
+
const ts = required(args, "ts");
|
|
2420
|
+
ctx.store.deleteMessage(channel.id, ts);
|
|
2421
|
+
return { channel: channel.id, ts };
|
|
2422
|
+
},
|
|
2423
|
+
"chat.startStream": (ctx, args) => {
|
|
2424
|
+
const channel = resolveChannel(ctx.store, required(args, "channel"));
|
|
2425
|
+
requireMember(channel, ctx.actor);
|
|
2426
|
+
const threadTs = str(args, "thread_ts");
|
|
2427
|
+
const message = ctx.store.addMessage({
|
|
2428
|
+
channel: channel.id,
|
|
2429
|
+
user: ctx.actor.userId,
|
|
2430
|
+
text: streamText(args),
|
|
2431
|
+
streaming_state: "in_progress",
|
|
2432
|
+
...threadTs ? { thread_ts: threadTs } : {},
|
|
2433
|
+
...str(args, "username") ? { username: str(args, "username") } : {},
|
|
2434
|
+
...str(args, "icon_emoji") ? { icons: { emoji: str(args, "icon_emoji") } } : {},
|
|
2435
|
+
...botFields(ctx)
|
|
2436
|
+
});
|
|
2437
|
+
return { channel: channel.id, ts: message.ts };
|
|
2438
|
+
},
|
|
2439
|
+
"chat.appendStream": (ctx, args) => {
|
|
2440
|
+
const channel = resolveChannel(ctx.store, required(args, "channel"));
|
|
2441
|
+
const ts = required(args, "ts");
|
|
2442
|
+
const existing = ctx.store.message(channel.id, ts);
|
|
2443
|
+
if (existing.streaming_state !== "in_progress")
|
|
2444
|
+
throw new SlackApiError("message_not_in_streaming_state");
|
|
2445
|
+
const message = ctx.store.updateMessage(channel.id, ts, { text: existing.text + streamText(args) }, ctx.actor.userId);
|
|
2446
|
+
return { channel: channel.id, ts: message.ts };
|
|
2447
|
+
},
|
|
2448
|
+
"chat.stopStream": (ctx, args) => {
|
|
2449
|
+
const channel = resolveChannel(ctx.store, required(args, "channel"));
|
|
2450
|
+
const ts = required(args, "ts");
|
|
2451
|
+
const existing = ctx.store.message(channel.id, ts);
|
|
2452
|
+
if (existing.streaming_state !== "in_progress")
|
|
2453
|
+
throw new SlackApiError("message_not_in_streaming_state");
|
|
2454
|
+
const patch = {
|
|
2455
|
+
streaming_state: "completed",
|
|
2456
|
+
text: existing.text + streamText(args)
|
|
2457
|
+
};
|
|
2458
|
+
if (Array.isArray(args.blocks))
|
|
2459
|
+
patch.blocks = args.blocks;
|
|
2460
|
+
const message = ctx.store.updateMessage(channel.id, ts, patch, ctx.actor.userId);
|
|
2461
|
+
return { channel: channel.id, ts, message: wireMessage(message) };
|
|
2462
|
+
},
|
|
2463
|
+
"chat.getPermalink": (ctx, args) => {
|
|
2464
|
+
const channel = resolveChannel(ctx.store, required(args, "channel"));
|
|
2465
|
+
const ts = required(args, "message_ts");
|
|
2466
|
+
ctx.store.message(channel.id, ts);
|
|
2467
|
+
return {
|
|
2468
|
+
channel: channel.id,
|
|
2469
|
+
permalink: `${ctx.baseUrl}/archives/${channel.id}/p${ts.replace(".", "")}`
|
|
2470
|
+
};
|
|
2471
|
+
},
|
|
2472
|
+
"conversations.list": (ctx, args) => {
|
|
2473
|
+
const types = new Set((str(args, "types") ?? "public_channel").split(",").map((t) => t.trim()));
|
|
2474
|
+
const excludeArchived = bool(args, "exclude_archived") ?? false;
|
|
2475
|
+
const all = [...ctx.store.channels.values()].filter((c) => {
|
|
2476
|
+
if (excludeArchived && c.is_archived)
|
|
2477
|
+
return false;
|
|
2478
|
+
if (c.is_im)
|
|
2479
|
+
return types.has("im");
|
|
2480
|
+
if (c.is_mpim)
|
|
2481
|
+
return types.has("mpim");
|
|
2482
|
+
if (c.is_private)
|
|
2483
|
+
return types.has("private_channel");
|
|
2484
|
+
return types.has("public_channel");
|
|
2485
|
+
});
|
|
2486
|
+
const limit = num(args, "limit", 100);
|
|
2487
|
+
const start = cursorOffset(str(args, "cursor"));
|
|
2488
|
+
const slice = all.slice(start, start + limit);
|
|
2489
|
+
const hasMore = start + limit < all.length;
|
|
2490
|
+
return {
|
|
2491
|
+
channels: slice.map((c) => channelInfo(ctx.store, c, ctx.actor)),
|
|
2492
|
+
response_metadata: { next_cursor: hasMore ? cursorFor(start + limit) : "" }
|
|
2493
|
+
};
|
|
2494
|
+
},
|
|
2495
|
+
"conversations.info": (ctx, args) => {
|
|
2496
|
+
const channel = ctx.store.channel(required(args, "channel"));
|
|
2497
|
+
return { channel: channelInfo(ctx.store, channel, ctx.actor) };
|
|
2498
|
+
},
|
|
2499
|
+
"conversations.create": (ctx, args) => {
|
|
2500
|
+
const name = required(args, "name");
|
|
2501
|
+
if (!/^[a-z0-9_-]{1,80}$/.test(name))
|
|
2502
|
+
throw new SlackApiError("invalid_name_specials");
|
|
2503
|
+
const channel = ctx.store.addChannel({
|
|
2504
|
+
name,
|
|
2505
|
+
is_private: bool(args, "is_private") ?? false,
|
|
2506
|
+
creator: ctx.actor.userId
|
|
2507
|
+
});
|
|
2508
|
+
return { channel: channelInfo(ctx.store, channel, ctx.actor) };
|
|
2509
|
+
},
|
|
2510
|
+
"conversations.join": (ctx, args) => {
|
|
2511
|
+
const channel = ctx.store.channel(required(args, "channel"));
|
|
2512
|
+
if (channel.is_private)
|
|
2513
|
+
throw new SlackApiError("method_not_supported_for_channel_type");
|
|
2514
|
+
const { alreadyMember } = ctx.store.join(channel.id, ctx.actor.userId);
|
|
2515
|
+
return {
|
|
2516
|
+
channel: channelInfo(ctx.store, channel, ctx.actor),
|
|
2517
|
+
...alreadyMember ? { warning: "already_in_channel", response_metadata: { warnings: ["already_in_channel"] } } : {}
|
|
2518
|
+
};
|
|
2519
|
+
},
|
|
2520
|
+
"conversations.invite": (ctx, args) => {
|
|
2521
|
+
const channel = ctx.store.channel(required(args, "channel"));
|
|
2522
|
+
const users = required(args, "users").split(",").map((u) => u.trim()).filter(Boolean);
|
|
2523
|
+
const errors = [];
|
|
2524
|
+
for (const u of users) {
|
|
2525
|
+
if (!ctx.store.users.has(u)) {
|
|
2526
|
+
errors.push({ user: u, ok: false, error: "user_not_found" });
|
|
2527
|
+
continue;
|
|
2528
|
+
}
|
|
2529
|
+
const { alreadyMember } = ctx.store.join(channel.id, u, ctx.actor.userId);
|
|
2530
|
+
if (alreadyMember)
|
|
2531
|
+
errors.push({ user: u, ok: false, error: "already_in_channel" });
|
|
2532
|
+
}
|
|
2533
|
+
if (errors.length === users.length)
|
|
2534
|
+
throw new SlackApiError(String(errors[0].error), { errors });
|
|
2535
|
+
return {
|
|
2536
|
+
channel: channelInfo(ctx.store, channel, ctx.actor),
|
|
2537
|
+
...errors.length ? { errors } : {}
|
|
2538
|
+
};
|
|
2539
|
+
},
|
|
2540
|
+
"conversations.archive": (ctx, args) => {
|
|
2541
|
+
ctx.store.archive(required(args, "channel"));
|
|
2542
|
+
return {};
|
|
2543
|
+
},
|
|
2544
|
+
"conversations.members": (ctx, args) => {
|
|
2545
|
+
const channel = ctx.store.channel(required(args, "channel"));
|
|
2546
|
+
return { members: channel.members, response_metadata: { next_cursor: "" } };
|
|
2547
|
+
},
|
|
2548
|
+
"conversations.open": (ctx, args) => {
|
|
2549
|
+
const users = (str(args, "users") ?? "").split(",").map((u) => u.trim()).filter(Boolean);
|
|
2550
|
+
if (users.length !== 1)
|
|
2551
|
+
throw new SlackApiError("users_list_not_supplied");
|
|
2552
|
+
const dm = ctx.store.openDm(users[0]);
|
|
2553
|
+
return { channel: { id: dm.id, is_im: true, user: dm.user, created: dm.created } };
|
|
2554
|
+
},
|
|
2555
|
+
"conversations.history": (ctx, args) => {
|
|
2556
|
+
const channel = ctx.store.channel(required(args, "channel"));
|
|
2557
|
+
requireMember(channel, ctx.actor);
|
|
2558
|
+
const p = ctx.store.history(channel.id, {
|
|
2559
|
+
oldest: str(args, "oldest"),
|
|
2560
|
+
latest: str(args, "latest"),
|
|
2561
|
+
inclusive: bool(args, "inclusive"),
|
|
2562
|
+
limit: num(args, "limit", 100),
|
|
2563
|
+
cursor: str(args, "cursor")
|
|
2564
|
+
});
|
|
2565
|
+
return {
|
|
2566
|
+
messages: p.items.map((m) => historyMessage(m, bool(args, "include_all_metadata"))),
|
|
2567
|
+
has_more: p.has_more,
|
|
2568
|
+
pin_count: 0,
|
|
2569
|
+
response_metadata: { next_cursor: p.next_cursor }
|
|
2570
|
+
};
|
|
2571
|
+
},
|
|
2572
|
+
"conversations.replies": (ctx, args) => {
|
|
2573
|
+
const channel = ctx.store.channel(required(args, "channel"));
|
|
2574
|
+
requireMember(channel, ctx.actor);
|
|
2575
|
+
const ts = required(args, "ts");
|
|
2576
|
+
if (!ctx.store.findMessage(channel.id, ts))
|
|
2577
|
+
throw new SlackApiError("thread_not_found");
|
|
2578
|
+
const p = ctx.store.replies(channel.id, ts, {
|
|
2579
|
+
oldest: str(args, "oldest"),
|
|
2580
|
+
latest: str(args, "latest"),
|
|
2581
|
+
inclusive: bool(args, "inclusive"),
|
|
2582
|
+
limit: num(args, "limit", 1000),
|
|
2583
|
+
cursor: str(args, "cursor")
|
|
2584
|
+
});
|
|
2585
|
+
return {
|
|
2586
|
+
messages: p.items.map((m) => historyMessage(m, bool(args, "include_all_metadata"))),
|
|
2587
|
+
has_more: p.has_more,
|
|
2588
|
+
response_metadata: { next_cursor: p.next_cursor }
|
|
2589
|
+
};
|
|
2590
|
+
},
|
|
2591
|
+
"users.info": (ctx, args) => ({ user: ctx.store.user(required(args, "user")) }),
|
|
2592
|
+
"users.list": (ctx) => ({
|
|
2593
|
+
members: [...ctx.store.users.values()],
|
|
2594
|
+
response_metadata: { next_cursor: "" }
|
|
2595
|
+
}),
|
|
2596
|
+
"users.lookupByEmail": (ctx, args) => {
|
|
2597
|
+
const user = ctx.store.userByEmail(required(args, "email"));
|
|
2598
|
+
if (!user)
|
|
2599
|
+
throw new SlackApiError("users_not_found");
|
|
2600
|
+
return { user };
|
|
2601
|
+
},
|
|
2602
|
+
"users.conversations": (ctx, args) => {
|
|
2603
|
+
const user = str(args, "user") ?? ctx.actor.userId;
|
|
2604
|
+
const channels = [...ctx.store.channels.values()].filter((c) => c.members.includes(user) && !c.is_im);
|
|
2605
|
+
return {
|
|
2606
|
+
channels: channels.map((c) => channelInfo(ctx.store, c, ctx.actor)),
|
|
2607
|
+
response_metadata: { next_cursor: "" }
|
|
2608
|
+
};
|
|
2609
|
+
},
|
|
2610
|
+
"reactions.add": (ctx, args) => {
|
|
2611
|
+
const channel = ctx.store.channel(required(args, "channel"));
|
|
2612
|
+
ctx.store.addReaction(channel.id, required(args, "timestamp"), required(args, "name"), ctx.actor.userId);
|
|
2613
|
+
return {};
|
|
2614
|
+
},
|
|
2615
|
+
"reactions.remove": (ctx, args) => {
|
|
2616
|
+
const channel = ctx.store.channel(required(args, "channel"));
|
|
2617
|
+
ctx.store.removeReaction(channel.id, required(args, "timestamp"), required(args, "name"), ctx.actor.userId);
|
|
2618
|
+
return {};
|
|
2619
|
+
},
|
|
2620
|
+
"reactions.get": (ctx, args) => {
|
|
2621
|
+
const channel = ctx.store.channel(required(args, "channel"));
|
|
2622
|
+
const message = ctx.store.message(channel.id, required(args, "timestamp"));
|
|
2623
|
+
return { type: "message", channel: channel.id, message: wireMessage(message) };
|
|
2624
|
+
},
|
|
2625
|
+
"files.info": (ctx, args) => {
|
|
2626
|
+
const file = ctx.store.file(required(args, "file"));
|
|
2627
|
+
return { file: wireFile(file), comments: [], response_metadata: { next_cursor: "" } };
|
|
2628
|
+
},
|
|
2629
|
+
"files.getUploadURLExternal": (ctx, args) => {
|
|
2630
|
+
const filename = required(args, "filename");
|
|
2631
|
+
const length = num(args, "length", -1);
|
|
2632
|
+
if (length < 0)
|
|
2633
|
+
throw new SlackApiError("invalid_arguments", {
|
|
2634
|
+
response_metadata: { messages: ["[ERROR] missing required field: length"] }
|
|
2635
|
+
});
|
|
2636
|
+
const id = slackId("F");
|
|
2637
|
+
ctx.pendingUploads.set(id, {
|
|
2638
|
+
name: filename,
|
|
2639
|
+
length,
|
|
2640
|
+
alt_text: str(args, "alt_text"),
|
|
2641
|
+
user: ctx.actor.userId
|
|
2642
|
+
});
|
|
2643
|
+
return { upload_url: `${ctx.baseUrl}/upload/v1/${id}`, file_id: id };
|
|
2644
|
+
},
|
|
2645
|
+
"files.completeUploadExternal": (ctx, args) => {
|
|
2646
|
+
const list = Array.isArray(args.files) ? args.files : [];
|
|
2647
|
+
if (list.length === 0)
|
|
2648
|
+
throw new SlackApiError("invalid_arguments", {
|
|
2649
|
+
response_metadata: { messages: ["[ERROR] missing required field: files"] }
|
|
2650
|
+
});
|
|
2651
|
+
const files = list.map(({ id, title }) => {
|
|
2652
|
+
const f = ctx.store.file(id);
|
|
2653
|
+
if (title)
|
|
2654
|
+
f.title = title;
|
|
2655
|
+
return f;
|
|
2656
|
+
});
|
|
2657
|
+
const channelId = str(args, "channel_id");
|
|
2658
|
+
if (channelId) {
|
|
2659
|
+
const channel = ctx.store.channel(channelId);
|
|
2660
|
+
requireMember(channel, ctx.actor);
|
|
2661
|
+
for (const f of files)
|
|
2662
|
+
if (!f.channels.includes(channel.id))
|
|
2663
|
+
f.channels.push(channel.id);
|
|
2664
|
+
const threadTs = str(args, "thread_ts");
|
|
2665
|
+
ctx.store.addMessage({
|
|
2666
|
+
channel: channel.id,
|
|
2667
|
+
user: ctx.actor.userId,
|
|
2668
|
+
subtype: "file_share",
|
|
2669
|
+
text: str(args, "initial_comment") ?? "",
|
|
2670
|
+
files,
|
|
2671
|
+
...threadTs ? { thread_ts: threadTs } : {},
|
|
2672
|
+
...botFields(ctx)
|
|
2673
|
+
});
|
|
2674
|
+
}
|
|
2675
|
+
return { files: files.map(wireFile) };
|
|
2676
|
+
},
|
|
2677
|
+
"files.delete": (ctx, args) => {
|
|
2678
|
+
ctx.store.file(required(args, "file"));
|
|
2679
|
+
ctx.store.files.delete(required(args, "file"));
|
|
2680
|
+
return {};
|
|
2681
|
+
},
|
|
2682
|
+
"views.open": (ctx, args) => {
|
|
2683
|
+
const triggerId = required(args, "trigger_id");
|
|
2684
|
+
const expires = ctx.triggerIds.get(triggerId);
|
|
2685
|
+
if (expires === undefined)
|
|
2686
|
+
throw new SlackApiError("invalid_trigger_id");
|
|
2687
|
+
ctx.triggerIds.delete(triggerId);
|
|
2688
|
+
if (Date.now() > expires)
|
|
2689
|
+
throw new SlackApiError("expired_trigger_id");
|
|
2690
|
+
const view = viewArg(args);
|
|
2691
|
+
if (view.type !== "modal")
|
|
2692
|
+
throw new SlackApiError("invalid_arguments", {
|
|
2693
|
+
response_metadata: { messages: ["[ERROR] view type must be modal"] }
|
|
2694
|
+
});
|
|
2695
|
+
const stored = ctx.store.openView({
|
|
2696
|
+
type: "modal",
|
|
2697
|
+
callback_id: str(view, "callback_id"),
|
|
2698
|
+
private_metadata: str(view, "private_metadata") ?? "",
|
|
2699
|
+
title: view.title,
|
|
2700
|
+
submit: view.submit,
|
|
2701
|
+
close: view.close,
|
|
2702
|
+
blocks: Array.isArray(view.blocks) ? view.blocks : [],
|
|
2703
|
+
external_id: str(view, "external_id"),
|
|
2704
|
+
opened_by: "",
|
|
2705
|
+
trigger_id: triggerId,
|
|
2706
|
+
state: { values: {} },
|
|
2707
|
+
clear_on_close: bool(view, "clear_on_close") ?? false,
|
|
2708
|
+
notify_on_close: bool(view, "notify_on_close") ?? false
|
|
2709
|
+
});
|
|
2710
|
+
return { view: publicView(stored) };
|
|
2711
|
+
},
|
|
2712
|
+
"views.update": (ctx, args) => {
|
|
2713
|
+
const id = required(args, "view_id");
|
|
2714
|
+
const existing = ctx.store.views.get(id);
|
|
2715
|
+
if (!existing)
|
|
2716
|
+
throw new SlackApiError("not_found");
|
|
2717
|
+
const view = viewArg(args);
|
|
2718
|
+
Object.assign(existing, {
|
|
2719
|
+
callback_id: str(view, "callback_id") ?? existing.callback_id,
|
|
2720
|
+
private_metadata: str(view, "private_metadata") ?? existing.private_metadata,
|
|
2721
|
+
title: view.title ?? existing.title,
|
|
2722
|
+
submit: view.submit ?? existing.submit,
|
|
2723
|
+
close: view.close ?? existing.close,
|
|
2724
|
+
blocks: Array.isArray(view.blocks) ? view.blocks : existing.blocks,
|
|
2725
|
+
hash: `${nowUnix()}.${slackId("", 6).toLowerCase()}`
|
|
2726
|
+
});
|
|
2727
|
+
ctx.store.onChangeEmit({ kind: "view.update", view: existing });
|
|
2728
|
+
return { view: publicView(existing) };
|
|
2729
|
+
},
|
|
2730
|
+
"views.push": (ctx, args) => handlers["views.open"](ctx, args),
|
|
2731
|
+
"assistant.threads.setStatus": (ctx, args) => {
|
|
2732
|
+
const channel = ctx.store.channel(required(args, "channel_id"));
|
|
2733
|
+
const threadTs = required(args, "thread_ts");
|
|
2734
|
+
const t = ctx.store.assistantThread(channel.id, threadTs);
|
|
2735
|
+
t.status = str(args, "status") ?? "";
|
|
2736
|
+
ctx.store.onChangeEmit({
|
|
2737
|
+
kind: "assistant.status",
|
|
2738
|
+
channel: channel.id,
|
|
2739
|
+
thread_ts: threadTs,
|
|
2740
|
+
status: t.status
|
|
2741
|
+
});
|
|
2742
|
+
return {};
|
|
2743
|
+
},
|
|
2744
|
+
"assistant.threads.setTitle": (ctx, args) => {
|
|
2745
|
+
const channel = ctx.store.channel(required(args, "channel_id"));
|
|
2746
|
+
const threadTs = required(args, "thread_ts");
|
|
2747
|
+
const t = ctx.store.assistantThread(channel.id, threadTs);
|
|
2748
|
+
t.title = required(args, "title");
|
|
2749
|
+
ctx.store.onChangeEmit({
|
|
2750
|
+
kind: "assistant.title",
|
|
2751
|
+
channel: channel.id,
|
|
2752
|
+
thread_ts: threadTs,
|
|
2753
|
+
title: t.title
|
|
2754
|
+
});
|
|
2755
|
+
return {};
|
|
2756
|
+
},
|
|
2757
|
+
"assistant.threads.setSuggestedPrompts": (ctx, args) => {
|
|
2758
|
+
const channel = ctx.store.channel(required(args, "channel_id"));
|
|
2759
|
+
const threadTs = required(args, "thread_ts");
|
|
2760
|
+
const t = ctx.store.assistantThread(channel.id, threadTs);
|
|
2761
|
+
t.prompts = Array.isArray(args.prompts) ? args.prompts : [];
|
|
2762
|
+
t.promptsTitle = str(args, "title");
|
|
2763
|
+
ctx.store.onChangeEmit({
|
|
2764
|
+
kind: "assistant.prompts",
|
|
2765
|
+
channel: channel.id,
|
|
2766
|
+
thread_ts: threadTs,
|
|
2767
|
+
prompts: t.prompts,
|
|
2768
|
+
title: t.promptsTitle
|
|
2769
|
+
});
|
|
2770
|
+
return {};
|
|
2771
|
+
},
|
|
2772
|
+
"pins.add": (ctx, args) => {
|
|
2773
|
+
const channel = ctx.store.channel(required(args, "channel"));
|
|
2774
|
+
ctx.store.message(channel.id, required(args, "timestamp"));
|
|
2775
|
+
return {};
|
|
2776
|
+
}
|
|
2777
|
+
};
|
|
2778
|
+
function streamText(args) {
|
|
2779
|
+
const md = str(args, "markdown_text");
|
|
2780
|
+
if (md)
|
|
2781
|
+
return md;
|
|
2782
|
+
const chunks = Array.isArray(args.chunks) ? args.chunks : [];
|
|
2783
|
+
return chunks.map((c) => typeof c.text === "string" ? c.text : typeof c.markdown_text === "string" ? c.markdown_text : "").join("");
|
|
2784
|
+
}
|
|
2785
|
+
function historyMessage(m, includeMetadata) {
|
|
2786
|
+
const wire = wireMessage(m);
|
|
2787
|
+
if (!includeMetadata)
|
|
2788
|
+
delete wire.metadata;
|
|
2789
|
+
return wire;
|
|
2790
|
+
}
|
|
2791
|
+
function viewArg(args) {
|
|
2792
|
+
const v = args.view;
|
|
2793
|
+
if (typeof v === "string") {
|
|
2794
|
+
try {
|
|
2795
|
+
return JSON.parse(v);
|
|
2796
|
+
} catch {
|
|
2797
|
+
throw new SlackApiError("invalid_arguments", {
|
|
2798
|
+
response_metadata: { messages: ["[ERROR] view must be valid JSON"] }
|
|
2799
|
+
});
|
|
2800
|
+
}
|
|
2801
|
+
}
|
|
2802
|
+
if (v && typeof v === "object")
|
|
2803
|
+
return v;
|
|
2804
|
+
throw new SlackApiError("invalid_arguments", {
|
|
2805
|
+
response_metadata: { messages: ["[ERROR] missing required field: view"] }
|
|
2806
|
+
});
|
|
2807
|
+
}
|
|
2808
|
+
function publicView(view) {
|
|
2809
|
+
const { opened_by: _o, trigger_id: _t, ...rest } = view;
|
|
2810
|
+
return rest;
|
|
2811
|
+
}
|
|
2812
|
+
function cursorOffset(cursor) {
|
|
2813
|
+
if (!cursor)
|
|
2814
|
+
return 0;
|
|
2815
|
+
return Number.parseInt(Buffer.from(cursor, "base64").toString("utf8").replace("offset:", ""), 10) || 0;
|
|
2816
|
+
}
|
|
2817
|
+
function cursorFor(offset) {
|
|
2818
|
+
return Buffer.from(`offset:${offset}`).toString("base64");
|
|
2819
|
+
}
|
|
2820
|
+
function newTriggerId() {
|
|
2821
|
+
return `${nowUnix()}${Math.floor(Math.random() * 1e6)}.${slackId("", 10).toLowerCase()}.${nextTs().replace(".", "")}`;
|
|
2822
|
+
}
|
|
2823
|
+
|
|
2824
|
+
// src/server.ts
|
|
2825
|
+
var DEFAULT_EVENTS = [
|
|
2826
|
+
"message.channels",
|
|
2827
|
+
"message.groups",
|
|
2828
|
+
"message.im",
|
|
2829
|
+
"message.mpim",
|
|
2830
|
+
"app_mention",
|
|
2831
|
+
"assistant_thread_started",
|
|
2832
|
+
"assistant_thread_context_changed",
|
|
2833
|
+
"reaction_added",
|
|
2834
|
+
"reaction_removed",
|
|
2835
|
+
"member_joined_channel"
|
|
2836
|
+
];
|
|
2837
|
+
|
|
2838
|
+
class SlackMock {
|
|
2839
|
+
store;
|
|
2840
|
+
hub;
|
|
2841
|
+
opts;
|
|
2842
|
+
server;
|
|
2843
|
+
triggerIds = new Map;
|
|
2844
|
+
pendingUploads = new Map;
|
|
2845
|
+
responseUrls = new Map;
|
|
2846
|
+
inflight = new Set;
|
|
2847
|
+
subscribed;
|
|
2848
|
+
commands = null;
|
|
2849
|
+
faults = [];
|
|
2850
|
+
lastRequestAt = 0;
|
|
2851
|
+
log;
|
|
2852
|
+
static Error = SlackApiError;
|
|
2853
|
+
constructor(opts = {}) {
|
|
2854
|
+
const manifest = typeof opts.manifest === "string" ? JSON.parse(readFileSync2(opts.manifest, "utf8")) : opts.manifest;
|
|
2855
|
+
const appName = opts.appName ?? manifest?.features?.bot_user?.display_name ?? manifest?.display_information?.name;
|
|
2856
|
+
this.opts = { ...opts, appName };
|
|
2857
|
+
this.log = typeof opts.log === "function" ? opts.log : opts.log ? (m) => console.log(`[slack-mock] ${m}`) : () => {};
|
|
2858
|
+
if (opts.dataFile)
|
|
2859
|
+
ensureDir(opts.dataFile);
|
|
2860
|
+
this.store = new Store({ ...opts, appName });
|
|
2861
|
+
this.hub = new SocketModeHub({
|
|
2862
|
+
appId: this.store.app.id,
|
|
2863
|
+
pingIntervalMs: opts.pingIntervalMs,
|
|
2864
|
+
ackTimeoutMs: opts.ackTimeoutMs,
|
|
2865
|
+
maxRetries: opts.maxRetries,
|
|
2866
|
+
log: this.log
|
|
2867
|
+
});
|
|
2868
|
+
this.subscribed = new Set(opts.subscribedEvents ?? manifest?.settings?.event_subscriptions?.bot_events ?? DEFAULT_EVENTS);
|
|
2869
|
+
if (manifest?.features?.slash_commands)
|
|
2870
|
+
this.commands = new Set(manifest.features.slash_commands.map((c) => c.command));
|
|
2871
|
+
if (opts.seed !== false && this.store.channels.size === 0)
|
|
2872
|
+
this.seed();
|
|
2873
|
+
this.store.onChange((change) => this.dispatch(change));
|
|
2874
|
+
}
|
|
2875
|
+
static async start(opts = {}) {
|
|
2876
|
+
const mock = new SlackMock(opts);
|
|
2877
|
+
mock.listen();
|
|
2878
|
+
return mock;
|
|
2879
|
+
}
|
|
2880
|
+
seed() {
|
|
2881
|
+
const alice = this.store.addUser({
|
|
2882
|
+
id: "U0ALICE000",
|
|
2883
|
+
name: "alice",
|
|
2884
|
+
real_name: "Alice Example",
|
|
2885
|
+
email: "alice@example.com",
|
|
2886
|
+
is_admin: true
|
|
2887
|
+
});
|
|
2888
|
+
const bob = this.store.addUser({
|
|
2889
|
+
id: "U0BOB00000",
|
|
2890
|
+
name: "bob",
|
|
2891
|
+
real_name: "Bob Example",
|
|
2892
|
+
email: "bob@example.com"
|
|
2893
|
+
});
|
|
2894
|
+
this.store.addChannel({
|
|
2895
|
+
id: "C0GENERAL0",
|
|
2896
|
+
name: "general",
|
|
2897
|
+
creator: alice.id,
|
|
2898
|
+
members: [alice.id, bob.id, this.store.bot.userId],
|
|
2899
|
+
purpose: "Company-wide announcements"
|
|
2900
|
+
});
|
|
2901
|
+
}
|
|
2902
|
+
listen() {
|
|
2903
|
+
const host = this.opts.host ?? "127.0.0.1";
|
|
2904
|
+
this.server = Bun.serve({
|
|
2905
|
+
hostname: host,
|
|
2906
|
+
port: this.opts.port ?? 0,
|
|
2907
|
+
fetch: (req, server) => this.fetch(req, server),
|
|
2908
|
+
websocket: {
|
|
2909
|
+
open: (ws) => this.hub.open(ws),
|
|
2910
|
+
message: (ws, msg) => this.hub.message(ws, msg),
|
|
2911
|
+
close: (ws) => this.hub.close(ws),
|
|
2912
|
+
ping: () => {},
|
|
2913
|
+
pong: () => {}
|
|
2914
|
+
}
|
|
2915
|
+
});
|
|
2916
|
+
this.log(`listening on ${this.baseUrl}`);
|
|
2917
|
+
}
|
|
2918
|
+
get baseUrl() {
|
|
2919
|
+
return `http://${this.server.hostname}:${this.server.port}`;
|
|
2920
|
+
}
|
|
2921
|
+
get apiUrl() {
|
|
2922
|
+
return `${this.baseUrl}/api/`;
|
|
2923
|
+
}
|
|
2924
|
+
get port() {
|
|
2925
|
+
return this.server.port ?? 0;
|
|
2926
|
+
}
|
|
2927
|
+
get env() {
|
|
2928
|
+
return {
|
|
2929
|
+
SLACK_BOT_TOKEN: this.store.bot.token,
|
|
2930
|
+
SLACK_APP_TOKEN: this.store.bot.appToken,
|
|
2931
|
+
SLACK_API_URL: this.apiUrl,
|
|
2932
|
+
SLACK_SIGNING_SECRET: "mock-signing-secret"
|
|
2933
|
+
};
|
|
2934
|
+
}
|
|
2935
|
+
get bot() {
|
|
2936
|
+
return this.store.bot;
|
|
2937
|
+
}
|
|
2938
|
+
get team() {
|
|
2939
|
+
return this.store.team;
|
|
2940
|
+
}
|
|
2941
|
+
async stop() {
|
|
2942
|
+
this.hub.shutdown();
|
|
2943
|
+
await Promise.allSettled([...this.inflight]);
|
|
2944
|
+
this.server.stop(true);
|
|
2945
|
+
}
|
|
2946
|
+
async fetch(req, server) {
|
|
2947
|
+
const url = new URL(req.url);
|
|
2948
|
+
const path = url.pathname;
|
|
2949
|
+
this.lastRequestAt = Date.now();
|
|
2950
|
+
try {
|
|
2951
|
+
if (path.startsWith("/link/") || path === "/link") {
|
|
2952
|
+
const ticket = url.searchParams.get("ticket") ?? "";
|
|
2953
|
+
if (!this.hub.tickets.has(ticket))
|
|
2954
|
+
return new Response("invalid ticket", { status: 403 });
|
|
2955
|
+
this.hub.tickets.delete(ticket);
|
|
2956
|
+
if (server.upgrade(req, { data: { id: slackId("S", 6), ticket } }))
|
|
2957
|
+
return;
|
|
2958
|
+
return new Response("upgrade failed", { status: 400 });
|
|
2959
|
+
}
|
|
2960
|
+
if (path.startsWith("/api/"))
|
|
2961
|
+
return await this.handleApi(req, path.slice(5));
|
|
2962
|
+
if (path.startsWith("/upload/v1/"))
|
|
2963
|
+
return await this.handleUpload(req, path.slice("/upload/v1/".length));
|
|
2964
|
+
if (path.startsWith("/files-pri/"))
|
|
2965
|
+
return this.handleDownload(req, path);
|
|
2966
|
+
if (path.startsWith("/actions/"))
|
|
2967
|
+
return await this.handleResponseUrl(req, path.slice("/actions/".length));
|
|
2968
|
+
if (path.startsWith("/mock/"))
|
|
2969
|
+
return await this.handleAdmin(req, path.slice(6), url);
|
|
2970
|
+
return this.handleUi(path, url);
|
|
2971
|
+
} catch (e) {
|
|
2972
|
+
this.log(`unhandled error on ${req.method} ${path}: ${e instanceof Error ? e.stack : e}`);
|
|
2973
|
+
return new Response(String(e), { status: 500 });
|
|
2974
|
+
}
|
|
2975
|
+
}
|
|
2976
|
+
actorFor(token) {
|
|
2977
|
+
if (!token)
|
|
2978
|
+
return null;
|
|
2979
|
+
if (token === this.store.bot.token || token === this.store.bot.appToken)
|
|
2980
|
+
return { userId: this.store.bot.userId, isBot: true };
|
|
2981
|
+
if (this.store.bot.userToken && token === this.store.bot.userToken) {
|
|
2982
|
+
const human = [...this.store.users.values()].find((u) => !u.is_bot);
|
|
2983
|
+
return human ? { userId: human.id, isBot: false } : null;
|
|
2984
|
+
}
|
|
2985
|
+
return null;
|
|
2986
|
+
}
|
|
2987
|
+
async handleApi(req, method) {
|
|
2988
|
+
let args = {};
|
|
2989
|
+
try {
|
|
2990
|
+
args = await parseArgs(req);
|
|
2991
|
+
} catch (e) {
|
|
2992
|
+
return slackError("invalid_form_data", { detail: String(e) });
|
|
2993
|
+
}
|
|
2994
|
+
const token = bearerToken(req, args);
|
|
2995
|
+
const actor = this.actorFor(token);
|
|
2996
|
+
const record = (ok, error) => {
|
|
2997
|
+
const { token: _t, ...rest } = args;
|
|
2998
|
+
const call = {
|
|
2999
|
+
at: new Date().toISOString(),
|
|
3000
|
+
method,
|
|
3001
|
+
args: rest,
|
|
3002
|
+
ok,
|
|
3003
|
+
...error ? { error } : {}
|
|
3004
|
+
};
|
|
3005
|
+
this.store.recordApiCall(call);
|
|
3006
|
+
};
|
|
3007
|
+
if (!token) {
|
|
3008
|
+
record(false, "not_authed");
|
|
3009
|
+
return slackError("not_authed");
|
|
3010
|
+
}
|
|
3011
|
+
if (!actor) {
|
|
3012
|
+
record(false, "invalid_auth");
|
|
3013
|
+
return slackError("invalid_auth");
|
|
3014
|
+
}
|
|
3015
|
+
if (method === "apps.connections.open" && token !== this.store.bot.appToken) {
|
|
3016
|
+
record(false, "not_allowed_token_type");
|
|
3017
|
+
return slackError("not_allowed_token_type");
|
|
3018
|
+
}
|
|
3019
|
+
const fault = this.faults.find((f) => f.method === method && f.remaining > 0);
|
|
3020
|
+
if (fault) {
|
|
3021
|
+
fault.remaining -= 1;
|
|
3022
|
+
record(false, fault.error);
|
|
3023
|
+
this.log(`${method} -> injected ${fault.error}`);
|
|
3024
|
+
return Response.json({
|
|
3025
|
+
ok: false,
|
|
3026
|
+
error: fault.error,
|
|
3027
|
+
...fault.retryAfterSec ? { retry_after: fault.retryAfterSec } : {},
|
|
3028
|
+
...fault.extra
|
|
3029
|
+
}, {
|
|
3030
|
+
status: fault.httpStatus ?? 200,
|
|
3031
|
+
headers: fault.retryAfterSec ? { "retry-after": String(fault.retryAfterSec) } : {}
|
|
3032
|
+
});
|
|
3033
|
+
}
|
|
3034
|
+
const handler = handlers[method];
|
|
3035
|
+
if (!handler) {
|
|
3036
|
+
record(false, "unknown_method");
|
|
3037
|
+
return slackError("unknown_method", { req_method: method });
|
|
3038
|
+
}
|
|
3039
|
+
const ctx = {
|
|
3040
|
+
store: this.store,
|
|
3041
|
+
hub: this.hub,
|
|
3042
|
+
baseUrl: this.baseUrl,
|
|
3043
|
+
wsUrl: this.baseUrl.replace(/^http/, "ws"),
|
|
3044
|
+
actor,
|
|
3045
|
+
triggerIds: this.triggerIds,
|
|
3046
|
+
pendingUploads: this.pendingUploads
|
|
3047
|
+
};
|
|
3048
|
+
try {
|
|
3049
|
+
const body = handler(ctx, args);
|
|
3050
|
+
record(true);
|
|
3051
|
+
return Response.json({ ok: true, ...body });
|
|
3052
|
+
} catch (e) {
|
|
3053
|
+
if (e instanceof SlackApiError) {
|
|
3054
|
+
record(false, e.code);
|
|
3055
|
+
this.log(`${method} -> ${e.code}`);
|
|
3056
|
+
return slackError(e.code, e.extra);
|
|
3057
|
+
}
|
|
3058
|
+
throw e;
|
|
3059
|
+
}
|
|
3060
|
+
}
|
|
3061
|
+
async handleUpload(req, fileId) {
|
|
3062
|
+
const pending = this.pendingUploads.get(fileId);
|
|
3063
|
+
if (!pending)
|
|
3064
|
+
return new Response("unknown upload", { status: 404 });
|
|
3065
|
+
let bytes;
|
|
3066
|
+
const contentType = req.headers.get("content-type") ?? "";
|
|
3067
|
+
if (contentType.includes("multipart/form-data")) {
|
|
3068
|
+
const form = await req.formData();
|
|
3069
|
+
let part;
|
|
3070
|
+
form.forEach((v) => {
|
|
3071
|
+
if (typeof v !== "string" && !part)
|
|
3072
|
+
part = v;
|
|
3073
|
+
});
|
|
3074
|
+
bytes = part ? new Uint8Array(await part.arrayBuffer()) : new Uint8Array;
|
|
3075
|
+
} else {
|
|
3076
|
+
bytes = new Uint8Array(await req.arrayBuffer());
|
|
3077
|
+
}
|
|
3078
|
+
this.pendingUploads.delete(fileId);
|
|
3079
|
+
this.store.addFile({
|
|
3080
|
+
id: fileId,
|
|
3081
|
+
name: pending.name,
|
|
3082
|
+
user: pending.user,
|
|
3083
|
+
bytes,
|
|
3084
|
+
baseUrl: this.baseUrl
|
|
3085
|
+
});
|
|
3086
|
+
return new Response("OK");
|
|
3087
|
+
}
|
|
3088
|
+
handleDownload(req, path) {
|
|
3089
|
+
const m = /^\/files-pri\/[A-Z0-9]+-([A-Z0-9]+)\/(?:download\/)?/.exec(path);
|
|
3090
|
+
const file = m ? this.store.files.get(m[1]) : undefined;
|
|
3091
|
+
if (!file)
|
|
3092
|
+
return new Response("not found", { status: 404 });
|
|
3093
|
+
const token = bearerToken(req, {}) ?? new URL(req.url).searchParams.get("t") ?? undefined;
|
|
3094
|
+
if (!this.actorFor(token))
|
|
3095
|
+
return new Response("authentication required", { status: 401 });
|
|
3096
|
+
return new Response(Buffer.from(file.bytes ?? new Uint8Array), {
|
|
3097
|
+
headers: {
|
|
3098
|
+
"content-type": file.mimetype,
|
|
3099
|
+
"content-disposition": `attachment; filename="${file.name}"`,
|
|
3100
|
+
"content-length": String(file.size)
|
|
3101
|
+
}
|
|
3102
|
+
});
|
|
3103
|
+
}
|
|
3104
|
+
async handleResponseUrl(req, id) {
|
|
3105
|
+
const target = this.responseUrls.get(id);
|
|
3106
|
+
if (!target)
|
|
3107
|
+
return new Response("invalid response_url", { status: 404 });
|
|
3108
|
+
if (Date.now() > target.expires)
|
|
3109
|
+
return new Response("expired_url", { status: 410 });
|
|
3110
|
+
let body;
|
|
3111
|
+
try {
|
|
3112
|
+
body = await parseArgs(req);
|
|
3113
|
+
} catch (e) {
|
|
3114
|
+
return Response.json({ ok: false, error: "invalid_payload", detail: String(e) }, { status: 400 });
|
|
3115
|
+
}
|
|
3116
|
+
const isTrue = (v) => v === true || v === "true";
|
|
3117
|
+
try {
|
|
3118
|
+
if (isTrue(body.delete_original) && target.messageTs) {
|
|
3119
|
+
if (this.store.findMessage(target.channel, target.messageTs))
|
|
3120
|
+
this.store.deleteMessage(target.channel, target.messageTs);
|
|
3121
|
+
else
|
|
3122
|
+
this.store.deleteEphemeral(target.channel, target.messageTs);
|
|
3123
|
+
return new Response("ok");
|
|
3124
|
+
}
|
|
3125
|
+
if (isTrue(body.replace_original) && target.messageTs) {
|
|
3126
|
+
const patch = { text: body.text ?? "", blocks: body.blocks, attachments: body.attachments };
|
|
3127
|
+
if (this.store.findMessage(target.channel, target.messageTs))
|
|
3128
|
+
this.store.updateMessage(target.channel, target.messageTs, patch, this.store.bot.userId);
|
|
3129
|
+
else
|
|
3130
|
+
this.store.updateEphemeral(target.channel, target.messageTs, patch);
|
|
3131
|
+
return new Response("ok");
|
|
3132
|
+
}
|
|
3133
|
+
} catch (e) {
|
|
3134
|
+
if (e instanceof SlackApiError)
|
|
3135
|
+
return Response.json({ ok: false, error: e.code });
|
|
3136
|
+
throw e;
|
|
3137
|
+
}
|
|
3138
|
+
this.postAsBot({
|
|
3139
|
+
channel: target.channel,
|
|
3140
|
+
text: body.text ?? "",
|
|
3141
|
+
blocks: body.blocks,
|
|
3142
|
+
attachments: body.attachments,
|
|
3143
|
+
thread_ts: body.thread_ts,
|
|
3144
|
+
ephemeral_user: body.response_type === "in_channel" ? undefined : target.user
|
|
3145
|
+
});
|
|
3146
|
+
return new Response("ok");
|
|
3147
|
+
}
|
|
3148
|
+
postAsBot(input) {
|
|
3149
|
+
return this.store.addMessage({
|
|
3150
|
+
channel: input.channel,
|
|
3151
|
+
user: this.store.bot.userId,
|
|
3152
|
+
text: input.text,
|
|
3153
|
+
blocks: input.blocks,
|
|
3154
|
+
attachments: input.attachments,
|
|
3155
|
+
...input.thread_ts ? { thread_ts: input.thread_ts } : {},
|
|
3156
|
+
...input.ephemeral_user ? { ephemeral_user: input.ephemeral_user } : {},
|
|
3157
|
+
bot_id: this.store.bot.botId,
|
|
3158
|
+
app_id: this.store.app.id
|
|
3159
|
+
});
|
|
3160
|
+
}
|
|
3161
|
+
handleUi(path, url) {
|
|
3162
|
+
const screenshotParam = url.searchParams.get("screenshot");
|
|
3163
|
+
const screenshot = screenshotParam !== null && screenshotParam !== "0" && screenshotParam !== "false";
|
|
3164
|
+
const refresh = Number(url.searchParams.get("refresh"));
|
|
3165
|
+
const panel = url.searchParams.get("panel") ?? this.opts.panelWidth;
|
|
3166
|
+
const opts = {
|
|
3167
|
+
screenshot,
|
|
3168
|
+
refreshSec: Number.isFinite(refresh) && refresh > 0 ? refresh : undefined,
|
|
3169
|
+
connections: this.hub.connectionCount,
|
|
3170
|
+
panelWidth: panel ? /^\d+$/.test(panel) ? `${panel}%` : /^\d+(px|%|vw|rem)$/.test(panel) ? panel : undefined : undefined,
|
|
3171
|
+
threadView: url.searchParams.has("full") ? "full" : "panel"
|
|
3172
|
+
};
|
|
3173
|
+
let html;
|
|
3174
|
+
if (path === "/" || path === "")
|
|
3175
|
+
html = renderPage(this.store, { kind: "index" }, opts);
|
|
3176
|
+
else {
|
|
3177
|
+
const m = /^\/c\/([^/]+)(?:\/t\/([^/]+))?\/?$/.exec(path);
|
|
3178
|
+
if (!m)
|
|
3179
|
+
return new Response("not found", { status: 404 });
|
|
3180
|
+
const channel = this.store.channelByName(m[1])?.id ?? m[1];
|
|
3181
|
+
if (!this.store.channels.has(channel))
|
|
3182
|
+
return new Response("channel not found", { status: 404 });
|
|
3183
|
+
html = m[2] ? renderPage(this.store, { kind: "thread", channel, ts: m[2] }, opts) : renderPage(this.store, { kind: "channel", channel }, opts);
|
|
3184
|
+
}
|
|
3185
|
+
return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } });
|
|
3186
|
+
}
|
|
3187
|
+
isSubscribed(type) {
|
|
3188
|
+
return this.subscribed.has(type);
|
|
3189
|
+
}
|
|
3190
|
+
messageEventName(channel) {
|
|
3191
|
+
const t = this.store.channelType(channel);
|
|
3192
|
+
return `message.${t === "channel" ? "channels" : t === "group" ? "groups" : t}`;
|
|
3193
|
+
}
|
|
3194
|
+
track(p) {
|
|
3195
|
+
const wrapped = p.then(() => {}, (e) => {
|
|
3196
|
+
if (!(e instanceof SocketModeClosedError))
|
|
3197
|
+
this.log(`delivery failed: ${e instanceof Error ? e.message : e}`);
|
|
3198
|
+
});
|
|
3199
|
+
this.inflight.add(wrapped);
|
|
3200
|
+
wrapped.finally(() => this.inflight.delete(wrapped));
|
|
3201
|
+
return wrapped;
|
|
3202
|
+
}
|
|
3203
|
+
push(event) {
|
|
3204
|
+
if (this.hub.connectionCount === 0) {
|
|
3205
|
+
this.log(`dropping ${event.type}${event.subtype ? `/${event.subtype}` : ""} event: no app connected`);
|
|
3206
|
+
return Promise.resolve();
|
|
3207
|
+
}
|
|
3208
|
+
const send = async () => {
|
|
3209
|
+
if (this.opts.eventDelayMs)
|
|
3210
|
+
await Bun.sleep(this.opts.eventDelayMs);
|
|
3211
|
+
await this.hub.send("events_api", eventCallback(this.store, event));
|
|
3212
|
+
};
|
|
3213
|
+
return this.track(send());
|
|
3214
|
+
}
|
|
3215
|
+
botInChannel(channel) {
|
|
3216
|
+
return channel.members.includes(this.store.bot.userId);
|
|
3217
|
+
}
|
|
3218
|
+
dispatch(change) {
|
|
3219
|
+
switch (change.kind) {
|
|
3220
|
+
case "message.add": {
|
|
3221
|
+
const m = change.message;
|
|
3222
|
+
if (m.ephemeral_user || m.subtype === "assistant_app_thread")
|
|
3223
|
+
return;
|
|
3224
|
+
const channel = this.store.channel(m.channel);
|
|
3225
|
+
if (!this.botInChannel(channel))
|
|
3226
|
+
return;
|
|
3227
|
+
const fromBot = this.store.isBotUser(m.user);
|
|
3228
|
+
if (fromBot && this.opts.echoBotMessages === false)
|
|
3229
|
+
return;
|
|
3230
|
+
const mentionsBot = !fromBot && m.text.includes(`<@${this.store.bot.userId}>`);
|
|
3231
|
+
if (mentionsBot && this.isSubscribed("app_mention"))
|
|
3232
|
+
this.push(appMentionEvent(this.store, m));
|
|
3233
|
+
if (this.isSubscribed(this.messageEventName(channel)))
|
|
3234
|
+
this.push(messageEvent(this.store, m, channel));
|
|
3235
|
+
return;
|
|
3236
|
+
}
|
|
3237
|
+
case "message.update": {
|
|
3238
|
+
const channel = this.store.channel(change.message.channel);
|
|
3239
|
+
if (this.botInChannel(channel) && this.isSubscribed(this.messageEventName(channel))) {
|
|
3240
|
+
this.push(messageChangedEvent(this.store, change.message, change.previous));
|
|
3241
|
+
}
|
|
3242
|
+
return;
|
|
3243
|
+
}
|
|
3244
|
+
case "message.delete": {
|
|
3245
|
+
const channel = this.store.channel(change.message.channel);
|
|
3246
|
+
if (this.botInChannel(channel) && this.isSubscribed(this.messageEventName(channel))) {
|
|
3247
|
+
this.push(messageDeletedEvent(this.store, change.message));
|
|
3248
|
+
}
|
|
3249
|
+
return;
|
|
3250
|
+
}
|
|
3251
|
+
case "reaction.add":
|
|
3252
|
+
case "reaction.remove": {
|
|
3253
|
+
const kind = change.kind === "reaction.add" ? "reaction_added" : "reaction_removed";
|
|
3254
|
+
if (this.isSubscribed(kind) && this.botInChannel(this.store.channel(change.message.channel))) {
|
|
3255
|
+
this.push(reactionEvent(kind, change.message, change.name, change.user));
|
|
3256
|
+
}
|
|
3257
|
+
return;
|
|
3258
|
+
}
|
|
3259
|
+
case "member.join": {
|
|
3260
|
+
if (this.isSubscribed("member_joined_channel") && this.botInChannel(change.channel)) {
|
|
3261
|
+
this.push(memberJoinedEvent(this.store, change.channel, change.user, change.inviter));
|
|
3262
|
+
}
|
|
3263
|
+
return;
|
|
3264
|
+
}
|
|
3265
|
+
default:
|
|
3266
|
+
return;
|
|
3267
|
+
}
|
|
3268
|
+
}
|
|
3269
|
+
async flush(settleMs = 100, maxMs = 3000) {
|
|
3270
|
+
const start = Date.now();
|
|
3271
|
+
for (;; ) {
|
|
3272
|
+
while (this.inflight.size > 0)
|
|
3273
|
+
await Promise.allSettled([...this.inflight]);
|
|
3274
|
+
const quietSince = Math.max(this.lastRequestAt, start);
|
|
3275
|
+
const quiet = Date.now() - quietSince;
|
|
3276
|
+
if (quiet >= settleMs || Date.now() - start > maxMs)
|
|
3277
|
+
return;
|
|
3278
|
+
await Bun.sleep(settleMs - quiet + 5);
|
|
3279
|
+
}
|
|
3280
|
+
}
|
|
3281
|
+
addUser(input) {
|
|
3282
|
+
return this.store.addUser(input);
|
|
3283
|
+
}
|
|
3284
|
+
addChannel(input) {
|
|
3285
|
+
const members = [...input.members ?? []];
|
|
3286
|
+
if (input.withBot !== false)
|
|
3287
|
+
members.push(this.store.bot.userId);
|
|
3288
|
+
const creator = input.creator ?? (input.withBot === false ? members[0] ?? this.defaultHuman().id : this.store.bot.userId);
|
|
3289
|
+
return this.store.addChannel({ ...input, creator, members });
|
|
3290
|
+
}
|
|
3291
|
+
openDm(user) {
|
|
3292
|
+
return this.store.openDm(user);
|
|
3293
|
+
}
|
|
3294
|
+
invite(channel, users, inviter) {
|
|
3295
|
+
for (const u of users)
|
|
3296
|
+
this.store.join(this.resolveChannel(channel).id, u, inviter);
|
|
3297
|
+
}
|
|
3298
|
+
user(idOrName) {
|
|
3299
|
+
const byId = this.store.users.get(idOrName);
|
|
3300
|
+
if (byId)
|
|
3301
|
+
return byId;
|
|
3302
|
+
for (const u of this.store.users.values())
|
|
3303
|
+
if (u.name === idOrName)
|
|
3304
|
+
return u;
|
|
3305
|
+
throw new SlackApiError("user_not_found");
|
|
3306
|
+
}
|
|
3307
|
+
channel(idOrName) {
|
|
3308
|
+
return this.resolveChannel(idOrName);
|
|
3309
|
+
}
|
|
3310
|
+
resolveChannel(idOrName) {
|
|
3311
|
+
return this.store.channels.get(idOrName) ?? this.store.channelByName(idOrName) ?? this.store.channel(idOrName);
|
|
3312
|
+
}
|
|
3313
|
+
defaultHuman() {
|
|
3314
|
+
const u = [...this.store.users.values()].find((x) => !x.is_bot);
|
|
3315
|
+
if (!u)
|
|
3316
|
+
throw new Error("no human user in the workspace; call addUser first");
|
|
3317
|
+
return u;
|
|
3318
|
+
}
|
|
3319
|
+
resolveMentions(text) {
|
|
3320
|
+
const byName = new Map;
|
|
3321
|
+
for (const u of this.store.users.values())
|
|
3322
|
+
byName.set(u.name.toLowerCase(), u.id);
|
|
3323
|
+
return text.replace(/(^|[^<\w])@([\w.-]+)/g, (whole, lead, name) => {
|
|
3324
|
+
const lower = name.toLowerCase();
|
|
3325
|
+
if (lower === "here" || lower === "channel" || lower === "everyone")
|
|
3326
|
+
return `${lead}<!${lower}>`;
|
|
3327
|
+
const id = byName.get(lower);
|
|
3328
|
+
return id ? `${lead}<@${id}>` : whole;
|
|
3329
|
+
});
|
|
3330
|
+
}
|
|
3331
|
+
async postMessage(input) {
|
|
3332
|
+
const channel = this.resolveChannel(input.channel);
|
|
3333
|
+
const user = input.user ? this.user(input.user) : this.defaultHuman();
|
|
3334
|
+
if (!channel.members.includes(user.id))
|
|
3335
|
+
this.store.join(channel.id, user.id);
|
|
3336
|
+
const files = input.files?.map((f) => this.store.addFile({
|
|
3337
|
+
name: f.name,
|
|
3338
|
+
title: f.title,
|
|
3339
|
+
mimetype: f.mimetype,
|
|
3340
|
+
user: user.id,
|
|
3341
|
+
bytes: typeof f.content === "string" ? new TextEncoder().encode(f.content) : f.content,
|
|
3342
|
+
baseUrl: this.baseUrl
|
|
3343
|
+
}));
|
|
3344
|
+
for (const f of files ?? [])
|
|
3345
|
+
f.channels.push(channel.id);
|
|
3346
|
+
const before = new Set(this.inflight);
|
|
3347
|
+
const message = this.store.addMessage({
|
|
3348
|
+
channel: channel.id,
|
|
3349
|
+
user: user.id,
|
|
3350
|
+
text: input.text,
|
|
3351
|
+
client_msg_id: crypto.randomUUID(),
|
|
3352
|
+
...input.thread_ts ? { thread_ts: input.thread_ts } : {},
|
|
3353
|
+
...input.reply_broadcast && input.thread_ts ? { subtype: "thread_broadcast" } : {},
|
|
3354
|
+
...input.blocks ? { blocks: input.blocks } : {},
|
|
3355
|
+
...files?.length ? { files, subtype: "file_share" } : {}
|
|
3356
|
+
});
|
|
3357
|
+
await Promise.allSettled([...this.inflight].filter((p) => !before.has(p)));
|
|
3358
|
+
return message;
|
|
3359
|
+
}
|
|
3360
|
+
async editMessage(channel, ts, text) {
|
|
3361
|
+
const c = this.resolveChannel(channel);
|
|
3362
|
+
const existing = this.store.message(c.id, ts);
|
|
3363
|
+
const message = this.store.updateMessage(c.id, ts, { text }, existing.user ?? this.defaultHuman().id);
|
|
3364
|
+
await this.flush();
|
|
3365
|
+
return message;
|
|
3366
|
+
}
|
|
3367
|
+
async deleteMessage(channel, ts) {
|
|
3368
|
+
this.store.deleteMessage(this.resolveChannel(channel).id, ts);
|
|
3369
|
+
await this.flush();
|
|
3370
|
+
}
|
|
3371
|
+
async addReaction(input) {
|
|
3372
|
+
const user = input.user ? this.user(input.user) : this.defaultHuman();
|
|
3373
|
+
this.store.addReaction(this.resolveChannel(input.channel).id, input.ts, input.name, user.id);
|
|
3374
|
+
await this.flush();
|
|
3375
|
+
}
|
|
3376
|
+
issueResponseUrl(target) {
|
|
3377
|
+
const id = `${this.store.team.id}/${slackId("", 10)}/${slackId("", 24).toLowerCase()}`;
|
|
3378
|
+
this.responseUrls.set(id, { ...target, expires: Date.now() + 30 * 60000 });
|
|
3379
|
+
return `${this.baseUrl}/actions/${id}`;
|
|
3380
|
+
}
|
|
3381
|
+
issueTriggerId() {
|
|
3382
|
+
const id = newTriggerId();
|
|
3383
|
+
this.triggerIds.set(id, Date.now() + (this.opts.triggerIdTtlMs ?? 3000));
|
|
3384
|
+
return id;
|
|
3385
|
+
}
|
|
3386
|
+
async slashCommand(input) {
|
|
3387
|
+
if (this.commands && !this.commands.has(input.command))
|
|
3388
|
+
throw new Error(`unknown slash command ${input.command}; manifest declares ${[...this.commands].join(", ")}`);
|
|
3389
|
+
const user = input.user ? this.user(input.user) : this.defaultHuman();
|
|
3390
|
+
const channel = input.channel ? this.resolveChannel(input.channel) : this.store.channelByName("general") ?? this.openDm(user.id);
|
|
3391
|
+
const responseUrl = this.issueResponseUrl({ channel: channel.id, user: user.id });
|
|
3392
|
+
const payload = slashCommandPayload(this.store, {
|
|
3393
|
+
command: input.command,
|
|
3394
|
+
text: input.text ?? "",
|
|
3395
|
+
user,
|
|
3396
|
+
channel,
|
|
3397
|
+
responseUrl,
|
|
3398
|
+
triggerId: this.issueTriggerId()
|
|
3399
|
+
});
|
|
3400
|
+
const ack = await this.hub.send("slash_commands", payload, true);
|
|
3401
|
+
let response;
|
|
3402
|
+
const body = ack.payload;
|
|
3403
|
+
if (body && (body.text || body.blocks)) {
|
|
3404
|
+
response = this.postAsBot({
|
|
3405
|
+
channel: channel.id,
|
|
3406
|
+
text: body.text ?? "",
|
|
3407
|
+
blocks: body.blocks,
|
|
3408
|
+
ephemeral_user: body.response_type === "in_channel" ? undefined : user.id
|
|
3409
|
+
});
|
|
3410
|
+
}
|
|
3411
|
+
await this.flush();
|
|
3412
|
+
return { ack, response };
|
|
3413
|
+
}
|
|
3414
|
+
async clickButton(input) {
|
|
3415
|
+
const user = input.user ? this.user(input.user) : this.defaultHuman();
|
|
3416
|
+
const channel = this.resolveChannel(input.channel);
|
|
3417
|
+
const message = this.store.findMessage(channel.id, input.ts) ?? this.store.ephemerals.find((m) => m.channel === channel.id && m.ts === input.ts);
|
|
3418
|
+
if (!message)
|
|
3419
|
+
throw new SlackApiError("message_not_found");
|
|
3420
|
+
const found = findButton(message.blocks, input.action_id);
|
|
3421
|
+
if (!found && !input.value && !input.block_id)
|
|
3422
|
+
throw new Error(`no button with action_id ${input.action_id} on message ${input.ts}`);
|
|
3423
|
+
const responseUrl = this.issueResponseUrl({
|
|
3424
|
+
channel: channel.id,
|
|
3425
|
+
user: user.id,
|
|
3426
|
+
messageTs: message.ts
|
|
3427
|
+
});
|
|
3428
|
+
const payload = blockActionsPayload(this.store, {
|
|
3429
|
+
user,
|
|
3430
|
+
channel,
|
|
3431
|
+
message,
|
|
3432
|
+
responseUrl,
|
|
3433
|
+
triggerId: this.issueTriggerId(),
|
|
3434
|
+
actions: [
|
|
3435
|
+
{
|
|
3436
|
+
type: "button",
|
|
3437
|
+
action_id: input.action_id,
|
|
3438
|
+
block_id: input.block_id ?? found?.block_id ?? slackId("", 5),
|
|
3439
|
+
text: found?.text ?? {
|
|
3440
|
+
type: "plain_text",
|
|
3441
|
+
text: input.text ?? input.action_id,
|
|
3442
|
+
emoji: true
|
|
3443
|
+
},
|
|
3444
|
+
value: input.value ?? found?.value,
|
|
3445
|
+
...found?.style ? { style: found.style } : {}
|
|
3446
|
+
}
|
|
3447
|
+
]
|
|
3448
|
+
});
|
|
3449
|
+
const ack = await this.hub.send("interactive", payload, true);
|
|
3450
|
+
await this.flush();
|
|
3451
|
+
return ack;
|
|
3452
|
+
}
|
|
3453
|
+
async submitView(input) {
|
|
3454
|
+
const user = input.user ? this.user(input.user) : this.defaultHuman();
|
|
3455
|
+
const views = [...this.store.views.values()];
|
|
3456
|
+
const view = input.view_id ? this.store.views.get(input.view_id) : input.callback_id ? views.reverse().find((v) => v.callback_id === input.callback_id) : views.at(-1);
|
|
3457
|
+
if (!view)
|
|
3458
|
+
throw new Error("no open view to submit");
|
|
3459
|
+
view.state = { values: input.values };
|
|
3460
|
+
const payload = viewSubmissionPayload(this.store, {
|
|
3461
|
+
user,
|
|
3462
|
+
view,
|
|
3463
|
+
values: input.values,
|
|
3464
|
+
triggerId: this.issueTriggerId()
|
|
3465
|
+
});
|
|
3466
|
+
const ack = await this.hub.send("interactive", payload, true);
|
|
3467
|
+
const response = ack.payload ?? {};
|
|
3468
|
+
if (response.response_action === "errors") {
|
|
3469
|
+
view.state = { values: input.values };
|
|
3470
|
+
} else if (response.response_action === "update" && response.view) {
|
|
3471
|
+
Object.assign(view, {
|
|
3472
|
+
callback_id: response.view.callback_id ?? view.callback_id,
|
|
3473
|
+
private_metadata: response.view.private_metadata ?? view.private_metadata,
|
|
3474
|
+
title: response.view.title ?? view.title,
|
|
3475
|
+
submit: response.view.submit ?? view.submit,
|
|
3476
|
+
blocks: Array.isArray(response.view.blocks) ? response.view.blocks : view.blocks
|
|
3477
|
+
});
|
|
3478
|
+
} else if (response.response_action === "push" && response.view) {
|
|
3479
|
+
this.store.openView({
|
|
3480
|
+
type: "modal",
|
|
3481
|
+
callback_id: response.view.callback_id,
|
|
3482
|
+
private_metadata: response.view.private_metadata ?? "",
|
|
3483
|
+
title: response.view.title,
|
|
3484
|
+
submit: response.view.submit,
|
|
3485
|
+
close: response.view.close,
|
|
3486
|
+
blocks: Array.isArray(response.view.blocks) ? response.view.blocks : [],
|
|
3487
|
+
opened_by: user.id,
|
|
3488
|
+
trigger_id: payload.trigger_id,
|
|
3489
|
+
state: { values: {} },
|
|
3490
|
+
clear_on_close: false,
|
|
3491
|
+
notify_on_close: false
|
|
3492
|
+
});
|
|
3493
|
+
} else if (response.response_action === "clear") {
|
|
3494
|
+
this.store.views.clear();
|
|
3495
|
+
} else {
|
|
3496
|
+
this.store.views.delete(view.id);
|
|
3497
|
+
}
|
|
3498
|
+
await this.flush();
|
|
3499
|
+
return ack;
|
|
3500
|
+
}
|
|
3501
|
+
async startAssistantThread(input = {}) {
|
|
3502
|
+
const user = input.user ? this.user(input.user) : this.defaultHuman();
|
|
3503
|
+
const dm = this.store.openDm(user.id);
|
|
3504
|
+
const root = this.store.addMessage({
|
|
3505
|
+
channel: dm.id,
|
|
3506
|
+
user: user.id,
|
|
3507
|
+
subtype: "assistant_app_thread",
|
|
3508
|
+
text: "New chat"
|
|
3509
|
+
});
|
|
3510
|
+
const threadTs = root.ts;
|
|
3511
|
+
if (this.isSubscribed("assistant_thread_started")) {
|
|
3512
|
+
await this.track(this.hub.send("events_api", eventCallback(this.store, assistantThreadStartedEvent(this.store, dm, user.id, threadTs, input.context))));
|
|
3513
|
+
}
|
|
3514
|
+
return { channel: dm.id, thread_ts: threadTs };
|
|
3515
|
+
}
|
|
3516
|
+
async changeAssistantContext(input) {
|
|
3517
|
+
const user = input.user ? this.user(input.user) : this.defaultHuman();
|
|
3518
|
+
const dm = this.resolveChannel(input.channel);
|
|
3519
|
+
await this.track(this.hub.send("events_api", eventCallback(this.store, assistantThreadContextChangedEvent(this.store, dm, user.id, input.thread_ts, input.context))));
|
|
3520
|
+
}
|
|
3521
|
+
assistantThread(channel, thread_ts) {
|
|
3522
|
+
return this.store.assistantThreads.get(`${this.resolveChannel(channel).id}:${thread_ts}`) ?? {};
|
|
3523
|
+
}
|
|
3524
|
+
messages(channel) {
|
|
3525
|
+
return [...this.store.messages.get(this.resolveChannel(channel).id) ?? []];
|
|
3526
|
+
}
|
|
3527
|
+
thread(channel, ts) {
|
|
3528
|
+
return this.store.replies(this.resolveChannel(channel).id, ts, { limit: 1000 }).items;
|
|
3529
|
+
}
|
|
3530
|
+
ephemeralMessages(channel) {
|
|
3531
|
+
const id = channel ? this.resolveChannel(channel).id : undefined;
|
|
3532
|
+
return this.store.ephemerals.filter((m) => !id || m.channel === id);
|
|
3533
|
+
}
|
|
3534
|
+
injectFault(fault) {
|
|
3535
|
+
this.faults.push({ ...fault, remaining: fault.times ?? 1 });
|
|
3536
|
+
}
|
|
3537
|
+
deliveries(name) {
|
|
3538
|
+
return name ? this.hub.history.filter((d) => d.name === name) : [...this.hub.history];
|
|
3539
|
+
}
|
|
3540
|
+
apiCalls(method) {
|
|
3541
|
+
return method ? this.store.apiCalls.filter((c) => c.method === method) : [...this.store.apiCalls];
|
|
3542
|
+
}
|
|
3543
|
+
matches(m, q) {
|
|
3544
|
+
if (m.ephemeral_user && !q.ephemeral)
|
|
3545
|
+
return false;
|
|
3546
|
+
if (q.channel && m.channel !== this.resolveChannel(q.channel).id)
|
|
3547
|
+
return false;
|
|
3548
|
+
if (q.thread_ts && m.thread_ts !== q.thread_ts && m.ts !== q.thread_ts)
|
|
3549
|
+
return false;
|
|
3550
|
+
if (q.from === "bot" && !this.store.isBotUser(m.user))
|
|
3551
|
+
return false;
|
|
3552
|
+
if (q.from === "human" && this.store.isBotUser(m.user))
|
|
3553
|
+
return false;
|
|
3554
|
+
if (q.from && q.from !== "bot" && q.from !== "human" && m.user !== this.user(q.from).id)
|
|
3555
|
+
return false;
|
|
3556
|
+
if (q.event_type && m.metadata?.event_type !== q.event_type)
|
|
3557
|
+
return false;
|
|
3558
|
+
if (typeof q.text === "string" && !m.text.includes(q.text))
|
|
3559
|
+
return false;
|
|
3560
|
+
if (q.text instanceof RegExp && !q.text.test(m.text))
|
|
3561
|
+
return false;
|
|
3562
|
+
return true;
|
|
3563
|
+
}
|
|
3564
|
+
findMessages(q) {
|
|
3565
|
+
const all = [...this.store.messages.values()].flat().concat(q.ephemeral ? this.store.ephemerals : []);
|
|
3566
|
+
return all.filter((m) => this.matches(m, q));
|
|
3567
|
+
}
|
|
3568
|
+
waitForMessage(q, opts = {}) {
|
|
3569
|
+
const test = typeof q === "function" ? q : (m) => this.matches(m, q);
|
|
3570
|
+
const after = opts.after ? Number(opts.after) : -1;
|
|
3571
|
+
const existing = [...this.store.messages.values()].flat().concat(this.store.ephemerals).find((m) => Number(m.ts) > after && test(m));
|
|
3572
|
+
if (existing)
|
|
3573
|
+
return Promise.resolve(existing);
|
|
3574
|
+
return new Promise((resolve, reject) => {
|
|
3575
|
+
const timer = setTimeout(() => {
|
|
3576
|
+
off();
|
|
3577
|
+
reject(new Error(`timed out after ${opts.timeoutMs ?? 1e4}ms waiting for a matching message`));
|
|
3578
|
+
}, opts.timeoutMs ?? 1e4);
|
|
3579
|
+
const off = this.store.onChange((c) => {
|
|
3580
|
+
if ((c.kind === "message.add" || c.kind === "message.update") && Number(c.message.ts) > after && test(c.message)) {
|
|
3581
|
+
clearTimeout(timer);
|
|
3582
|
+
off();
|
|
3583
|
+
resolve(c.message);
|
|
3584
|
+
}
|
|
3585
|
+
});
|
|
3586
|
+
});
|
|
3587
|
+
}
|
|
3588
|
+
waitForApiCall(method, opts = {}) {
|
|
3589
|
+
const found = this.store.apiCalls.find((c) => c.method === method && (opts.where?.(c) ?? true));
|
|
3590
|
+
if (found)
|
|
3591
|
+
return Promise.resolve(found);
|
|
3592
|
+
return new Promise((resolve, reject) => {
|
|
3593
|
+
const timer = setTimeout(() => {
|
|
3594
|
+
off();
|
|
3595
|
+
reject(new Error(`timed out waiting for ${method}`));
|
|
3596
|
+
}, opts.timeoutMs ?? 1e4);
|
|
3597
|
+
const off = this.store.onChange((c) => {
|
|
3598
|
+
if (c.kind === "api.call" && c.call.method === method && (opts.where?.(c.call) ?? true)) {
|
|
3599
|
+
clearTimeout(timer);
|
|
3600
|
+
off();
|
|
3601
|
+
resolve(c.call);
|
|
3602
|
+
}
|
|
3603
|
+
});
|
|
3604
|
+
});
|
|
3605
|
+
}
|
|
3606
|
+
waitForConnection(timeoutMs = 15000) {
|
|
3607
|
+
return this.hub.waitForConnection(timeoutMs);
|
|
3608
|
+
}
|
|
3609
|
+
disconnectSockets(reason) {
|
|
3610
|
+
this.hub.disconnectAll(reason);
|
|
3611
|
+
}
|
|
3612
|
+
onChange(listener) {
|
|
3613
|
+
return this.store.onChange(listener);
|
|
3614
|
+
}
|
|
3615
|
+
async handleAdmin(req, path, url) {
|
|
3616
|
+
const json = (body2, status = 200) => Response.json(body2, { status });
|
|
3617
|
+
const body = req.method === "POST" ? await req.json().catch(() => ({})) : {};
|
|
3618
|
+
try {
|
|
3619
|
+
if (path === "state") {
|
|
3620
|
+
return json({
|
|
3621
|
+
team: this.store.team,
|
|
3622
|
+
app: this.store.app,
|
|
3623
|
+
bot: { userId: this.store.bot.userId, botId: this.store.bot.botId },
|
|
3624
|
+
connections: this.hub.connectionCount,
|
|
3625
|
+
users: [...this.store.users.values()],
|
|
3626
|
+
channels: [...this.store.channels.values()]
|
|
3627
|
+
});
|
|
3628
|
+
}
|
|
3629
|
+
if (path === "channels" && req.method === "POST")
|
|
3630
|
+
return json(this.addChannel(body));
|
|
3631
|
+
if (path === "users" && req.method === "POST")
|
|
3632
|
+
return json(this.addUser(body));
|
|
3633
|
+
if (path === "messages" && req.method === "POST") {
|
|
3634
|
+
const input = body;
|
|
3635
|
+
return json(wireMessage(await this.postMessage({ ...input, text: this.resolveMentions(input.text ?? "") })));
|
|
3636
|
+
}
|
|
3637
|
+
if (path === "messages" && req.method === "GET") {
|
|
3638
|
+
const q = Object.fromEntries(url.searchParams);
|
|
3639
|
+
return json(this.findMessages(q).map(wireMessage));
|
|
3640
|
+
}
|
|
3641
|
+
if (path === "commands" && req.method === "POST") {
|
|
3642
|
+
const r = await this.slashCommand(body);
|
|
3643
|
+
return json({ ack: r.ack, response: r.response ? wireMessage(r.response) : undefined });
|
|
3644
|
+
}
|
|
3645
|
+
if (path === "actions" && req.method === "POST")
|
|
3646
|
+
return json(await this.clickButton(body));
|
|
3647
|
+
if (path === "views/submit" && req.method === "POST")
|
|
3648
|
+
return json(await this.submitView(body));
|
|
3649
|
+
if (path === "assistant/start" && req.method === "POST")
|
|
3650
|
+
return json(await this.startAssistantThread(body));
|
|
3651
|
+
if (path === "reactions" && req.method === "POST") {
|
|
3652
|
+
await this.addReaction(body);
|
|
3653
|
+
return json({ ok: true });
|
|
3654
|
+
}
|
|
3655
|
+
if (path === "api-calls")
|
|
3656
|
+
return json(this.apiCalls(url.searchParams.get("method") ?? undefined));
|
|
3657
|
+
if (path === "disconnect" && req.method === "POST") {
|
|
3658
|
+
this.disconnectSockets(body.reason);
|
|
3659
|
+
return json({ ok: true });
|
|
3660
|
+
}
|
|
3661
|
+
const m = /^channels\/([^/]+)(?:\/threads\/([^/]+))?$/.exec(path);
|
|
3662
|
+
if (m)
|
|
3663
|
+
return json((m[2] ? this.thread(m[1], m[2]) : this.messages(m[1])).map(wireMessage));
|
|
3664
|
+
return json({ ok: false, error: "unknown_admin_route" }, 404);
|
|
3665
|
+
} catch (e) {
|
|
3666
|
+
return json({ ok: false, error: e instanceof SlackApiError ? e.code : String(e) }, 400);
|
|
3667
|
+
}
|
|
3668
|
+
}
|
|
3669
|
+
}
|
|
3670
|
+
function slackError(code, extra = {}) {
|
|
3671
|
+
return Response.json({ ok: false, error: code, ...extra });
|
|
3672
|
+
}
|
|
3673
|
+
function findButton(blocks, actionId) {
|
|
3674
|
+
for (const b of blocks ?? []) {
|
|
3675
|
+
const elements = [
|
|
3676
|
+
...Array.isArray(b.elements) ? b.elements : [],
|
|
3677
|
+
...b.accessory ? [b.accessory] : []
|
|
3678
|
+
];
|
|
3679
|
+
for (const el of elements) {
|
|
3680
|
+
if (el.type === "button" && el.action_id === actionId) {
|
|
3681
|
+
return {
|
|
3682
|
+
block_id: b.block_id,
|
|
3683
|
+
text: el.text,
|
|
3684
|
+
value: el.value,
|
|
3685
|
+
style: el.style
|
|
3686
|
+
};
|
|
3687
|
+
}
|
|
3688
|
+
}
|
|
3689
|
+
}
|
|
3690
|
+
return;
|
|
3691
|
+
}
|
|
3692
|
+
|
|
3693
|
+
export { SlackApiError, Store, SlackMock };
|