@desplega.ai/slack-mock 0.5.0 → 0.6.1

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.
@@ -424,7 +424,7 @@ function richElement(v, ctx) {
424
424
  return `<span class="sm-pill">@${escapeHtml(str(el.range) || "channel")}</span>`;
425
425
  case "emoji": {
426
426
  const char = emojiChar(str(el.name)) ?? (el.unicode ? emojiFromUnicode(str(el.unicode)) : undefined);
427
- return char ?? `<span class="sm-emoji-name">:${escapeHtml(str(el.name))}:</span>`;
427
+ return char ? escapeHtml(char) : `<span class="sm-emoji-name">:${escapeHtml(str(el.name))}:</span>`;
428
428
  }
429
429
  case "date":
430
430
  return plainTextToHtml(str(el.fallback) || str(el.timestamp));
@@ -505,6 +505,113 @@ function videoBlock(block, ctx) {
505
505
  const inner = `${thumb ? `<img class="sm-video-thumb" src="${thumb}" alt="${escapeHtml(str(block.alt_text))}">` : ""}<div class="sm-video-title">\u25B6 ${title}</div>`;
506
506
  return `<div class="sm-block sm-video">${url ? `<a class="sm-video-link" href="${url}" target="_blank" rel="noopener">${inner}</a>` : inner}</div>`;
507
507
  }
508
+ function tableCell(v, ctx) {
509
+ const cell = rec(v);
510
+ if (!cell)
511
+ return "";
512
+ if (str(cell.type) === "rich_text")
513
+ return arr(cell.elements).map((e) => richSection(e, ctx)).join("");
514
+ if (str(cell.type) === "action_cell") {
515
+ const el = rec(cell.element);
516
+ return el && str(el.type) === "button" ? button(el, ctx) : tableCell(cell.fallback, ctx);
517
+ }
518
+ return plainTextToHtml(str(cell.text) || (cell.value === undefined ? "" : String(cell.value)));
519
+ }
520
+ function tableBlock(block, ctx) {
521
+ const settings = arr(block.column_settings).map(rec);
522
+ const rows = arr(block.rows).map(arr);
523
+ const ps = Number(block.page_size);
524
+ const pageSize = block.type === "data_table" ? Number.isInteger(ps) && ps >= 1 ? ps : 5 : 0;
525
+ const head = block.type === "data_table" ? 1 : 0;
526
+ const body = rows.slice(head);
527
+ const per = pageSize || body.length || 1;
528
+ const pages = [];
529
+ for (let i = 0;i < body.length || i === 0; i += per)
530
+ pages.push(body.slice(i, i + per));
531
+ const row = (cells, tag) => `<tr>${cells.map((c, i) => {
532
+ const align = str(settings[i]?.align);
533
+ const cls = [
534
+ align === "center" || align === "right" ? `sm-ta-${align}` : "",
535
+ settings[i]?.is_wrapped === true ? "sm-td-wrap" : ""
536
+ ].filter(Boolean);
537
+ return `<${tag}${cls.length ? ` class="${cls.join(" ")}"` : ""}>${tableCell(c, ctx)}</${tag}>`;
538
+ }).join("")}</tr>`;
539
+ const caption = str(block.caption) ? `<div class="sm-table-caption">${plainTextToHtml(str(block.caption))}</div>` : "";
540
+ const paged = pages.length > 1;
541
+ const range = (p) => `${p * per + 1}\u2013${p * per + (pages[p]?.length ?? 0)} of ${body.length}`;
542
+ const pager = paged ? `<div class="sm-table-pager"><button type="button" class="sm-pager-btn" data-step="-1" aria-label="Previous page" disabled>\u2039</button><span class="sm-pager-label">${range(0)}</span><button type="button" class="sm-pager-btn" data-step="1" aria-label="Next page">\u203A</button></div>` : "";
543
+ const tbodies = pages.map((pg, p) => `<tbody${paged ? ` data-range="${range(p)}"` : ""}${p ? " hidden" : ""}>${pg.map((r) => row(r, "td")).join("")}</tbody>`).join("");
544
+ 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>`;
545
+ }
546
+ var CHART_COLORS = ["#1264a3", "#2eb67d", "#ecb22e", "#e01e5a", "#36c5f0", "#7c3085"];
547
+ var color = (i) => CHART_COLORS[i % CHART_COLORS.length];
548
+ var num = (v) => Number.isFinite(Number(v)) ? Number(v) : 0;
549
+ var svgText = (x, y, text, attrs = "") => `<text x="${x}" y="${y}" ${attrs}>${escapeHtml(text)}</text>`;
550
+ function legend(labels) {
551
+ return `<div class="sm-chart-legend">${labels.map((l, i) => `<span class="sm-chart-key"><i style="background:${color(i)}"></i>${escapeHtml(l)}</span>`).join("")}</div>`;
552
+ }
553
+ function pieChart(chart) {
554
+ const segments = arr(chart.segments).map(rec);
555
+ const total = segments.reduce((t, s) => t + Math.max(0, num(s?.value)), 0) || 1;
556
+ let angle = -Math.PI / 2;
557
+ const slices = segments.map((s, i) => {
558
+ const frac = Math.max(0, num(s?.value)) / total;
559
+ if (frac >= 0.9999)
560
+ return `<circle cx="100" cy="100" r="90" fill="${color(i)}"/>`;
561
+ const a0 = angle;
562
+ angle += frac * 2 * Math.PI;
563
+ const p = (a) => `${100 + 90 * Math.cos(a)} ${100 + 90 * Math.sin(a)}`;
564
+ return `<path d="M100 100 L${p(a0)} A90 90 0 ${frac > 0.5 ? 1 : 0} 1 ${p(angle)} Z" fill="${color(i)}"/>`;
565
+ });
566
+ 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)})`))}`;
567
+ }
568
+ function seriesChart(chart, type) {
569
+ const axis = rec(chart.axis_config) ?? {};
570
+ const series = arr(chart.series).map((s) => rec(s) ?? {});
571
+ const categories = arr(axis.categories).map(str);
572
+ const valueAt = (s, c) => num(rec(arr(s.data).find((p) => rec(p)?.label === c))?.value);
573
+ const values = series.flatMap((s) => categories.map((c) => valueAt(s, c)));
574
+ const min = Math.min(0, ...values);
575
+ const max = Math.max(min < 0 ? 0 : 1, ...values);
576
+ const [W, H, L, T, B] = [480, 220, 44, 10, 30];
577
+ const plotW = W - L - 10;
578
+ const plotH = H - T - B;
579
+ const y = (v) => T + plotH - (v - min) / (max - min) * plotH;
580
+ const zero = y(0);
581
+ const step = plotW / Math.max(1, categories.length);
582
+ const parts = [];
583
+ for (let k = 0;k <= 4; k++) {
584
+ const v = min + (max - min) * k / 4;
585
+ parts.push(`<line x1="${L}" x2="${W - 10}" y1="${y(v)}" y2="${y(v)}" stroke="#e8e8e8"/>`, svgText(L - 6, y(v) + 4, String(Math.round(v * 100) / 100), 'text-anchor="end"'));
586
+ }
587
+ categories.forEach((c, i) => {
588
+ parts.push(svgText(L + step * (i + 0.5), H - B + 16, c, 'text-anchor="middle"'));
589
+ });
590
+ series.forEach((s, si) => {
591
+ if (type === "bar") {
592
+ const bw = step * 0.7 / Math.max(1, series.length);
593
+ categories.forEach((c, i) => {
594
+ const v = valueAt(s, c);
595
+ parts.push(`<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)}"/>`);
596
+ });
597
+ return;
598
+ }
599
+ const pts = categories.map((c, i) => `${L + step * (i + 0.5)},${y(valueAt(s, c))}`);
600
+ if (type === "area" && pts.length)
601
+ parts.push(`<polygon points="${L + step * 0.5},${zero} ${pts.join(" ")} ${L + step * (categories.length - 0.5)},${zero}" fill="${color(si)}" fill-opacity=".25"/>`);
602
+ parts.push(`<polyline points="${pts.join(" ")}" fill="none" stroke="${color(si)}" stroke-width="2"/>`);
603
+ });
604
+ const xLabel = str(axis.x_label);
605
+ const yLabel = str(axis.y_label);
606
+ const labels = `${yLabel ? `<div class="sm-chart-axis">${plainTextToHtml(yLabel)} \u2191</div>` : ""}`;
607
+ 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)} \u2192</div>` : ""}${legend(series.map((s) => str(s.name)))}`;
608
+ }
609
+ function dataVisualizationBlock(block) {
610
+ const chart = rec(block.chart) ?? {};
611
+ const type = str(chart.type);
612
+ const body = type === "pie" ? pieChart(chart) : type === "bar" || type === "line" || type === "area" ? seriesChart(chart, type) : unsupported(`chart ${type}`);
613
+ return `<div class="sm-block sm-chart" data-chart="${escapeHtml(type)}"><div class="sm-chart-title">${plainTextToHtml(str(block.title))}</div>${body}</div>`;
614
+ }
508
615
  function renderBlock(v, ctx) {
509
616
  const block = rec(v);
510
617
  if (!block)
@@ -532,6 +639,11 @@ function renderBlock(v, ctx) {
532
639
  return videoBlock(block, ctx);
533
640
  case "markdown":
534
641
  return `<div class="sm-block sm-markdown">${markdownToHtml(str(block.text), ctx)}</div>`;
642
+ case "table":
643
+ case "data_table":
644
+ return tableBlock(block, ctx);
645
+ case "data_visualization":
646
+ return dataVisualizationBlock(block);
535
647
  default:
536
648
  return `<div class="sm-block">${unsupported(str(block.type))}</div>`;
537
649
  }
@@ -798,6 +910,25 @@ a:hover{text-decoration:underline}
798
910
  .sm-video-title{font-size:14px;font-weight:700;margin-top:4px}
799
911
  .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}
