@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.
@@ -0,0 +1,321 @@
1
+ // Slack mrkdwn -> HTML.
2
+ //
3
+ // Message text arrives with `&`, `<` and `>` already escaped by Slack, except
4
+ // inside the `<...>` control sequences (links, mentions, specials). The renderer
5
+ // therefore tokenises code spans and control sequences first, then normalises the
6
+ // remaining entities back to characters and escapes them once. That keeps
7
+ // `&amp;` a single `&amp;` in the output instead of `&amp;amp;`.
8
+
9
+ import type { SlackChannel, SlackUser } from "../types.ts";
10
+
11
+ export interface RenderContext {
12
+ users: Map<string, SlackUser>;
13
+ channels: Map<string, SlackChannel>;
14
+ botUserId: string;
15
+ }
16
+
17
+ export function escapeHtml(s: string): string {
18
+ return s
19
+ .replace(/&/g, "&amp;")
20
+ .replace(/</g, "&lt;")
21
+ .replace(/>/g, "&gt;")
22
+ .replace(/"/g, "&quot;");
23
+ }
24
+
25
+ /** Slack-escaped text (`&amp;` `&lt;` `&gt;`) back to plain characters, one pass. */
26
+ function unescapeSlack(s: string): string {
27
+ return s.replace(/&(amp|lt|gt|quot);/g, (_m, name: string) =>
28
+ name === "amp" ? "&" : name === "lt" ? "<" : name === "gt" ? ">" : '"',
29
+ );
30
+ }
31
+
32
+ /** Escape text that came off the wire already Slack-escaped. */
33
+ function reEscape(s: string): string {
34
+ return escapeHtml(unescapeSlack(s));
35
+ }
36
+
37
+ const EMOJI: Record<string, string> = {
38
+ eyes: "👀",
39
+ white_check_mark: "✅",
40
+ x: "❌",
41
+ heavy_plus_sign: "➕",
42
+ heavy_minus_sign: "➖",
43
+ heavy_multiplication_x: "✖️",
44
+ zap: "⚡",
45
+ speech_balloon: "💬",
46
+ robot_face: "🤖",
47
+ gear: "⚙️",
48
+ rocket: "🚀",
49
+ star: "⭐",
50
+ crystal_ball: "🔮",
51
+ bulb: "💡",
52
+ wrench: "🔧",
53
+ hammer: "🔨",
54
+ crown: "👑",
55
+ tada: "🎉",
56
+ warning: "⚠️",
57
+ hourglass: "⌛",
58
+ hourglass_flowing_sand: "⏳",
59
+ thumbsup: "👍",
60
+ thumbsdown: "👎",
61
+ "+1": "👍",
62
+ "-1": "👎",
63
+ heavy_check_mark: "✔️",
64
+ question: "❓",
65
+ grey_question: "❔",
66
+ exclamation: "❗",
67
+ white_circle: "⚪",
68
+ large_blue_circle: "🔵",
69
+ black_circle: "⚫",
70
+ red_circle: "🔴",
71
+ large_green_circle: "🟢",
72
+ large_yellow_circle: "🟡",
73
+ fire: "🔥",
74
+ sparkles: "✨",
75
+ memo: "📝",
76
+ clipboard: "📋",
77
+ mag: "🔍",
78
+ mag_right: "🔎",
79
+ link: "🔗",
80
+ lock: "🔒",
81
+ unlock: "🔓",
82
+ bell: "🔔",
83
+ package: "📦",
84
+ construction: "🚧",
85
+ bug: "🐛",
86
+ boom: "💥",
87
+ pencil2: "✏️",
88
+ scroll: "📜",
89
+ page_facing_up: "📄",
90
+ file_folder: "📁",
91
+ card_index_dividers: "🗂️",
92
+ paperclip: "📎",
93
+ bar_chart: "📊",
94
+ chart_with_upwards_trend: "📈",
95
+ calendar: "📅",
96
+ clock1: "🕐",
97
+ arrow_right: "➡️",
98
+ arrow_left: "⬅️",
99
+ arrow_up: "⬆️",
100
+ arrow_down: "⬇️",
101
+ arrow_right_hook: "↪️",
102
+ repeat: "🔁",
103
+ arrows_counterclockwise: "🔄",
104
+ recycle: "♻️",
105
+ no_entry: "⛔",
106
+ no_entry_sign: "🚫",
107
+ stop_sign: "🛑",
108
+ pause_button: "⏸️",
109
+ information_source: "ℹ️",
110
+ wave: "👋",
111
+ pray: "🙏",
112
+ muscle: "💪",
113
+ brain: "🧠",
114
+ dart: "🎯",
115
+ trophy: "🏆",
116
+ medal: "🏅",
117
+ checkered_flag: "🏁",
118
+ ok_hand: "👌",
119
+ point_right: "👉",
120
+ clap: "👏",
121
+ raised_hands: "🙌",
122
+ thinking_face: "🤔",
123
+ "100": "💯",
124
+ green_heart: "💚",
125
+ thread: "🧵",
126
+ satellite_antenna: "📡",
127
+ inbox_tray: "📥",
128
+ outbox_tray: "📤",
129
+ incoming_envelope: "📨",
130
+ mailbox_with_no_mail: "📭",
131
+ envelope: "✉️",
132
+ test_tube: "🧪",
133
+ ship: "🚢",
134
+ sos: "🆘",
135
+ small_blue_diamond: "🔹",
136
+ small_orange_diamond: "🔸",
137
+ black_small_square: "▪️",
138
+ white_small_square: "▫️",
139
+ };
140
+
141
+ /** Unicode character for a Slack emoji shortcode, or undefined when unknown. */
142
+ export function emojiChar(name: string): string | undefined {
143
+ return EMOJI[name.replace(/^:|:$/g, "").replace(/::skin-tone-\d$/, "")];
144
+ }
145
+
146
+ /** Codepoint list from a rich_text emoji element, e.g. "1f44b" or "1f1ea-1f1f8". */
147
+ export function emojiFromUnicode(code: string): string | undefined {
148
+ const points = code.split("-").map((p) => Number.parseInt(p, 16));
149
+ if (points.some((p) => !Number.isFinite(p))) return undefined;
150
+ try {
151
+ return String.fromCodePoint(...points);
152
+ } catch {
153
+ return undefined;
154
+ }
155
+ }
156
+
157
+ /** Replace `:shortcode:` in already-escaped HTML text. */
158
+ function renderEmoji(html: string): string {
159
+ return html.replace(/:([a-z][a-z0-9_+'-]*|\+1|-1|100):/g, (m, name: string) => {
160
+ const char = emojiChar(name);
161
+ return char ?? `<span class="sm-emoji-name">${m}</span>`;
162
+ });
163
+ }
164
+
165
+ export function displayName(user: SlackUser): string {
166
+ return user.profile.display_name || user.real_name || user.name;
167
+ }
168
+
169
+ function pill(text: string): string {
170
+ return `<span class="sm-pill">${escapeHtml(text)}</span>`;
171
+ }
172
+
173
+ function isSafeUrl(url: string): boolean {
174
+ return /^(https?:\/\/|mailto:|tel:)/i.test(url);
175
+ }
176
+
177
+ /** One `<...>` control sequence: mention, channel, special or link. */
178
+ function renderControl(inner: string, ctx: RenderContext): string {
179
+ const bar = inner.indexOf("|");
180
+ const head = bar >= 0 ? inner.slice(0, bar) : inner;
181
+ const label = bar >= 0 ? inner.slice(bar + 1) : "";
182
+
183
+ if (head.startsWith("@")) {
184
+ const id = head.slice(1);
185
+ const user = ctx.users.get(id);
186
+ return pill(`@${user ? displayName(user) : label || id}`);
187
+ }
188
+ if (head.startsWith("#")) {
189
+ const id = head.slice(1);
190
+ const channel = ctx.channels.get(id);
191
+ return pill(`#${channel ? channel.name : label.replace(/^#/, "") || id}`);
192
+ }
193
+ if (head.startsWith("!")) {
194
+ const cmd = head.slice(1);
195
+ if (cmd === "here" || cmd === "channel" || cmd === "everyone") return pill(`@${cmd}`);
196
+ if (cmd.startsWith("subteam^")) {
197
+ const handle = label || cmd.slice("subteam^".length);
198
+ return pill(handle.startsWith("@") ? handle : `@${handle}`);
199
+ }
200
+ if (cmd.startsWith("date^")) {
201
+ if (label) return renderEmoji(reEscape(label));
202
+ const secs = Number(cmd.split("^")[1]);
203
+ return Number.isFinite(secs) ? escapeHtml(new Date(secs * 1000).toISOString()) : "";
204
+ }
205
+ return pill(`@${cmd}`);
206
+ }
207
+ if (isSafeUrl(head)) {
208
+ const shown = label || head.replace(/^mailto:/i, "");
209
+ const attrs = /^mailto:/i.test(head) ? "" : ' target="_blank" rel="noopener"';
210
+ return `<a class="sm-link" href="${escapeHtml(head)}"${attrs}>${renderEmoji(reEscape(shown))}</a>`;
211
+ }
212
+ return escapeHtml(`<${unescapeSlack(inner)}>`);
213
+ }
214
+
215
+ function preHtml(body: string): string {
216
+ let code = body.replace(/^\n/, "").replace(/\n$/, "");
217
+ // Strip a leading language tag (```ts) when the fence spans several lines.
218
+ if (code.includes("\n")) code = code.replace(/^[a-z][a-z0-9+#-]{0,11}\n/, "");
219
+ return `<pre class="sm-pre">${reEscape(code)}</pre>`;
220
+ }
221
+
222
+ const BOUND_L = "(^|[\\s(\\[{'\"\\uE000\\uE001])";
223
+ const BOUND_R = "(?=$|[\\s.,;:!?)\\]}'\"\\uE000\\uE001])";
224
+
225
+ function styleRule(marker: string): RegExp {
226
+ const m = marker.replace(/[*]/g, "\\*");
227
+ return new RegExp(`${BOUND_L}${m}(?![\\s${m}])([^${m}\\n]*[^\\s${m}])${m}${BOUND_R}`, "g");
228
+ }
229
+
230
+ const RULES: Array<[RegExp, string]> = [
231
+ [styleRule("*"), "strong"],
232
+ [styleRule("~"), "s"],
233
+ [styleRule("_"), "em"],
234
+ ];
235
+
236
+ function inlineStyles(s: string): string {
237
+ let out = s;
238
+ for (const [re, tag] of RULES) out = out.replace(re, `$1<${tag}>$2</${tag}>`);
239
+ return out;
240
+ }
241
+
242
+ interface Group {
243
+ kind: "p" | "quote" | "ul" | "ol";
244
+ items: Array<{ html: string; indent: number }>;
245
+ }
246
+
247
+ const QUOTE = /^\s*(?:&gt;|>)\s?/;
248
+ const BULLET = /^(\s*)(?:•|-|\*)\s+(.*)$/;
249
+ const NUMBER = /^(\s*)\d+[.)]\s+(.*)$/;
250
+
251
+ /** Split lines into blockquote / list / paragraph groups and emit HTML. */
252
+ function blockify(text: string): string {
253
+ const groups: Group[] = [];
254
+ const push = (kind: Group["kind"], html: string, indent = 0) => {
255
+ const last = groups[groups.length - 1];
256
+ if (last?.kind === kind) last.items.push({ html, indent });
257
+ else groups.push({ kind, items: [{ html, indent }] });
258
+ };
259
+ for (const line of text.split("\n")) {
260
+ const bullet = BULLET.exec(line);
261
+ const numbered = bullet ? null : NUMBER.exec(line);
262
+ if (QUOTE.test(line)) push("quote", line.replace(QUOTE, ""));
263
+ else if (bullet)
264
+ push("ul", bullet[2] ?? "", Math.min(4, Math.floor((bullet[1]?.length ?? 0) / 2)));
265
+ else if (numbered)
266
+ push("ol", numbered[2] ?? "", Math.min(4, Math.floor((numbered[1]?.length ?? 0) / 2)));
267
+ else push("p", line);
268
+ }
269
+ return groups
270
+ .map((g) => {
271
+ if (g.kind === "p") return g.items.map((i) => i.html).join("<br>");
272
+ const inner = g.items
273
+ .map(
274
+ (i) => `<li${i.indent ? ` style="margin-left:${i.indent * 18}px"` : ""}>${i.html}</li>`,
275
+ )
276
+ .join("");
277
+ if (g.kind === "quote")
278
+ return `<blockquote class="sm-quote">${g.items.map((i) => i.html).join("<br>")}</blockquote>`;
279
+ return `<${g.kind} class="sm-list">${inner}</${g.kind}>`;
280
+ })
281
+ .join("");
282
+ }
283
+
284
+ const BLOCK_TAGS = "pre|blockquote|ul|ol";
285
+
286
+ function tidy(html: string): string {
287
+ return html
288
+ .replace(new RegExp(`<br>\\s*(<(?:${BLOCK_TAGS})\\b)`, "g"), "$1")
289
+ .replace(new RegExp(`(</(?:${BLOCK_TAGS})>)\\s*<br>`, "g"), "$1");
290
+ }
291
+
292
+ /** Render Slack mrkdwn to HTML. */
293
+ export function mrkdwnToHtml(text: string, ctx: RenderContext): string {
294
+ if (!text) return "";
295
+ const tokens: string[] = [];
296
+ const hold = (html: string): string => {
297
+ tokens.push(html);
298
+ return `\uE000${tokens.length - 1}\uE001`;
299
+ };
300
+
301
+ let s = text.replace(/\r\n/g, "\n");
302
+ s = s.replace(/```([\s\S]*?)```/g, (_m, body: string) => hold(preHtml(body)));
303
+ s = s.replace(/`([^`\n]+)`/g, (_m, body: string) =>
304
+ hold(`<code class="sm-code">${reEscape(body)}</code>`),
305
+ );
306
+ s = s.replace(/<([^<>\n]*)>/g, (_m, inner: string) => hold(renderControl(inner, ctx)));
307
+ s = renderEmoji(reEscape(s));
308
+ s = inlineStyles(s);
309
+ s = blockify(s);
310
+ // Tokens can nest (a code span inside a link label), so expand recursively.
311
+ // Every token only refers to earlier tokens, which bounds the recursion.
312
+ const expand = (html: string): string =>
313
+ html.replace(/\uE000(\d+)\uE001/g, (_m, i: string) => expand(tokens[Number(i)] ?? ""));
314
+ return tidy(expand(s));
315
+ }
316
+
317
+ /** plain_text objects: escaping and emoji only, no formatting. */
318
+ export function plainTextToHtml(text: string): string {
319
+ if (!text) return "";
320
+ return renderEmoji(reEscape(text.replace(/\r\n/g, "\n"))).replace(/\n/g, "<br>");
321
+ }
@@ -0,0 +1,59 @@
1
+ import { existsSync } from "node:fs";
2
+
3
+ const CHROME_CANDIDATES = [
4
+ process.env.SLACK_MOCK_CHROME,
5
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
6
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
7
+ "/usr/bin/google-chrome",
8
+ "/usr/bin/google-chrome-stable",
9
+ "/usr/bin/chromium",
10
+ "/usr/bin/chromium-browser",
11
+ ];
12
+
13
+ /** Locate a Chrome/Chromium binary for headless screenshots, or undefined. */
14
+ export function findChrome(): string | undefined {
15
+ for (const c of CHROME_CANDIDATES) if (c && existsSync(c)) return c;
16
+ const fromPath = Bun.which("google-chrome") ?? Bun.which("chromium") ?? Bun.which("chrome");
17
+ return fromPath ?? undefined;
18
+ }
19
+
20
+ export interface ScreenshotOptions {
21
+ out: string;
22
+ width?: number;
23
+ height?: number;
24
+ timeoutMs?: number;
25
+ }
26
+
27
+ /**
28
+ * Render a URL to a PNG with headless Chrome. Appends `screenshot=1` so the
29
+ * mock's pages drop their navigation chrome.
30
+ */
31
+ export async function screenshot(url: string, opts: ScreenshotOptions): Promise<string> {
32
+ const chrome = findChrome();
33
+ if (!chrome)
34
+ throw new Error("no Chrome/Chromium binary found; set SLACK_MOCK_CHROME=/path/to/chrome");
35
+ const target = new URL(url);
36
+ if (!target.searchParams.has("screenshot")) target.searchParams.set("screenshot", "1");
37
+ const proc = Bun.spawn(
38
+ [
39
+ chrome,
40
+ "--headless=new",
41
+ "--disable-gpu",
42
+ "--hide-scrollbars",
43
+ "--no-first-run",
44
+ "--no-default-browser-check",
45
+ `--window-size=${opts.width ?? 800},${opts.height ?? 1000}`,
46
+ `--screenshot=${opts.out}`,
47
+ target.toString(),
48
+ ],
49
+ { stdout: "ignore", stderr: "pipe" },
50
+ );
51
+ const timer = setTimeout(() => proc.kill(), opts.timeoutMs ?? 30_000);
52
+ const code = await proc.exited;
53
+ clearTimeout(timer);
54
+ if (code !== 0 || !existsSync(opts.out)) {
55
+ const err = await new Response(proc.stderr).text();
56
+ throw new Error(`chrome exited with ${code}: ${err.slice(-500)}`);
57
+ }
58
+ return opts.out;
59
+ }