File size: 10,754 Bytes
87fc763
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/**
 * Tests for outbound.ts module
 *
 * Tests cover:
 * - resolveTarget with various modes (explicit, implicit, heartbeat)
 * - sendText with markdown stripping
 * - sendMedia delegation to sendText
 * - Error handling for missing accounts/channels
 * - Abort signal handling
 */

import type { OpenClawConfig } from "openclaw/plugin-sdk";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { twitchOutbound } from "./outbound.js";

// Mock dependencies
vi.mock("./config.js", () => ({
  DEFAULT_ACCOUNT_ID: "default",
  getAccountConfig: vi.fn(),
}));

vi.mock("./send.js", () => ({
  sendMessageTwitchInternal: vi.fn(),
}));

vi.mock("./utils/markdown.js", () => ({
  chunkTextForTwitch: vi.fn((text) => text.split(/(.{500})/).filter(Boolean)),
}));

vi.mock("./utils/twitch.js", () => ({
  normalizeTwitchChannel: (channel: string) => channel.toLowerCase().replace(/^#/, ""),
  missingTargetError: (channel: string, hint: string) =>
    `Missing target for ${channel}. Provide ${hint}`,
}));

describe("outbound", () => {
  const mockAccount = {
    username: "testbot",
    token: "oauth:test123",
    clientId: "test-client-id",
    channel: "#testchannel",
  };

  const mockConfig = {
    channels: {
      twitch: {
        accounts: {
          default: mockAccount,
        },
      },
    },
  } as unknown as OpenClawConfig;

  beforeEach(() => {
    vi.clearAllMocks();
  });

  afterEach(() => {
    vi.restoreAllMocks();
  });

  describe("metadata", () => {
    it("should have direct delivery mode", () => {
      expect(twitchOutbound.deliveryMode).toBe("direct");
    });

    it("should have 500 character text chunk limit", () => {
      expect(twitchOutbound.textChunkLimit).toBe(500);
    });

    it("should have chunker function", () => {
      expect(twitchOutbound.chunker).toBeDefined();
      expect(typeof twitchOutbound.chunker).toBe("function");
    });
  });

  describe("resolveTarget", () => {
    it("should normalize and return target in explicit mode", () => {
      const result = twitchOutbound.resolveTarget({
        to: "#MyChannel",
        mode: "explicit",
        allowFrom: [],
      });

      expect(result.ok).toBe(true);
      expect(result.to).toBe("mychannel");
    });

    it("should return target in implicit mode with wildcard allowlist", () => {
      const result = twitchOutbound.resolveTarget({
        to: "#AnyChannel",
        mode: "implicit",
        allowFrom: ["*"],
      });

      expect(result.ok).toBe(true);
      expect(result.to).toBe("anychannel");
    });

    it("should return target in implicit mode when in allowlist", () => {
      const result = twitchOutbound.resolveTarget({
        to: "#allowed",
        mode: "implicit",
        allowFrom: ["#allowed", "#other"],
      });

      expect(result.ok).toBe(true);
      expect(result.to).toBe("allowed");
    });

    it("should fallback to first allowlist entry when target not in list", () => {
      const result = twitchOutbound.resolveTarget({
        to: "#notallowed",
        mode: "implicit",
        allowFrom: ["#primary", "#secondary"],
      });

      expect(result.ok).toBe(true);
      expect(result.to).toBe("primary");
    });

    it("should accept any target when allowlist is empty", () => {
      const result = twitchOutbound.resolveTarget({
        to: "#anychannel",
        mode: "heartbeat",
        allowFrom: [],
      });

      expect(result.ok).toBe(true);
      expect(result.to).toBe("anychannel");
    });

    it("should use first allowlist entry when no target provided", () => {
      const result = twitchOutbound.resolveTarget({
        to: undefined,
        mode: "implicit",
        allowFrom: ["#fallback", "#other"],
      });

      expect(result.ok).toBe(true);
      expect(result.to).toBe("fallback");
    });

    it("should return error when no target and no allowlist", () => {
      const result = twitchOutbound.resolveTarget({
        to: undefined,
        mode: "explicit",
        allowFrom: [],
      });

      expect(result.ok).toBe(false);
      expect(result.error).toContain("Missing target");
    });

    it("should handle whitespace-only target", () => {
      const result = twitchOutbound.resolveTarget({
        to: "   ",
        mode: "explicit",
        allowFrom: [],
      });

      expect(result.ok).toBe(false);
      expect(result.error).toContain("Missing target");
    });

    it("should filter wildcard from allowlist when checking membership", () => {
      const result = twitchOutbound.resolveTarget({
        to: "#mychannel",
        mode: "implicit",
        allowFrom: ["*", "#specific"],
      });

      // With wildcard, any target is accepted
      expect(result.ok).toBe(true);
      expect(result.to).toBe("mychannel");
    });
  });

  describe("sendText", () => {
    it("should send message successfully", async () => {
      const { getAccountConfig } = await import("./config.js");
      const { sendMessageTwitchInternal } = await import("./send.js");

      vi.mocked(getAccountConfig).mockReturnValue(mockAccount);
      vi.mocked(sendMessageTwitchInternal).mockResolvedValue({
        ok: true,
        messageId: "twitch-msg-123",
      });

      const result = await twitchOutbound.sendText({
        cfg: mockConfig,
        to: "#testchannel",
        text: "Hello Twitch!",
        accountId: "default",
      });

      expect(result.channel).toBe("twitch");
      expect(result.messageId).toBe("twitch-msg-123");
      expect(result.to).toBe("testchannel");
      expect(result.timestamp).toBeGreaterThan(0);
    });

    it("should throw when account not found", async () => {
      const { getAccountConfig } = await import("./config.js");

      vi.mocked(getAccountConfig).mockReturnValue(null);

      await expect(
        twitchOutbound.sendText({
          cfg: mockConfig,
          to: "#testchannel",
          text: "Hello!",
          accountId: "nonexistent",
        }),
      ).rejects.toThrow("Twitch account not found: nonexistent");
    });

    it("should throw when no channel specified", async () => {
      const { getAccountConfig } = await import("./config.js");

      const accountWithoutChannel = { ...mockAccount, channel: undefined as unknown as string };
      vi.mocked(getAccountConfig).mockReturnValue(accountWithoutChannel);

      await expect(
        twitchOutbound.sendText({
          cfg: mockConfig,
          to: undefined,
          text: "Hello!",
          accountId: "default",
        }),
      ).rejects.toThrow("No channel specified");
    });

    it("should use account channel when target not provided", async () => {
      const { getAccountConfig } = await import("./config.js");
      const { sendMessageTwitchInternal } = await import("./send.js");

      vi.mocked(getAccountConfig).mockReturnValue(mockAccount);
      vi.mocked(sendMessageTwitchInternal).mockResolvedValue({
        ok: true,
        messageId: "msg-456",
      });

      await twitchOutbound.sendText({
        cfg: mockConfig,
        to: undefined,
        text: "Hello!",
        accountId: "default",
      });

      expect(sendMessageTwitchInternal).toHaveBeenCalledWith(
        "testchannel",
        "Hello!",
        mockConfig,
        "default",
        true,
        console,
      );
    });

    it("should handle abort signal", async () => {
      const abortController = new AbortController();
      abortController.abort();

      await expect(
        twitchOutbound.sendText({
          cfg: mockConfig,
          to: "#testchannel",
          text: "Hello!",
          accountId: "default",
          signal: abortController.signal,
        }),
      ).rejects.toThrow("Outbound delivery aborted");
    });

    it("should throw on send failure", async () => {
      const { getAccountConfig } = await import("./config.js");
      const { sendMessageTwitchInternal } = await import("./send.js");

      vi.mocked(getAccountConfig).mockReturnValue(mockAccount);
      vi.mocked(sendMessageTwitchInternal).mockResolvedValue({
        ok: false,
        messageId: "failed-msg",
        error: "Connection lost",
      });

      await expect(
        twitchOutbound.sendText({
          cfg: mockConfig,
          to: "#testchannel",
          text: "Hello!",
          accountId: "default",
        }),
      ).rejects.toThrow("Connection lost");
    });
  });

  describe("sendMedia", () => {
    it("should combine text and media URL", async () => {
      const { sendMessageTwitchInternal } = await import("./send.js");
      const { getAccountConfig } = await import("./config.js");

      vi.mocked(getAccountConfig).mockReturnValue(mockAccount);
      vi.mocked(sendMessageTwitchInternal).mockResolvedValue({
        ok: true,
        messageId: "media-msg-123",
      });

      const result = await twitchOutbound.sendMedia({
        cfg: mockConfig,
        to: "#testchannel",
        text: "Check this:",
        mediaUrl: "https://example.com/image.png",
        accountId: "default",
      });

      expect(result.channel).toBe("twitch");
      expect(result.messageId).toBe("media-msg-123");
      expect(sendMessageTwitchInternal).toHaveBeenCalledWith(
        expect.anything(),
        "Check this: https://example.com/image.png",
        expect.anything(),
        expect.anything(),
        expect.anything(),
        expect.anything(),
      );
    });

    it("should send media URL only when no text", async () => {
      const { sendMessageTwitchInternal } = await import("./send.js");
      const { getAccountConfig } = await import("./config.js");

      vi.mocked(getAccountConfig).mockReturnValue(mockAccount);
      vi.mocked(sendMessageTwitchInternal).mockResolvedValue({
        ok: true,
        messageId: "media-only-msg",
      });

      await twitchOutbound.sendMedia({
        cfg: mockConfig,
        to: "#testchannel",
        text: undefined,
        mediaUrl: "https://example.com/image.png",
        accountId: "default",
      });

      expect(sendMessageTwitchInternal).toHaveBeenCalledWith(
        expect.anything(),
        "https://example.com/image.png",
        expect.anything(),
        expect.anything(),
        expect.anything(),
        expect.anything(),
      );
    });

    it("should handle abort signal", async () => {
      const abortController = new AbortController();
      abortController.abort();

      await expect(
        twitchOutbound.sendMedia({
          cfg: mockConfig,
          to: "#testchannel",
          text: "Check this:",
          mediaUrl: "https://example.com/image.png",
          accountId: "default",
          signal: abortController.signal,
        }),
      ).rejects.toThrow("Outbound delivery aborted");
    });
  });
});