800
912
  .sm-rt-section{margin:2px 0}
913
+ .sm-table-caption{font-size:13px;font-weight:700;color:#454245;margin-bottom:4px}
914
+ .sm-table-wrap{width:fit-content;overflow-x:auto;border:1px solid #ddd;border-radius:6px;max-width:100%}
915
+ .sm-bk-table{border-collapse:collapse;font-size:14px;line-height:20px}
916
+ .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}
917
+ .sm-bk-table th{font-weight:700;background:#f8f8f8}
918
+ .sm-bk-table tr:last-child td{border-bottom:0}
919
+ .sm-bk-table .sm-ta-center{text-align:center}
920
+ .sm-bk-table .sm-ta-right{text-align:right}
921
+ .sm-bk-table .sm-td-wrap{white-space:normal}
922
+ .sm-table-pager{display:flex;align-items:center;gap:6px;font-size:12px;color:#616061;margin-top:4px}
923
+ .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}
924
+ .sm-pager-btn:disabled{color:#bbb;cursor:default}
925
+ .sm-chart{border:1px solid #ddd;border-radius:6px;padding:10px 12px;max-width:520px}
926
+ .sm-chart-title{font-size:14px;font-weight:700;margin-bottom:6px}
927
+ .sm-chart-svg{display:block;max-width:100%;height:auto;font-size:11px;fill:#616061}
928
+ .sm-chart-axis{font-size:11px;color:#616061}
929
+ .sm-chart-axis-x{text-align:center}
930
+ .sm-chart-legend{display:flex;flex-wrap:wrap;gap:4px 12px;font-size:12px;color:#454245;margin-top:6px}
931
+ .sm-chart-key i{display:inline-block;width:10px;height:10px;border-radius:2px;margin-right:4px;vertical-align:-1px}
801
932
 
802
933
  .sm-atts{margin-top:4px}
803
934
  .sm-att{border-left:4px solid #ddd;border-radius:2px;padding:2px 0 2px 12px;margin:6px 0;max-width:600px}
@@ -1284,6 +1415,7 @@ function fitViewport(){if(viewport&&viewport.scale!==1)return;var style=document
1284
1415
  fitViewport();addEventListener("resize",fitViewport);
1285
1416
  if(viewport){viewport.addEventListener("resize",fitViewport);viewport.addEventListener("scroll",fitViewport)}
1286
1417
  document.addEventListener("change",function(e){if(e.target.classList.contains("sm-channel-switch"))location.href=e.target.value});
1418
+ 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});
1287
1419
  var W="sm-panel-w",DEF=${JSON.stringify(panelWidth(opts))},FIXED=${opts.panelWidth ? "true" : "false"};
1288
1420
  ${autoScroll ? `function scroll(){document.querySelectorAll(".sm-scroll").forEach(function(el){el.scrollTop=el.scrollHeight})}
1289
1421
  scroll();addEventListener("load",scroll);` : ""}
@@ -1586,7 +1718,7 @@ function str2(args, key) {
1586
1718
  const v = args[key];
1587
1719
  return typeof v === "string" ? v : v == null ? undefined : String(v);
1588
1720
  }
1589
- function num(args, key, fallback) {
1721
+ function num2(args, key, fallback) {
1590
1722
  const v = args[key];
1591
1723
  const n = typeof v === "number" ? v : typeof v === "string" ? Number.parseInt(v, 10) : Number.NaN;
1592
1724
  return Number.isFinite(n) ? n : fallback;
@@ -1736,7 +1868,10 @@ class Store2 {
1736
1868
  break;
1737
1869
  }
1738
1870
  case "message.add":
1739
- this.insertMessage(change.message);
1871
+ if (change.message.ephemeral_user)
1872
+ this.ephemerals.push(change.message);
1873
+ else
1874
+ this.insertMessage(change.message);
1740
1875
  break;
1741
1876
  case "message.update":
1742
1877
  case "reaction.add":
@@ -2372,6 +2507,9 @@ function viewSubmissionPayload(store, input) {
2372
2507
  };
2373
2508
  }
2374
2509
 
2510
+ // src/http-delivery.ts
2511
+ import { createHmac } from "crypto";
2512
+
2375
2513
  // src/socket-mode.ts
2376
2514
  class SocketModeClosedError extends Error {
2377
2515
  }
@@ -2546,6 +2684,318 @@ class SocketModeHub {
2546
2684
  }
2547
2685
  }
2548
2686
 
2687
+ // src/http-delivery.ts
2688
+ function slackSignature2(secret, timestamp, body) {
2689
+ return `v0=${createHmac("sha256", secret).update(`v0:${timestamp}:${body}`).digest("hex")}`;
2690
+ }
2691
+
2692
+ class HttpDeliveryError2 extends Error {
2693
+ }
2694
+
2695
+ class HttpDeliveryStoppedError2 extends HttpDeliveryError2 {
2696
+ constructor() {
2697
+ super("mock stopped");
2698
+ }
2699
+ }
2700
+
2701
+ class HttpDelivery2 {
2702
+ history = [];
2703
+ opts;
2704
+ stopController = new AbortController;
2705
+ retryTimers = new Set;
2706
+ constructor(opts) {
2707
+ this.opts = {
2708
+ eventsUrl: opts.eventsUrl,
2709
+ interactivityUrl: opts.interactivityUrl ?? opts.eventsUrl,
2710
+ commandsUrl: opts.commandsUrl ?? opts.eventsUrl,
2711
+ signingSecret: opts.signingSecret,
2712
+ retryDelaysMs: opts.retryDelaysMs ?? [60000, 300000, 1800000],
2713
+ timeoutMs: opts.timeoutMs ?? 3000,
2714
+ log: opts.log ?? (() => {})
2715
+ };
2716
+ }
2717
+ shutdown() {
2718
+ this.stopController.abort();
2719
+ for (const t of this.retryTimers) {
2720
+ clearTimeout(t.timer);
2721
+ t.wake();
2722
+ }
2723
+ this.retryTimers.clear();
2724
+ }
2725
+ get stopped() {
2726
+ return this.stopController.signal.aborted;
2727
+ }
2728
+ waitToRetry(ms) {
2729
+ return new Promise((resolve) => {
2730
+ const entry = {
2731
+ timer: setTimeout(() => {
2732
+ this.retryTimers.delete(entry);
2733
+ resolve();
2734
+ }, ms),
2735
+ wake: resolve
2736
+ };
2737
+ this.retryTimers.add(entry);
2738
+ });
2739
+ }
2740
+ get connectionCount() {
2741
+ return 1;
2742
+ }
2743
+ waitForConnection() {
2744
+ return Promise.resolve();
2745
+ }
2746
+ async verifyUrl() {
2747
+ const challenge = crypto.randomUUID();
2748
+ const body = JSON.stringify({
2749
+ token: "mock-verification-token",
2750
+ challenge,
2751
+ type: "url_verification"
2752
+ });
2753
+ const res = await this.post(this.opts.eventsUrl, body, "application/json", {});
2754
+ if (!res.ok)
2755
+ return false;
2756
+ return res.payload?.challenge === challenge || res.text === challenge;
2757
+ }
2758
+ async send(type, payload, _acceptsResponsePayload = false) {
2759
+ if (this.stopped)
2760
+ throw new HttpDeliveryStoppedError2;
2761
+ const record = {
2762
+ envelope_id: crypto.randomUUID(),
2763
+ type,
2764
+ name: envelopeName(type, payload),
2765
+ sentAt: new Date().toISOString(),
2766
+ attempts: 0,
2767
+ acked: false
2768
+ };
2769
+ this.history.push(record);
2770
+ const { url, body, contentType } = this.encode(type, payload);
2771
+ const delays = type === "events_api" ? this.opts.retryDelaysMs : [];
2772
+ let retry;
2773
+ for (let attempt = 0;; attempt++) {
2774
+ record.attempts = attempt + 1;
2775
+ const res = await this.post(url, body, contentType, retry ? this.retryHeaders(retry) : {});
2776
+ if (this.stopped)
2777
+ throw new HttpDeliveryStoppedError2;
2778
+ if (res.ok) {
2779
+ record.acked = true;
2780
+ record.ackPayload = res.payload;
2781
+ return { envelope_id: record.envelope_id, payload: res.payload, attempts: record.attempts };
2782
+ }
2783
+ const delay = delays[attempt];
2784
+ if (delay === undefined) {
2785
+ throw new HttpDeliveryError2(`${record.name} not acknowledged (${res.reason}) after ${record.attempts} attempt(s)`);
2786
+ }
2787
+ this.opts.log(`${record.name} to ${url}: ${res.reason}; retry ${attempt + 1} in ${delay}ms`);
2788
+ await this.waitToRetry(delay);
2789
+ if (this.stopped)
2790
+ throw new HttpDeliveryStoppedError2;
2791
+ retry = { num: attempt + 1, reason: res.reason };
2792
+ }
2793
+ }
2794
+ retryHeaders(retry) {
2795
+ return { "X-Slack-Retry-Num": String(retry.num), "X-Slack-Retry-Reason": retry.reason };
2796
+ }
2797
+ encode(type, payload) {
2798
+ if (type === "events_api") {
2799
+ return {
2800
+ url: this.opts.eventsUrl,
2801
+ body: JSON.stringify(payload),
2802
+ contentType: "application/json"
2803
+ };
2804
+ }
2805
+ const form = new URLSearchParams;
2806
+ if (type === "interactive") {
2807
+ form.set("payload", JSON.stringify(payload));
2808
+ } else {
2809
+ for (const [key, value] of Object.entries(payload)) {
2810
+ if (value !== undefined && value !== null)
2811
+ form.set(key, String(value));
2812
+ }
2813
+ }
2814
+ return {
2815
+ url: type === "interactive" ? this.opts.interactivityUrl : this.opts.commandsUrl,
2816
+ body: form.toString(),
2817
+ contentType: "application/x-www-form-urlencoded"
2818
+ };
2819
+ }
2820
+ async post(url, body, contentType, extraHeaders) {
2821
+ if (this.stopped)
2822
+ return { ok: false, reason: "stopped" };
2823
+ const timestamp = Math.floor(Date.now() / 1000);
2824
+ try {
2825
+ const res = await fetch(url, {
2826
+ method: "POST",
2827
+ headers: {
2828
+ "Content-Type": contentType,
2829
+ "X-Slack-Request-Timestamp": String(timestamp),
2830
+ "X-Slack-Signature": slackSignature2(this.opts.signingSecret, timestamp, body),
2831
+ "User-Agent": "Slackbot 1.0 (+https://api.slack.com/robots)",
2832
+ ...extraHeaders
2833
+ },
2834
+ body,
2835
+ signal: AbortSignal.any([
2836
+ AbortSignal.timeout(this.opts.timeoutMs),
2837
+ this.stopController.signal
2838
+ ])
2839
+ });
2840
+ if (!res.ok) {
2841
+ await res.body?.cancel();
2842
+ return { ok: false, reason: "http_error" };
2843
+ }
2844
+ const text = await res.text();
2845
+ let payload;
2846
+ try {
2847
+ payload = text ? JSON.parse(text) : undefined;
2848
+ } catch {
2849
+ payload = undefined;
2850
+ }
2851
+ return { ok: true, payload, text };
2852
+ } catch (e) {
2853
+ const timedOut = e instanceof Error && (e.name === "TimeoutError" || e.name === "AbortError");
2854
+ return { ok: false, reason: timedOut ? "http_timeout" : "connection_failed" };
2855
+ }
2856
+ }
2857
+ }
2858
+
2859
+ // src/block-limits.ts
2860
+ var rec2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : undefined;
2861
+ var arr2 = (v) => Array.isArray(v) ? v : [];
2862
+ var str3 = (v) => typeof v === "string" ? v : "";
2863
+ function cellChars(v) {
2864
+ const cell = rec2(v);
2865
+ if (!cell)
2866
+ return 0;
2867
+ if (cell.type === "action_cell")
2868
+ return str3(rec2(rec2(cell.element)?.text)?.text).length;
2869
+ if (typeof cell.text === "string")
2870
+ return cell.text.length;
2871
+ return arr2(cell.elements).reduce((n, e) => n + cellChars(e), 0);
2872
+ }
2873
+ function tableIssues(b, at, data) {
2874
+ const out = [];
2875
+ const rows = arr2(b.rows);
2876
+ const [minRows, maxRows, maxChars] = data ? [2, 201, 20000] : [1, 100, 1e4];
2877
+ if (rows.length < minRows || rows.length > maxRows)
2878
+ out.push(`rows must have between ${minRows} and ${maxRows} items [json-pointer:${at}/rows]`);
2879
+ const cellTypes = data ? ["raw_text", "raw_number", "rich_text", "action_cell"] : ["raw_text", "raw_number", "rich_text"];
2880
+ let chars = 0;
2881
+ rows.forEach((r, i) => {
2882
+ const cells = arr2(r);
2883
+ if (!Array.isArray(r) || cells.length < 1 || cells.length > 20)
2884
+ out.push(`row must have between 1 and 20 cells [json-pointer:${at}/rows/${i}]`);
2885
+ if (data && cells.length !== arr2(rows[0]).length)
2886
+ out.push(`all rows must have the same number of cells [json-pointer:${at}/rows/${i}]`);
2887
+ cells.forEach((c, j) => {
2888
+ const type = str3(rec2(c)?.type);
2889
+ if (!cellTypes.includes(type) || data && i === 0 && type === "rich_text")
2890
+ out.push(`invalid cell type "${type}" [json-pointer:${at}/rows/${i}/${j}]`);
2891
+ else if (type === "action_cell" && str3(rec2(rec2(c)?.element)?.type) !== "button")
2892
+ out.push(`action_cell element must be a button [json-pointer:${at}/rows/${i}/${j}/element]`);
2893
+ chars += cellChars(c);
2894
+ });
2895
+ });
2896
+ if (chars > maxChars)
2897
+ out.push(`cells must have at most ${maxChars} characters in total [json-pointer:${at}/rows]`);
2898
+ if (data) {
2899
+ if (!str3(b.caption))
2900
+ out.push(`caption is required [json-pointer:${at}/caption]`);
2901
+ const page = b.page_size;
2902
+ if (page !== undefined && !(Number.isInteger(page) && page >= 1 && page <= 100))
2903
+ out.push(`page_size must be an integer between 1 and 100 [json-pointer:${at}/page_size]`);
2904
+ } else if (arr2(b.column_settings).length > 20) {
2905
+ out.push(`column_settings must have at most 20 items [json-pointer:${at}/column_settings]`);
2906
+ }
2907
+ return { out, chars };
2908
+ }
2909
+ var label = (v) => str3(v).length >= 1 && str3(v).length <= 20;
2910
+ function chartIssues(b, at) {
2911
+ const out = [];
2912
+ const title = str3(b.title);
2913
+ if (title.length < 1 || title.length > 50)
2914
+ out.push(`title must have between 1 and 50 characters [json-pointer:${at}/title]`);
2915
+ const chart = rec2(b.chart);
2916
+ const type = str3(chart?.type);
2917
+ if (type === "pie") {
2918
+ const segments = arr2(chart?.segments);
2919
+ if (segments.length < 1 || segments.length > 12)
2920
+ out.push(`segments must have between 1 and 12 items [json-pointer:${at}/chart/segments]`);
2921
+ segments.forEach((s, i) => {
2922
+ const seg = rec2(s);
2923
+ if (!label(seg?.label) || !(typeof seg?.value === "number" && seg.value > 0))
2924
+ out.push(`segment needs a 1-20 character label and a value above 0 [json-pointer:${at}/chart/segments/${i}]`);
2925
+ });
2926
+ return out;
2927
+ }
2928
+ if (!["bar", "line", "area"].includes(type))
2929
+ return [...out, `chart type must be pie, bar, line or area [json-pointer:${at}/chart/type]`];
2930
+ const axis = rec2(chart?.axis_config);
2931
+ const categories = arr2(axis?.categories).map(str3);
2932
+ if (!categories.length)
2933
+ out.push(`axis_config.categories is required [json-pointer:${at}/chart/axis_config]`);
2934
+ categories.forEach((c, i) => {
2935
+ if (c.length > 20)
2936
+ out.push(`category must have at most 20 characters [json-pointer:${at}/chart/axis_config/categories/${i}]`);
2937
+ });
2938
+ for (const k of ["x_label", "y_label"])
2939
+ if (str3(axis?.[k]).length > 50)
2940
+ out.push(`${k} must have at most 50 characters [json-pointer:${at}/chart/axis_config/${k}]`);
2941
+ const series = arr2(chart?.series);
2942
+ if (series.length < 1 || series.length > 12)
2943
+ out.push(`series must have between 1 and 12 items [json-pointer:${at}/chart/series]`);
2944
+ const names = new Set;
2945
+ series.forEach((s, i) => {
2946
+ const sr = rec2(s);
2947
+ const name = str3(sr?.name);
2948
+ if (!label(name) || names.has(name))
2949
+ out.push(`series name must be unique and 1-20 characters [json-pointer:${at}/chart/series/${i}/name]`);
2950
+ names.add(name);
2951
+ const data = arr2(sr?.data).map((p) => rec2(p));
2952
+ const labels = data.map((p) => str3(p?.label));
2953
+ if (data.length < 1 || data.length > 20)
2954
+ out.push(`data must have between 1 and 20 items [json-pointer:${at}/chart/series/${i}/data]`);
2955
+ if (data.some((p) => !label(p?.label) || typeof p?.value !== "number"))
2956
+ out.push(`data points need a 1-20 character label and a number value [json-pointer:${at}/chart/series/${i}/data]`);
2957
+ const count = (c) => labels.filter((l) => l === c).length;
2958
+ if (labels.some((l) => !categories.includes(l)) || categories.some((c) => count(c) !== 1))
2959
+ out.push(`data labels must match axis_config.categories [json-pointer:${at}/chart/series/${i}/data]`);
2960
+ });
2961
+ return out;
2962
+ }
2963
+ function validateBlocks(blocks) {
2964
+ if (!blocks)
2965
+ return;
2966
+ const issues = [];
2967
+ if (blocks.length > 50)
2968
+ issues.push("must have at most 50 blocks");
2969
+ let charts = 0;
2970
+ const budget = { table: 0, data_table: 0 };
2971
+ blocks.forEach((v, i) => {
2972
+ const b = rec2(v);
2973
+ const at = `/blocks/${i}`;
2974
+ switch (str3(b?.type)) {
2975
+ case "table":
2976
+ case "data_table": {
2977
+ const t = tableIssues(b, at, b?.type === "data_table");
2978
+ issues.push(...t.out);
2979
+ budget[b?.type] += t.chars;
2980
+ break;
2981
+ }
2982
+ case "data_visualization":
2983
+ if (++charts > 2)
2984
+ issues.push(`at most 2 data_visualization blocks per message [json-pointer:${at}]`);
2985
+ issues.push(...chartIssues(b, at));
2986
+ break;
2987
+ }
2988
+ });
2989
+ if (budget.table > 1e4)
2990
+ issues.push("table cells must have at most 10000 characters in total per message");
2991
+ if (budget.data_table > 20000)
2992
+ issues.push("data_table cells must have at most 20000 characters in total per message");
2993
+ if (issues.length)
2994
+ throw new SlackApiError2("invalid_blocks", {
2995
+ response_metadata: { messages: issues.map((m) => `[ERROR] ${m}`) }
2996
+ });
2997
+ }
2998
+
2549
2999
  // src/web-api.ts
2550
3000
  function required(args, key) {
2551
3001
  const v = str2(args, key);
@@ -2600,10 +3050,7 @@ function messageContent(args) {
2600
3050
  const attachments = Array.isArray(args.attachments) ? args.attachments : undefined;
2601
3051
  if (!text && !blocks?.length && !attachments?.length)
2602
3052
  throw new SlackApiError2("no_text");
2603
- if (blocks && blocks.length > 50)
2604
- throw new SlackApiError2("invalid_blocks", {
2605
- response_metadata: { messages: ["[ERROR] must have at most 50 blocks"] }
2606
- });
3053
+ validateBlocks(blocks);
2607
3054
  const metadata = args.metadata && typeof args.metadata === "object" ? args.metadata : undefined;
2608
3055
  return {
2609
3056
  text,
@@ -2720,6 +3167,7 @@ var handlers = {
2720
3167
  }
2721
3168
  if (args.blocks !== undefined) {
2722
3169
  patch.blocks = Array.isArray(args.blocks) ? args.blocks : undefined;
3170
+ validateBlocks(patch.blocks);
2723
3171
  if (existing.streaming_state !== undefined)
2724
3172
  patch.stream_replaced = true;
2725
3173
  }
@@ -2805,7 +3253,7 @@ var handlers = {
2805
3253
  return types.has("private_channel");
2806
3254
  return types.has("public_channel");
2807
3255
  });
2808
- const limit = num(args, "limit", 100);
3256
+ const limit = num2(args, "limit", 100);
2809
3257
  const start = cursorOffset(str2(args, "cursor"));
2810
3258
  const slice = all.slice(start, start + limit);
2811
3259
  const hasMore = start + limit < all.length;
@@ -2885,7 +3333,7 @@ var handlers = {
2885
3333
  oldest: str2(args, "oldest"),
2886
3334
  latest: str2(args, "latest"),
2887
3335
  inclusive: bool(args, "inclusive"),
2888
- limit: num(args, "limit", 100),
3336
+ limit: num2(args, "limit", 100),
2889
3337
  cursor: str2(args, "cursor")
2890
3338
  });
2891
3339
  return {
@@ -2905,7 +3353,7 @@ var handlers = {
2905
3353
  oldest: str2(args, "oldest"),
2906
3354
  latest: str2(args, "latest"),
2907
3355
  inclusive: bool(args, "inclusive"),
2908
- limit: num(args, "limit", 1000),
3356
+ limit: num2(args, "limit", 1000),
2909
3357
  cursor: str2(args, "cursor")
2910
3358
  });
2911
3359
  return {
@@ -2954,7 +3402,7 @@ var handlers = {
2954
3402
  },
2955
3403
  "files.getUploadURLExternal": (ctx, args) => {
2956
3404
  const filename = required(args, "filename");
2957
- const length = num(args, "length", -1);
3405
+ const length = num2(args, "length", -1);
2958
3406
  if (length < 0)
2959
3407
  throw new SlackApiError2("invalid_arguments", {
2960
3408
  response_metadata: { messages: ["[ERROR] missing required field: length"] }
@@ -3181,6 +3629,7 @@ var DEFAULT_EVENTS = [
3181
3629
  class SlackMock2 {
3182
3630
  store;
3183
3631
  hub;
3632
+ delivery;
3184
3633
  opts;
3185
3634
  server;
3186
3635
  triggerIds = new Map;
@@ -3208,6 +3657,7 @@ class SlackMock2 {
3208
3657
  maxRetries: opts.maxRetries,
3209
3658
  log: this.log
3210
3659
  });
3660
+ this.delivery = opts.httpDelivery ? new HttpDelivery2({ log: this.log, ...opts.httpDelivery }) : this.hub;
3211
3661
  this.subscribed = new Set(opts.subscribedEvents ?? manifest?.settings?.event_subscriptions?.bot_events ?? DEFAULT_EVENTS);
3212
3662
  if (manifest?.features?.slash_commands)
3213
3663
  this.commands = new Set(manifest.features.slash_commands.map((c) => c.command));
@@ -3301,20 +3751,22 @@ class SlackMock2 {
3301
3751
  SLACK_BOT_TOKEN: this.store.bot.token,
3302
3752
  SLACK_APP_TOKEN: this.store.bot.appToken,
3303
3753
  SLACK_API_URL: this.apiUrl,
3304
- SLACK_SIGNING_SECRET: "mock-signing-secret"
3754
+ SLACK_SIGNING_SECRET: this.opts.httpDelivery?.signingSecret ?? "mock-signing-secret"
3305
3755
  };
3306
3756
  }
3307
3757
  get bot() {
3308
3758
  return this.store.bot;
3309
3759
  }
3310
3760
  get connectionCount() {
3311
- return this.hub.connectionCount;
3761
+ return this.delivery.connectionCount;
3312
3762
  }
3313
3763
  get team() {
3314
3764
  return this.store.team;
3315
3765
  }
3316
3766
  async stop() {
3317
3767
  this.hub.shutdown();
3768
+ if (this.delivery instanceof HttpDelivery2)
3769
+ this.delivery.shutdown();
3318
3770
  await Promise.allSettled([...this.inflight]);
3319
3771
  this.server.stop(true);
3320
3772
  }
@@ -3556,7 +4008,7 @@ class SlackMock2 {
3556
4008
  const opts = {
3557
4009
  screenshot,
3558
4010
  refreshSec: Number.isFinite(refresh) && refresh > 0 ? refresh : undefined,
3559
- connections: this.hub.connectionCount,
4011
+ connections: this.delivery.connectionCount,
3560
4012
  panelWidth: panel ? /^\d+$/.test(panel) ? `${panel}%` : /^\d+(px|%|vw|rem)$/.test(panel) ? panel : undefined : undefined,
3561
4013
  threadView: url.searchParams.has("full") ? "full" : "panel",
3562
4014
  live: url.searchParams.get("live") !== "0",
@@ -3632,7 +4084,7 @@ data: ${JSON.stringify(data)}
3632
4084
  }
3633
4085
  track(p) {
3634
4086
  const wrapped = p.then(() => {}, (e) => {
3635
- if (!(e instanceof SocketModeClosedError))
4087
+ if (!(e instanceof SocketModeClosedError || e instanceof HttpDeliveryStoppedError2))
3636
4088
  this.log(`delivery failed: ${e instanceof Error ? e.message : e}`);
3637
4089
  });
3638
4090
  this.inflight.add(wrapped);
@@ -3640,14 +4092,14 @@ data: ${JSON.stringify(data)}
3640
4092
  return wrapped;
3641
4093
  }
3642
4094
  push(event) {
3643
- if (this.hub.connectionCount === 0) {
4095
+ if (this.delivery.connectionCount === 0) {
3644
4096
  this.log(`dropping ${event.type}${event.subtype ? `/${event.subtype}` : ""} event: no app connected`);
3645
4097
  return Promise.resolve();
3646
4098
  }
3647
4099
  const send = async () => {
3648
4100
  if (this.opts.eventDelayMs)
3649
4101
  await Bun.sleep(this.opts.eventDelayMs);
3650
- await this.hub.send("events_api", eventCallback(this.store, event));
4102
+ await this.delivery.send("events_api", eventCallback(this.store, event));
3651
4103
  };
3652
4104
  return this.track(send());
3653
4105
  }
@@ -3848,7 +4300,7 @@ data: ${JSON.stringify(data)}
3848
4300
  responseUrl,
3849
4301
  triggerId: this.issueTriggerId()
3850
4302
  });
3851
- const ack = await this.hub.send("slash_commands", payload, true);
4303
+ const ack = await this.delivery.send("slash_commands", payload, true);
3852
4304
  let response;
3853
4305
  const body = ack.payload;
3854
4306
  if (body && (body.text || body.blocks)) {
@@ -3897,7 +4349,7 @@ data: ${JSON.stringify(data)}
3897
4349
  }
3898
4350
  ]
3899
4351
  });
3900
- const ack = await this.hub.send("interactive", payload, true);
4352
+ const ack = await this.delivery.send("interactive", payload, true);
3901
4353
  await this.flush();
3902
4354
  return ack;
3903
4355
  }
@@ -3914,7 +4366,7 @@ data: ${JSON.stringify(data)}
3914
4366
  values: input.values,
3915
4367
  triggerId: this.issueTriggerId()
3916
4368
  });
3917
- const ack = await this.hub.send("interactive", payload, true);
4369
+ const ack = await this.delivery.send("interactive", payload, true);
3918
4370
  const response = ack.payload ?? {};
3919
4371
  if (response.response_action === "errors") {
3920
4372
  view.state = { values: input.values };
@@ -3960,14 +4412,14 @@ data: ${JSON.stringify(data)}
3960
4412
  });
3961
4413
  const threadTs = root.ts;
3962
4414
  if (this.isSubscribed("assistant_thread_started")) {
3963
- await this.track(this.hub.send("events_api", eventCallback(this.store, assistantThreadStartedEvent(this.store, dm, user.id, threadTs, input.context))));
4415
+ await this.track(this.delivery.send("events_api", eventCallback(this.store, assistantThreadStartedEvent(this.store, dm, user.id, threadTs, input.context))));
3964
4416
  }
3965
4417
  return { channel: dm.id, thread_ts: threadTs };
3966
4418
  }
3967
4419
  async changeAssistantContext(input) {
3968
4420
  const user = input.user ? this.user(input.user) : this.defaultHuman();
3969
4421
  const dm = this.resolveChannel(input.channel);
3970
- await this.track(this.hub.send("events_api", eventCallback(this.store, assistantThreadContextChangedEvent(this.store, dm, user.id, input.thread_ts, input.context))));
4422
+ await this.track(this.delivery.send("events_api", eventCallback(this.store, assistantThreadContextChangedEvent(this.store, dm, user.id, input.thread_ts, input.context))));
3971
4423
  }
3972
4424
  assistantThread(channel, thread_ts) {
3973
4425
  return this.store.assistantThreads.get(`${this.resolveChannel(channel).id}:${thread_ts}`) ?? {};
@@ -3986,7 +4438,7 @@ data: ${JSON.stringify(data)}
3986
4438
  this.faults.push({ ...fault, remaining: fault.times ?? 1 });
3987
4439
  }
3988
4440
  deliveries(name) {
3989
- return name ? this.hub.history.filter((d) => d.name === name) : [...this.hub.history];
4441
+ return name ? this.delivery.history.filter((d) => d.name === name) : [...this.delivery.history];
3990
4442
  }
3991
4443
  apiCalls(method) {
3992
4444
  return method ? this.store.apiCalls.filter((c) => c.method === method) : [...this.store.apiCalls];
@@ -4055,7 +4507,7 @@ data: ${JSON.stringify(data)}
4055
4507
  });
4056
4508
  }
4057
4509
  waitForConnection(timeoutMs = 15000) {
4058
- return this.hub.waitForConnection(timeoutMs);
4510
+ return this.delivery.waitForConnection(timeoutMs);
4059
4511
  }
4060
4512
  disconnectSockets(reason) {
4061
4513
  this.hub.disconnectAll(reason);
@@ -4074,7 +4526,7 @@ data: ${JSON.stringify(data)}
4074
4526
  team: this.store.team,
4075
4527
  app: this.store.app,
4076
4528
  bot: { userId: this.store.bot.userId, botId: this.store.bot.botId },
4077
- connections: this.hub.connectionCount,
4529
+ connections: this.delivery.connectionCount,
4078
4530
  users: [...this.store.users.values()],
4079
4531
  channels: [...this.store.channels.values()]
4080
4532
  });
@@ -4236,4 +4688,4 @@ async function frames2(opts) {
4236
4688
  }
4237
4689
  }
4238
4690
 
4239
- export { SlackApiError2, Store2, SlackMock2, frames2 };
4691
+ export { SlackApiError2, Store2, slackSignature2, HttpDeliveryError2, HttpDeliveryStoppedError2, HttpDelivery2, SlackMock2, frames2 };