@desplega.ai/slack-mock 0.5.0 → 0.6.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.
@@ -171,7 +171,10 @@ function richElement(v: unknown, ctx: RenderContext): string {
171
171
  case "emoji": {
172
172
  const char =
173
173
  emojiChar(str(el.name)) ?? (el.unicode ? emojiFromUnicode(str(el.unicode)) : undefined);
174
- return char ?? `<span class="sm-emoji-name">:${escapeHtml(str(el.name))}:</span>`;
174
+ // `unicode` is caller-supplied codepoints, so the decoded string can be markup.
175
+ return char
176
+ ? escapeHtml(char)
177
+ : `<span class="sm-emoji-name">:${escapeHtml(str(el.name))}:</span>`;
175
178
  }
176
179
  case "date":
177
180
  return plainTextToHtml(str(el.fallback) || str(el.timestamp));
@@ -269,6 +272,162 @@ function videoBlock(block: Rec, ctx: RenderContext): string {
269
272
  return `<div class="sm-block sm-video">${url ? `<a class="sm-video-link" href="${url}" target="_blank" rel="noopener">${inner}</a>` : inner}</div>`;
270
273
  }
271
274
 
275
+ // ------------------------------------------------------- tables and charts
276
+
277
+ function tableCell(v: unknown, ctx: RenderContext): string {
278
+ const cell = rec(v);
279
+ if (!cell) return "";
280
+ if (str(cell.type) === "rich_text")
281
+ return arr(cell.elements)
282
+ .map((e) => richSection(e, ctx))
283
+ .join("");
284
+ if (str(cell.type) === "action_cell") {
285
+ const el = rec(cell.element);
286
+ return el && str(el.type) === "button" ? button(el, ctx) : tableCell(cell.fallback, ctx);
287
+ }
288
+ return plainTextToHtml(str(cell.text) || (cell.value === undefined ? "" : String(cell.value)));
289
+ }
290
+
291
+ /** `table` and `data_table`. Only data_table documents the first row as a header row. */
292
+ function tableBlock(block: Rec, ctx: RenderContext): string {
293
+ const settings = arr(block.column_settings).map(rec);
294
+ const rows = arr(block.rows).map(arr);
295
+ // data_table pages at 5 rows unless page_size says otherwise; table never pages.
296
+ // Rendering also runs on unvalidated blocks, so an out-of-range page_size falls back to 5.
297
+ const ps = Number(block.page_size);
298
+ const pageSize = block.type === "data_table" ? (Number.isInteger(ps) && ps >= 1 ? ps : 5) : 0;
299
+ const head = block.type === "data_table" ? 1 : 0;
300
+ const body = rows.slice(head);
301
+ // Every page is rendered; pages after the first start hidden and the pager
302
+ // buttons (uiScript) flip them, so no row is out of reach.
303
+ const per = pageSize || body.length || 1;
304
+ const pages: unknown[][][] = [];
305
+ for (let i = 0; i < body.length || i === 0; i += per) pages.push(body.slice(i, i + per));
306
+ const row = (cells: unknown[], tag: "th" | "td") =>
307
+ `<tr>${cells
308
+ .map((c, i) => {
309
+ const align = str(settings[i]?.align);
310
+ const cls = [
311
+ align === "center" || align === "right" ? `sm-ta-${align}` : "",
312
+ settings[i]?.is_wrapped === true ? "sm-td-wrap" : "",
313
+ ].filter(Boolean);
314
+ return `<${tag}${cls.length ? ` class="${cls.join(" ")}"` : ""}>${tableCell(c, ctx)}</${tag}>`;
315
+ })
316
+ .join("")}</tr>`;
317
+ const caption = str(block.caption)
318
+ ? `<div class="sm-table-caption">${plainTextToHtml(str(block.caption))}</div>`
319
+ : "";
320
+ const paged = pages.length > 1;
321
+ const range = (p: number) =>
322
+ `${p * per + 1}–${p * per + (pages[p]?.length ?? 0)} of ${body.length}`;
323
+ const pager = paged
324
+ ? `<div class="sm-table-pager"><button type="button" class="sm-pager-btn" data-step="-1" aria-label="Previous page" disabled>‹</button><span class="sm-pager-label">${range(0)}</span><button type="button" class="sm-pager-btn" data-step="1" aria-label="Next page">›</button></div>`
325
+ : "";
326
+ const tbodies = pages
327
+ .map(
328
+ (pg, p) =>
329
+ `<tbody${paged ? ` data-range="${range(p)}"` : ""}${p ? " hidden" : ""}>${pg.map((r) => row(r, "td")).join("")}</tbody>`,
330
+ )
331
+ .join("");
332
+ return `<div class="sm-block sm-table-block">${caption}<div class="sm-table-wrap"><table class="sm-bk-table">${head && rows.length ? `<thead>${row(rows[0] ?? [], "th")}</thead>` : ""}${tbodies}</table></div>${pager}</div>`;
333
+ }
334
+
335
+ const CHART_COLORS = ["#1264a3", "#2eb67d", "#ecb22e", "#e01e5a", "#36c5f0", "#7c3085"];
336
+ const color = (i: number) => CHART_COLORS[i % CHART_COLORS.length];
337
+ const num = (v: unknown) => (Number.isFinite(Number(v)) ? Number(v) : 0);
338
+ const svgText = (x: number, y: number, text: string, attrs = "") =>
339
+ `<text x="${x}" y="${y}" ${attrs}>${escapeHtml(text)}</text>`;
340
+
341
+ function legend(labels: string[]): string {
342
+ return `<div class="sm-chart-legend">${labels
343
+ .map(
344
+ (l, i) =>
345
+ `<span class="sm-chart-key"><i style="background:${color(i)}"></i>${escapeHtml(l)}</span>`,
346
+ )
347
+ .join("")}</div>`;
348
+ }
349
+
350
+ function pieChart(chart: Rec): string {
351
+ const segments = arr(chart.segments).map(rec);
352
+ const total = segments.reduce((t, s) => t + Math.max(0, num(s?.value)), 0) || 1;
353
+ let angle = -Math.PI / 2;
354
+ const slices = segments.map((s, i) => {
355
+ const frac = Math.max(0, num(s?.value)) / total;
356
+ if (frac >= 0.9999) return `<circle cx="100" cy="100" r="90" fill="${color(i)}"/>`;
357
+ const a0 = angle;
358
+ angle += frac * 2 * Math.PI;
359
+ const p = (a: number) => `${100 + 90 * Math.cos(a)} ${100 + 90 * Math.sin(a)}`;
360
+ return `<path d="M100 100 L${p(a0)} A90 90 0 ${frac > 0.5 ? 1 : 0} 1 ${p(angle)} Z" fill="${color(i)}"/>`;
361
+ });
362
+ return `<svg class="sm-chart-svg" viewBox="0 0 200 200" width="200" height="200">${slices.join("")}</svg>${legend(segments.map((s) => `${str(s?.label)} (${num(s?.value)})`))}`;
363
+ }
364
+
365
+ /** bar, line and area share axes: categories on x, a value scale on y that always spans 0. */
366
+ function seriesChart(chart: Rec, type: string): string {
367
+ const axis = rec(chart.axis_config) ?? {};
368
+ const series = arr(chart.series).map((s) => rec(s) ?? {});
369
+ const categories = arr(axis.categories).map(str);
370
+ const valueAt = (s: Rec, c: string) =>
371
+ num(rec(arr(s.data).find((p) => rec(p)?.label === c))?.value);
372
+ // Slack permits negative values, so the scale runs min..max and both include 0.
373
+ const values = series.flatMap((s) => categories.map((c) => valueAt(s, c)));
374
+ const min = Math.min(0, ...values);
375
+ const max = Math.max(min < 0 ? 0 : 1, ...values);
376
+ const [W, H, L, T, B] = [480, 220, 44, 10, 30];
377
+ const plotW = W - L - 10;
378
+ const plotH = H - T - B;
379
+ const y = (v: number) => T + plotH - ((v - min) / (max - min)) * plotH;
380
+ const zero = y(0);
381
+ const step = plotW / Math.max(1, categories.length);
382
+ const parts: string[] = [];
383
+ for (let k = 0; k <= 4; k++) {
384
+ const v = min + ((max - min) * k) / 4;
385
+ parts.push(
386
+ `<line x1="${L}" x2="${W - 10}" y1="${y(v)}" y2="${y(v)}" stroke="#e8e8e8"/>`,
387
+ svgText(L - 6, y(v) + 4, String(Math.round(v * 100) / 100), 'text-anchor="end"'),
388
+ );
389
+ }
390
+ categories.forEach((c, i) => {
391
+ parts.push(svgText(L + step * (i + 0.5), H - B + 16, c, 'text-anchor="middle"'));
392
+ });
393
+ series.forEach((s, si) => {
394
+ if (type === "bar") {
395
+ const bw = (step * 0.7) / Math.max(1, series.length);
396
+ categories.forEach((c, i) => {
397
+ const v = valueAt(s, c);
398
+ parts.push(
399
+ `<rect x="${L + step * i + step * 0.15 + bw * si}" y="${Math.min(zero, y(v))}" width="${bw}" height="${Math.abs(zero - y(v))}" fill="${color(si)}"/>`,
400
+ );
401
+ });
402
+ return;
403
+ }
404
+ const pts = categories.map((c, i) => `${L + step * (i + 0.5)},${y(valueAt(s, c))}`);
405
+ if (type === "area" && pts.length)
406
+ parts.push(
407
+ `<polygon points="${L + step * 0.5},${zero} ${pts.join(" ")} ${L + step * (categories.length - 0.5)},${zero}" fill="${color(si)}" fill-opacity=".25"/>`,
408
+ );
409
+ parts.push(
410
+ `<polyline points="${pts.join(" ")}" fill="none" stroke="${color(si)}" stroke-width="2"/>`,
411
+ );
412
+ });
413
+ const xLabel = str(axis.x_label);
414
+ const yLabel = str(axis.y_label);
415
+ const labels = `${yLabel ? `<div class="sm-chart-axis">${plainTextToHtml(yLabel)} ↑</div>` : ""}`;
416
+ return `${labels}<svg class="sm-chart-svg" viewBox="0 0 ${W} ${H}" width="${W}" height="${H}">${parts.join("")}<line x1="${L}" x2="${W - 10}" y1="${zero}" y2="${zero}" stroke="#bbb"/></svg>${xLabel ? `<div class="sm-chart-axis sm-chart-axis-x">${plainTextToHtml(xLabel)} →</div>` : ""}${legend(series.map((s) => str(s.name)))}`;
417
+ }
418
+
419
+ function dataVisualizationBlock(block: Rec): string {
420
+ const chart = rec(block.chart) ?? {};
421
+ const type = str(chart.type);
422
+ const body =
423
+ type === "pie"
424
+ ? pieChart(chart)
425
+ : type === "bar" || type === "line" || type === "area"
426
+ ? seriesChart(chart, type)
427
+ : unsupported(`chart ${type}`);
428
+ return `<div class="sm-block sm-chart" data-chart="${escapeHtml(type)}"><div class="sm-chart-title">${plainTextToHtml(str(block.title))}</div>${body}</div>`;
429
+ }
430
+
272
431
  function renderBlock(v: unknown, ctx: RenderContext): string {
273
432
  const block = rec(v);
274
433
  if (!block) return unsupported("block");
@@ -299,6 +458,11 @@ function renderBlock(v: unknown, ctx: RenderContext): string {
299
458
  return videoBlock(block, ctx);
300
459
  case "markdown":
301
460
  return `<div class="sm-block sm-markdown">${markdownToHtml(str(block.text), ctx)}</div>`;
461
+ case "table":
462
+ case "data_table":
463
+ return tableBlock(block, ctx);
464
+ case "data_visualization":
465
+ return dataVisualizationBlock(block);
302
466
  default:
303
467
  return `<div class="sm-block">${unsupported(str(block.type))}</div>`;
304
468
  }
@@ -217,6 +217,25 @@ a:hover{text-decoration:underline}
217
217
  .sm-video-title{font-size:14px;font-weight:700;margin-top:4px}
218
218
  .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}
219
219
  .sm-rt-section{margin:2px 0}
220
+ .sm-table-caption{font-size:13px;font-weight:700;color:#454245;margin-bottom:4px}
221
+ .sm-table-wrap{width:fit-content;overflow-x:auto;border:1px solid #ddd;border-radius:6px;max-width:100%}
222
+ .sm-bk-table{border-collapse:collapse;font-size:14px;line-height:20px}
223
+ .sm-bk-table th,.sm-bk-table td{padding:6px 12px;text-align:left;border-bottom:1px solid #e8e8e8;white-space:nowrap;vertical-align:top}
224
+ .sm-bk-table th{font-weight:700;background:#f8f8f8}
225
+ .sm-bk-table tr:last-child td{border-bottom:0}
226
+ .sm-bk-table .sm-ta-center{text-align:center}
227
+ .sm-bk-table .sm-ta-right{text-align:right}
228
+ .sm-bk-table .sm-td-wrap{white-space:normal}
229
+ .sm-table-pager{display:flex;align-items:center;gap:6px;font-size:12px;color:#616061;margin-top:4px}
230
+ .sm-pager-btn{border:1px solid #ddd;border-radius:4px;background:#fff;color:#1d1c1d;font-size:14px;line-height:16px;padding:0 6px;cursor:pointer}
231
+ .sm-pager-btn:disabled{color:#bbb;cursor:default}
232
+ .sm-chart{border:1px solid #ddd;border-radius:6px;padding:10px 12px;max-width:520px}
233
+ .sm-chart-title{font-size:14px;font-weight:700;margin-bottom:6px}
234
+ .sm-chart-svg{display:block;max-width:100%;height:auto;font-size:11px;fill:#616061}
235
+ .sm-chart-axis{font-size:11px;color:#616061}
236
+ .sm-chart-axis-x{text-align:center}
237
+ .sm-chart-legend{display:flex;flex-wrap:wrap;gap:4px 12px;font-size:12px;color:#454245;margin-top:6px}
238
+ .sm-chart-key i{display:inline-block;width:10px;height:10px;border-radius:2px;margin-right:4px;vertical-align:-1px}
220
239
 
221
240
  .sm-atts{margin-top:4px}
222
241
  .sm-att{border-left:4px solid #ddd;border-radius:2px;padding:2px 0 2px 12px;margin:6px 0;max-width:600px}
@@ -878,6 +897,7 @@ function fitViewport(){if(viewport&&viewport.scale!==1)return;var style=document
878
897
  fitViewport();addEventListener("resize",fitViewport);
879
898
  if(viewport){viewport.addEventListener("resize",fitViewport);viewport.addEventListener("scroll",fitViewport)}
880
899
  document.addEventListener("change",function(e){if(e.target.classList.contains("sm-channel-switch"))location.href=e.target.value});
900
+ document.addEventListener("click",function(e){var b=e.target.closest(".sm-pager-btn");if(!b)return;var block=b.closest(".sm-table-block"),pages=block.querySelectorAll("tbody"),cur=0;pages.forEach(function(t,i){if(!t.hidden)cur=i});var next=Math.min(Math.max(cur+Number(b.dataset.step),0),pages.length-1);pages.forEach(function(t,i){t.hidden=i!==next});block.querySelector(".sm-pager-label").textContent=pages[next].dataset.range;var btns=block.querySelectorAll(".sm-pager-btn");btns[0].disabled=next===0;btns[1].disabled=next===pages.length-1});
881
901
  var W="sm-panel-w",DEF=${JSON.stringify(panelWidth(opts))},FIXED=${opts.panelWidth ? "true" : "false"};
882
902
  ${autoScroll ? 'function scroll(){document.querySelectorAll(".sm-scroll").forEach(function(el){el.scrollTop=el.scrollHeight})}\nscroll();addEventListener("load",scroll);' : ""}
883
903
  var handle=document.querySelector(".sm-resize");
package/src/server.ts CHANGED
@@ -15,6 +15,11 @@ import {
15
15
  slashCommandPayload,
16
16
  viewSubmissionPayload,
17
17
  } from "./events.ts";
18
+ import {
19
+ HttpDelivery,
20
+ type HttpDeliveryOptions,
21
+ HttpDeliveryStoppedError,
22
+ } from "./http-delivery.ts";
18
23
  import { slackId } from "./ids.ts";
19
24
  import { renderPage } from "./render/index.ts";
20
25
  import {
@@ -101,6 +106,11 @@ export interface SlackMockOptions extends StoreOptions {
101
106
  * admin credential. `adminAuth` always implies it.
102
107
  */
103
108
  presenterAuth?: string;
109
+ /**
110
+ * Deliver events, slash commands and interactivity as signed HTTP requests to the app's request
111
+ * URLs instead of over Socket Mode (Slack's HTTP mode). The app needs no WebSocket connection.
112
+ */
113
+ httpDelivery?: HttpDeliveryOptions;
104
114
  log?: boolean | ((msg: string) => void);
105
115
  }
106
116
 
@@ -165,6 +175,11 @@ interface ResponseUrl {
165
175
  export class SlackMock {
166
176
  readonly store: Store;
167
177
  readonly hub: SocketModeHub;
178
+ /** Where deliveries go: the HTTP request URLs when `httpDelivery` is set, else the Socket Mode hub. */
179
+ readonly delivery: Pick<
180
+ SocketModeHub,
181
+ "send" | "connectionCount" | "history" | "waitForConnection"
182
+ >;
168
183
  readonly opts: SlackMockOptions;
169
184
  private server!: Server<ConnData>;
170
185
  private triggerIds = new Map<string, number>();
@@ -198,6 +213,9 @@ export class SlackMock {
198
213
  maxRetries: opts.maxRetries,
199
214
  log: this.log,
200
215
  });
216
+ this.delivery = opts.httpDelivery
217
+ ? new HttpDelivery({ log: this.log, ...opts.httpDelivery })
218
+ : this.hub;
201
219
  this.subscribed = new Set(
202
220
  opts.subscribedEvents ??
203
221
  manifest?.settings?.event_subscriptions?.bot_events ??
@@ -318,7 +336,7 @@ export class SlackMock {
318
336
  SLACK_BOT_TOKEN: this.store.bot.token,
319
337
  SLACK_APP_TOKEN: this.store.bot.appToken,
320
338
  SLACK_API_URL: this.apiUrl,
321
- SLACK_SIGNING_SECRET: "mock-signing-secret",
339
+ SLACK_SIGNING_SECRET: this.opts.httpDelivery?.signingSecret ?? "mock-signing-secret",
322
340
  };
323
341
  }
324
342
 
@@ -327,7 +345,7 @@ export class SlackMock {
327
345
  }
328
346
  /** Number of Socket Mode connections the app currently holds. */
329
347
  get connectionCount(): number {
330
- return this.hub.connectionCount;
348
+ return this.delivery.connectionCount;
331
349
  }
332
350
 
333
351
  get team() {
@@ -336,6 +354,7 @@ export class SlackMock {
336
354
 
337
355
  async stop(): Promise<void> {
338
356
  this.hub.shutdown();
357
+ if (this.delivery instanceof HttpDelivery) this.delivery.shutdown();
339
358
  await Promise.allSettled([...this.inflight]);
340
359
  this.server.stop(true);
341
360
  }
@@ -596,7 +615,7 @@ export class SlackMock {
596
615
  const opts = {
597
616
  screenshot,
598
617
  refreshSec: Number.isFinite(refresh) && refresh > 0 ? refresh : undefined,
599
- connections: this.hub.connectionCount,
618
+ connections: this.delivery.connectionCount,
600
619
  panelWidth: panel
601
620
  ? /^\d+$/.test(panel)
602
621
  ? `${panel}%`
@@ -685,7 +704,7 @@ export class SlackMock {
685
704
  const wrapped = p.then(
686
705
  () => {},
687
706
  (e) => {
688
- if (!(e instanceof SocketModeClosedError))
707
+ if (!(e instanceof SocketModeClosedError || e instanceof HttpDeliveryStoppedError))
689
708
  this.log(`delivery failed: ${e instanceof Error ? e.message : e}`);
690
709
  },
691
710
  );
@@ -695,7 +714,7 @@ export class SlackMock {
695
714
  }
696
715
 
697
716
  private push(event: Record<string, unknown>): Promise<void> {
698
- if (this.hub.connectionCount === 0) {
717
+ if (this.delivery.connectionCount === 0) {
699
718
  this.log(
700
719
  `dropping ${event.type}${event.subtype ? `/${event.subtype}` : ""} event: no app connected`,
701
720
  );
@@ -703,7 +722,7 @@ export class SlackMock {
703
722
  }
704
723
  const send = async () => {
705
724
  if (this.opts.eventDelayMs) await Bun.sleep(this.opts.eventDelayMs);
706
- await this.hub.send("events_api", eventCallback(this.store, event));
725
+ await this.delivery.send("events_api", eventCallback(this.store, event));
707
726
  };
708
727
  return this.track(send());
709
728
  }
@@ -962,7 +981,7 @@ export class SlackMock {
962
981
  responseUrl,
963
982
  triggerId: this.issueTriggerId(),
964
983
  });
965
- const ack = await this.hub.send("slash_commands", payload, true);
984
+ const ack = await this.delivery.send("slash_commands", payload, true);
966
985
  let response: SlackMessage | undefined;
967
986
  const body = ack.payload as
968
987
  | { text?: string; blocks?: unknown[]; response_type?: string }
@@ -1024,7 +1043,7 @@ export class SlackMock {
1024
1043
  },
1025
1044
  ],
1026
1045
  });
1027
- const ack = await this.hub.send("interactive", payload, true);
1046
+ const ack = await this.delivery.send("interactive", payload, true);
1028
1047
  await this.flush();
1029
1048
  return ack;
1030
1049
  }
@@ -1051,7 +1070,7 @@ export class SlackMock {
1051
1070
  values: input.values,
1052
1071
  triggerId: this.issueTriggerId(),
1053
1072
  });
1054
- const ack = await this.hub.send("interactive", payload, true);
1073
+ const ack = await this.delivery.send("interactive", payload, true);
1055
1074
  // Slack keeps the modal open on `errors`, swaps it on `update`, stacks on `push`, closes otherwise.
1056
1075
  const response = (ack.payload ?? {}) as {
1057
1076
  response_action?: string;
@@ -1108,7 +1127,7 @@ export class SlackMock {
1108
1127
  const threadTs = root.ts;
1109
1128
  if (this.isSubscribed("assistant_thread_started")) {
1110
1129
  await this.track(
1111
- this.hub.send(
1130
+ this.delivery.send(
1112
1131
  "events_api",
1113
1132
  eventCallback(
1114
1133
  this.store,
@@ -1129,7 +1148,7 @@ export class SlackMock {
1129
1148
  const user = input.user ? this.user(input.user) : this.defaultHuman();
1130
1149
  const dm = this.resolveChannel(input.channel);
1131
1150
  await this.track(
1132
- this.hub.send(
1151
+ this.delivery.send(
1133
1152
  "events_api",
1134
1153
  eventCallback(
1135
1154
  this.store,
@@ -1171,7 +1190,7 @@ export class SlackMock {
1171
1190
 
1172
1191
  /** Every Socket Mode envelope pushed to the app, with ack status. */
1173
1192
  deliveries(name?: string): DeliveryRecord[] {
1174
- return name ? this.hub.history.filter((d) => d.name === name) : [...this.hub.history];
1193
+ return name ? this.delivery.history.filter((d) => d.name === name) : [...this.delivery.history];
1175
1194
  }
1176
1195
 
1177
1196
  apiCalls(method?: string): ApiCall[] {
@@ -1256,7 +1275,7 @@ export class SlackMock {
1256
1275
  }
1257
1276
 
1258
1277
  waitForConnection(timeoutMs = 15_000): Promise<void> {
1259
- return this.hub.waitForConnection(timeoutMs);
1278
+ return this.delivery.waitForConnection(timeoutMs);
1260
1279
  }
1261
1280
 
1262
1281
  disconnectSockets(reason?: Parameters<SocketModeHub["disconnectAll"]>[0]): void {
@@ -1283,7 +1302,7 @@ export class SlackMock {
1283
1302
  team: this.store.team,
1284
1303
  app: this.store.app,
1285
1304
  bot: { userId: this.store.bot.userId, botId: this.store.bot.botId },
1286
- connections: this.hub.connectionCount,
1305
+ connections: this.delivery.connectionCount,
1287
1306
  users: [...this.store.users.values()],
1288
1307
  channels: [...this.store.channels.values()],
1289
1308
  });
@@ -57,7 +57,7 @@ export interface DeliveryRecord {
57
57
  ackPayload?: unknown;
58
58
  }
59
59
 
60
- function envelopeName(type: EnvelopeType, payload: unknown): string {
60
+ export function envelopeName(type: EnvelopeType, payload: unknown): string {
61
61
  const p = payload as Record<string, unknown>;
62
62
  if (type === "events_api")
63
63
  return String((p.event as Record<string, unknown> | undefined)?.type ?? "event");
package/src/web-api.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // Slack Web API method handlers. Each receives the parsed args and returns the
2
2
  // `ok: true` body; they throw SlackApiError for `ok: false` responses.
3
3
 
4
+ import { validateBlocks } from "./block-limits.ts";
4
5
  import { type Args, bool, num, str } from "./body.ts";
5
6
  import { nextTs, nowUnix, slackId } from "./ids.ts";
6
7
  import type { SocketModeHub } from "./socket-mode.ts";
@@ -86,10 +87,7 @@ function messageContent(
86
87
  const blocks = Array.isArray(args.blocks) ? (args.blocks as unknown[]) : undefined;
87
88
  const attachments = Array.isArray(args.attachments) ? (args.attachments as unknown[]) : undefined;
88
89
  if (!text && !blocks?.length && !attachments?.length) throw new SlackApiError("no_text");
89
- if (blocks && blocks.length > 50)
90
- throw new SlackApiError("invalid_blocks", {
91
- response_metadata: { messages: ["[ERROR] must have at most 50 blocks"] },
92
- });
90
+ validateBlocks(blocks);
93
91
  const metadata =
94
92
  args.metadata && typeof args.metadata === "object"
95
93
  ? (args.metadata as SlackMessage["metadata"])
@@ -221,6 +219,7 @@ export const handlers: Record<string, Handler> = {
221
219
  }
222
220
  if (args.blocks !== undefined) {
223
221
  patch.blocks = Array.isArray(args.blocks) ? (args.blocks as unknown[]) : undefined;
222
+ validateBlocks(patch.blocks);
224
223
  // On a streamed message the new blocks replace the body rather than trail it.
225
224
  if (existing.streaming_state !== undefined) patch.stream_replaced = true;
226
225
  }