Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 21, 04:45 UTC
| 1 | import { describe, it, expect, vi, beforeEach, afterEach, Mock } from 'vitest'; |
| 2 | import { Triggers } from '../../src/models/Triggers'; |
| 3 | import ComposioClient, { APIError } from '@composio/client'; |
| 4 | import logger from '../../src/utils/logger'; |
| 5 | import { |
| 6 | TriggerSubscribeParams, |
| 7 | TriggerData, |
| 8 | IncomingTriggerPayload, |
| 9 | IncomingTriggerPayloadSchema, |
| 10 | } from '../../src/types/triggers.types'; |
| 11 | import { telemetry } from '../../src/telemetry/Telemetry'; |
| 12 | import { ValidationError } from '../../src/errors'; |
| 13 | import { PusherService } from '../../src/services/pusher/Pusher'; |
| 14 | import { |
| 15 | ComposioFailedToSubscribeToPusherChannelError, |
| 16 | ComposioTriggerTypeNotFoundError, |
| 17 | ComposioWebhookSignatureVerificationError, |
| 18 | } from '../../src/errors/TriggerErrors'; |
| 19 | |
| 20 | // Mock dependencies |
| 21 | vi.mock('../../src/utils/logger'); |
| 22 | vi.mock('../../src/telemetry/Telemetry', () => ({ |
| 23 | telemetry: { |
| 24 | instrument: vi.fn(), |
| 25 | }, |
| 26 | })); |
| 27 | vi.mock('../../src/services/pusher/Pusher'); |
| 28 | |
| 29 | // Create mock client with trigger-related methods |
| 30 | const createMockClient = () => ({ |
| 31 | baseURL: 'https://api.composio.dev', |
| 32 | apiKey: 'test-api-key', |
| 33 | webhookSubscriptions: { |
| 34 | list: vi.fn(), |
| 35 | create: vi.fn(), |
| 36 | update: vi.fn(), |
| 37 | }, |
| 38 | triggerInstances: { |
| 39 | listActive: vi.fn(), |
| 40 | upsert: vi.fn(), |
| 41 | manage: { |
| 42 | delete: vi.fn(), |
| 43 | update: vi.fn(), |
| 44 | }, |
| 45 | }, |
| 46 | triggersTypes: { |
| 47 | list: vi.fn(), |
| 48 | retrieve: vi.fn(), |
| 49 | retrieveEnum: vi.fn(), |
| 50 | }, |
| 51 | connectedAccounts: { |
| 52 | list: vi.fn(), |
| 53 | }, |
| 54 | }); |
| 55 | |
| 56 | // Mock response data |
| 57 | const mockTriggerInstances = { |
| 58 | items: [ |
| 59 | { |
| 60 | id: 'trigger-1', |
| 61 | connected_account_id: 'conn-123', |
| 62 | disabled_at: null, |
| 63 | state: { lastRun: '2024-01-01T00:00:00Z' }, |
| 64 | trigger_config: { webhook_url: 'https://example.com/webhook' }, |
| 65 | trigger_name: 'github_webhook', |
| 66 | updated_at: '2024-01-01T00:00:00Z', |
| 67 | trigger_data: '{"event":"push"}', |
| 68 | uuid: 'uuid-123', |
| 69 | type: 'webhook', |
| 70 | fallback_reason: null, |
| 71 | polling_interval: null, |
| 72 | }, |
| 73 | { |
| 74 | id: 'trigger-2', |
| 75 | connected_account_id: 'conn-456', |
| 76 | disabled_at: '2024-01-02T00:00:00Z', |
| 77 | state: { lastRun: '2024-01-02T00:00:00Z' }, |
| 78 | trigger_config: { channel: '#general' }, |
| 79 | trigger_name: 'slack_message', |
| 80 | updated_at: '2024-01-02T00:00:00Z', |
| 81 | trigger_data: '{"event":"message"}', |
| 82 | uuid: 'uuid-456', |
| 83 | type: 'poll', |
| 84 | fallback_reason: 'No webhook endpoint is set up for this auth config.', |
| 85 | polling_interval: 15, |
| 86 | }, |
| 87 | ], |
| 88 | next_cursor: null, |
| 89 | total_pages: 1, |
| 90 | }; |
| 91 | |
| 92 | const mockTriggerUpsertResponse = { |
| 93 | trigger_id: 'trigger-123', |
| 94 | type: 'webhook', |
| 95 | fallback_reason: null, |
| 96 | polling_interval: null, |
| 97 | }; |
| 98 | |
| 99 | const expectedUpsertResult = { |
| 100 | triggerId: mockTriggerUpsertResponse.trigger_id, |
| 101 | type: mockTriggerUpsertResponse.type, |
| 102 | fallbackReason: mockTriggerUpsertResponse.fallback_reason, |
| 103 | pollingInterval: mockTriggerUpsertResponse.polling_interval, |
| 104 | }; |
| 105 | |
| 106 | const mockTriggerUpdateResponse = { |
| 107 | status: 'success', |
| 108 | }; |
| 109 | |
| 110 | const mockTriggerDeleteResponse = { |
| 111 | trigger_id: 'trigger-123', |
| 112 | }; |
| 113 | |
| 114 | const mockTriggerTypes = { |
| 115 | items: [ |
| 116 | { |
| 117 | slug: 'github_webhook', |
| 118 | name: 'GitHub Webhook', |
| 119 | description: 'Triggered when a GitHub event occurs', |
| 120 | // instructions: 'Instructions', |
| 121 | config: { |
| 122 | required: ['webhook_url'], |
| 123 | optional: ['secret'], |
| 124 | }, |
| 125 | payload: { |
| 126 | action: 'push', |
| 127 | repository: 'test-repo', |
| 128 | }, |
| 129 | toolkit: { |
| 130 | slug: 'github', |
| 131 | name: 'github', |
| 132 | logo: 'https://example.com/github.png', |
| 133 | }, |
| 134 | version: '20250101_00', |
| 135 | type: 'webhook', |
| 136 | types: ['webhook'], |
| 137 | requires_webhook_endpoint_setup: false, |
| 138 | }, |
| 139 | ], |
| 140 | total_pages: 1, |
| 141 | next_cursor: null, |
| 142 | }; |
| 143 | |
| 144 | const mockTriggerType = { |
| 145 | slug: 'github_webhook', |
| 146 | name: 'GitHub Webhook', |
| 147 | description: 'Triggered when a GitHub event occurs', |
| 148 | instructions: 'Instructions', |
| 149 | config: { |
| 150 | required: ['webhook_url'], |
| 151 | optional: ['secret'], |
| 152 | }, |
| 153 | payload: { |
| 154 | action: 'push', |
| 155 | repository: 'test-repo', |
| 156 | }, |
| 157 | toolkit: { |
| 158 | slug: 'github', |
| 159 | name: 'github', |
| 160 | logo: 'https://example.com/github.png', |
| 161 | }, |
| 162 | version: '20250101_00', |
| 163 | type: 'poll', |
| 164 | types: ['webhook', 'poll'], |
| 165 | requires_webhook_endpoint_setup: true, |
| 166 | }; |
| 167 | |
| 168 | const toTriggerType = <T extends { requires_webhook_endpoint_setup?: boolean }>({ |
| 169 | requires_webhook_endpoint_setup, |
| 170 | ...rest |
| 171 | }: T) => ({ ...rest, requiresWebhookEndpointSetup: requires_webhook_endpoint_setup }); |
| 172 | |
| 173 | const mockTriggerEnum = { |
| 174 | enum: ['github_webhook', 'slack_message', 'email_received'], |
| 175 | }; |
| 176 | |
| 177 | const mockSessionInfo = { |
| 178 | project: { |
| 179 | id: 'client-123', |
| 180 | name: 'Test Project', |
| 181 | }, |
| 182 | user: { |
| 183 | id: 'user-456', |
| 184 | email: 'test@example.com', |
| 185 | }, |
| 186 | }; |
| 187 | |
| 188 | const mockTriggerData: TriggerData = { |
| 189 | appName: 'github', |
| 190 | clientId: 123, |
| 191 | payload: { action: 'push', repository: 'test-repo' }, |
| 192 | originalPayload: { action: 'push', repository: 'test-repo' }, |
| 193 | metadata: { |
| 194 | id: 'trigger-123', |
| 195 | nanoId: 'trigger-123-nano', |
| 196 | triggerName: 'github_webhook', |
| 197 | triggerData: '{"action":"push"}', |
| 198 | triggerConfig: { webhook_url: 'https://example.com/webhook' }, |
| 199 | connection: { |
| 200 | id: 'conn-123', |
| 201 | connectedAccountNanoId: 'conn-123', |
| 202 | integrationId: 'github', |
| 203 | authConfigNanoId: 'auth-123', |
| 204 | clientUniqueUserId: 'user-456', |
| 205 | status: 'ACTIVE', |
| 206 | }, |
| 207 | }, |
| 208 | }; |
| 209 | |
| 210 | const mockIncomingTriggerPayload: IncomingTriggerPayload = { |
| 211 | id: 'trigger-123-nano', |
| 212 | uuid: 'trigger-123', |
| 213 | triggerSlug: 'github_webhook', |
| 214 | toolkitSlug: 'github', |
| 215 | userId: 'user-456', |
| 216 | payload: { action: 'push', repository: 'test-repo' }, |
| 217 | originalPayload: { action: 'push', repository: 'test-repo' }, |
| 218 | metadata: { |
| 219 | id: 'trigger-123-nano', |
| 220 | uuid: 'trigger-123', |
| 221 | toolkitSlug: 'github', |
| 222 | triggerSlug: 'github_webhook', |
| 223 | triggerData: '{"action":"push"}', |
| 224 | triggerConfig: { webhook_url: 'https://example.com/webhook' }, |
| 225 | connectedAccount: { |
| 226 | id: 'conn-123', |
| 227 | uuid: 'conn-123', |
| 228 | authConfigId: 'auth-123', |
| 229 | authConfigUUID: 'github', |
| 230 | userId: 'user-456', |
| 231 | status: 'ACTIVE', |
| 232 | }, |
| 233 | }, |
| 234 | }; |
| 235 | |
| 236 | describe('Triggers', () => { |
| 237 | let triggers: Triggers<unknown>; |
| 238 | let mockClient: ReturnType<typeof createMockClient>; |
| 239 | let mockPusherService: { |
| 240 | subscribe: Mock; |
| 241 | unsubscribe: Mock; |
| 242 | }; |
| 243 | |
| 244 | beforeEach(() => { |
| 245 | vi.clearAllMocks(); |
| 246 | |
| 247 | mockClient = createMockClient(); |
| 248 | mockPusherService = { |
| 249 | subscribe: vi.fn(), |
| 250 | unsubscribe: vi.fn(), |
| 251 | } as unknown as { subscribe: Mock; unsubscribe: Mock }; |
| 252 | |
| 253 | // Mock PusherService constructor |
| 254 | (PusherService as unknown as Mock).mockImplementation(function () { |
| 255 | return mockPusherService; |
| 256 | }); |
| 257 | |
| 258 | triggers = new Triggers(mockClient as unknown as ComposioClient); |
| 259 | }); |
| 260 | |
| 261 | afterEach(() => { |
| 262 | vi.resetAllMocks(); |
| 263 | }); |
| 264 | |
| 265 | describe('constructor', () => { |
| 266 | it('should create an instance successfully', () => { |
| 267 | expect(triggers).toBeInstanceOf(Triggers); |
| 268 | expect(telemetry.instrument).toHaveBeenCalledWith(triggers, 'Triggers'); |
| 269 | }); |
| 270 | }); |
| 271 | |
| 272 | describe('setWebhookSubscription', () => { |
| 273 | const webhookUrl = 'https://example.com/webhooks/composio'; |
| 274 | const rawSubscription = { |
| 275 | id: 'sub_123', |
| 276 | webhook_url: webhookUrl, |
| 277 | version: 'V3', |
| 278 | enabled_events: ['composio.trigger.message'], |
| 279 | secret: 'whsec_123', |
| 280 | created_at: '2026-01-01T00:00:00Z', |
| 281 | updated_at: '2026-01-01T00:00:00Z', |
| 282 | }; |
| 283 | |
| 284 | it('should create a webhook subscription when none exists', async () => { |
| 285 | mockClient.webhookSubscriptions.list.mockResolvedValue({ items: [] }); |
| 286 | mockClient.webhookSubscriptions.create.mockResolvedValue(rawSubscription); |
| 287 | |
| 288 | const result = await triggers.setWebhookSubscription({ webhookUrl }); |
| 289 | |
| 290 | expect(mockClient.webhookSubscriptions.list).toHaveBeenCalledWith({ limit: 1 }, undefined); |
| 291 | expect(mockClient.webhookSubscriptions.create).toHaveBeenCalledWith( |
| 292 | { |
| 293 | webhook_url: webhookUrl, |
| 294 | enabled_events: ['composio.trigger.message'], |
| 295 | version: 'V3', |
| 296 | }, |
| 297 | undefined |
| 298 | ); |
| 299 | expect(mockClient.webhookSubscriptions.update).not.toHaveBeenCalled(); |
| 300 | // Only camelCase keys — the snake_case wire fields must not leak through. |
| 301 | expect(result).toEqual({ |
| 302 | id: 'sub_123', |
| 303 | webhookUrl, |
| 304 | version: 'V3', |
| 305 | enabledEvents: ['composio.trigger.message'], |
| 306 | secret: 'whsec_123', |
| 307 | createdAt: '2026-01-01T00:00:00Z', |
| 308 | updatedAt: '2026-01-01T00:00:00Z', |
| 309 | }); |
| 310 | }); |
| 311 | |
| 312 | it('should update the first webhook subscription when one exists', async () => { |
| 313 | mockClient.webhookSubscriptions.list.mockResolvedValue({ items: [{ id: 'sub_123' }] }); |
| 314 | mockClient.webhookSubscriptions.update.mockResolvedValue(rawSubscription); |
| 315 | |
| 316 | await triggers.setWebhookSubscription({ |
| 317 | webhookUrl, |
| 318 | enabledEvents: ['composio.trigger.message', 'composio.connected_account.expired'], |
| 319 | version: 'V3', |
| 320 | }); |
| 321 | |
| 322 | expect(mockClient.webhookSubscriptions.update).toHaveBeenCalledWith( |
| 323 | 'sub_123', |
| 324 | { |
| 325 | webhook_url: webhookUrl, |
| 326 | enabled_events: ['composio.trigger.message', 'composio.connected_account.expired'], |
| 327 | version: 'V3', |
| 328 | }, |
| 329 | undefined |
| 330 | ); |
| 331 | expect(mockClient.webhookSubscriptions.create).not.toHaveBeenCalled(); |
| 332 | }); |
| 333 | |
| 334 | it('should throw validation error for invalid webhook subscription parameters', async () => { |
| 335 | await expect( |
| 336 | triggers.setWebhookSubscription({ webhookUrl, enabledEvents: [] }) |
| 337 | ).rejects.toThrow(ValidationError); |
| 338 | expect(mockClient.webhookSubscriptions.list).not.toHaveBeenCalled(); |
| 339 | }); |
| 340 | }); |
| 341 | |
| 342 | describe('parse', () => { |
| 343 | const webhookSecret = 'test-webhook-secret-12345'; |
| 344 | const webhookId = 'msg_test123'; |
| 345 | |
| 346 | const v3Payload = { |
| 347 | id: 'evt-123', |
| 348 | timestamp: '2026-01-28T12:00:00Z', |
| 349 | type: 'composio.trigger.message', |
| 350 | metadata: { |
| 351 | log_id: 'log-789', |
| 352 | trigger_slug: 'GMAIL_NEW_GMAIL_MESSAGE', |
| 353 | trigger_id: 'trigger-456', |
| 354 | connected_account_id: 'conn-123', |
| 355 | auth_config_id: 'auth-456', |
| 356 | user_id: 'user-789', |
| 357 | }, |
| 358 | data: { subject: 'Test email', from: 'test@example.com' }, |
| 359 | }; |
| 360 | |
| 361 | // Mirrors the signing format used by Composio: HMAC-SHA256(id.timestamp.payload). |
| 362 | const createSignature = async (timestamp: string, payload: string): Promise<string> => { |
| 363 | const { createHmac } = await import('node:crypto'); |
| 364 | const signature = createHmac('sha256', webhookSecret) |
| 365 | .update(`${webhookId}.${timestamp}.${payload}`) |
| 366 | .digest('base64'); |
| 367 | return `v1,${signature}`; |
| 368 | }; |
| 369 | |
| 370 | it('should parse and verify from a Fetch Request with a valid signature', async () => { |
| 371 | const timestamp = String(Math.floor(Date.now() / 1000)); |
| 372 | const body = JSON.stringify(v3Payload); |
| 373 | const signature = await createSignature(timestamp, body); |
| 374 | |
| 375 | const request = new Request('https://example.com/webhooks/composio', { |
| 376 | method: 'POST', |
| 377 | headers: { |
| 378 | 'webhook-id': webhookId, |
| 379 | 'webhook-timestamp': timestamp, |
| 380 | 'webhook-signature': signature, |
| 381 | }, |
| 382 | body, |
| 383 | }); |
| 384 | |
| 385 | const result = await triggers.parse(request, { verifySecret: webhookSecret }); |
| 386 | |
| 387 | expect(result.version).toBe('V3'); |
| 388 | expect(result.payload.triggerSlug).toBe('GMAIL_NEW_GMAIL_MESSAGE'); |
| 389 | expect(result.payload.payload).toEqual({ |
| 390 | subject: 'Test email', |
| 391 | from: 'test@example.com', |
| 392 | }); |
| 393 | }); |
| 394 | |
| 395 | it('should parse from an Express-style { body, headers } without verifying', async () => { |
| 396 | const body = JSON.stringify(v3Payload); |
| 397 | |
| 398 | const result = await triggers.parse({ |
| 399 | body: new TextEncoder().encode(body), |
| 400 | headers: {}, |
| 401 | }); |
| 402 | |
| 403 | expect(result.version).toBe('V3'); |
| 404 | expect(result.payload.triggerSlug).toBe('GMAIL_NEW_GMAIL_MESSAGE'); |
| 405 | expect(result.payload.payload).toEqual({ |
| 406 | subject: 'Test email', |
| 407 | from: 'test@example.com', |
| 408 | }); |
| 409 | }); |
| 410 | |
| 411 | it('should throw when verifySecret is set but the signature is invalid', async () => { |
| 412 | const timestamp = String(Math.floor(Date.now() / 1000)); |
| 413 | const body = JSON.stringify(v3Payload); |
| 414 | |
| 415 | const request = new Request('https://example.com/webhooks/composio', { |
| 416 | method: 'POST', |
| 417 | headers: { |
| 418 | 'webhook-id': webhookId, |
| 419 | 'webhook-timestamp': timestamp, |
| 420 | 'webhook-signature': 'v1,not-a-valid-signature', |
| 421 | }, |
| 422 | body, |
| 423 | }); |
| 424 | |
| 425 | await expect(triggers.parse(request, { verifySecret: webhookSecret })).rejects.toThrow( |
| 426 | ComposioWebhookSignatureVerificationError |
| 427 | ); |
| 428 | }); |
| 429 | |
| 430 | it('should throw a helpful ValidationError when signature headers are missing', async () => { |
| 431 | const body = JSON.stringify(v3Payload); |
| 432 | |
| 433 | await expect( |
| 434 | triggers.parse({ body, headers: {} }, { verifySecret: webhookSecret }) |
| 435 | ).rejects.toThrow(ValidationError); |
| 436 | |
| 437 | await expect( |
| 438 | triggers.parse({ body, headers: {} }, { verifySecret: webhookSecret }) |
| 439 | ).rejects.toThrow(/missing signature header/i); |
| 440 | }); |
| 441 | }); |
| 442 | |
| 443 | describe('list', () => { |
| 444 | it('should list active trigger instances', async () => { |
| 445 | mockClient.triggerInstances.listActive.mockResolvedValue(mockTriggerInstances); |
| 446 | |
| 447 | const result = await triggers.listActive(); |
| 448 | |
| 449 | expect(mockClient.triggerInstances.listActive).toHaveBeenCalledWith(undefined, undefined); |
| 450 | expect(result).toEqual({ |
| 451 | items: mockTriggerInstances.items.map(item => ({ |
| 452 | id: item.id, |
| 453 | connectedAccountId: item.connected_account_id, |
| 454 | disabledAt: item.disabled_at, |
| 455 | state: item.state, |
| 456 | triggerConfig: item.trigger_config, |
| 457 | triggerName: item.trigger_name, |
| 458 | updatedAt: item.updated_at, |
| 459 | triggerData: item.trigger_data, |
| 460 | uuid: item.uuid, |
| 461 | type: item.type, |
| 462 | fallbackReason: item.fallback_reason, |
| 463 | pollingInterval: item.polling_interval, |
| 464 | })), |
| 465 | nextCursor: null, |
| 466 | totalPages: 1, |
| 467 | }); |
| 468 | }); |
| 469 | |
| 470 | it('should list active trigger instances with query parameters', async () => { |
| 471 | const query = { |
| 472 | authConfigIds: ['auth-1'], |
| 473 | connectedAccountIds: ['conn-1'], |
| 474 | limit: 5, |
| 475 | cursor: 'cursor-abc', |
| 476 | showDisabled: true, |
| 477 | triggerIds: ['trigger-1'], |
| 478 | triggerNames: ['github_webhook'], |
| 479 | }; |
| 480 | |
| 481 | mockClient.triggerInstances.listActive.mockResolvedValue(mockTriggerInstances); |
| 482 | |
| 483 | await triggers.listActive(query); |
| 484 | |
| 485 | expect(mockClient.triggerInstances.listActive).toHaveBeenCalledWith( |
| 486 | { |
| 487 | auth_config_ids: query.authConfigIds, |
| 488 | connected_account_ids: query.connectedAccountIds, |
| 489 | limit: query.limit, |
| 490 | cursor: query.cursor, |
| 491 | show_disabled: query.showDisabled, |
| 492 | trigger_ids: query.triggerIds, |
| 493 | trigger_names: query.triggerNames, |
| 494 | }, |
| 495 | undefined |
| 496 | ); |
| 497 | }); |
| 498 | }); |
| 499 | |
| 500 | describe('create', () => { |
| 501 | const userId = 'user-123'; |
| 502 | const slug = 'github_webhook'; |
| 503 | const body = { |
| 504 | connectedAccountId: 'conn-123', |
| 505 | triggerConfig: { webhook_url: 'https://example.com/webhook' }, |
| 506 | }; |
| 507 | |
| 508 | beforeEach(() => { |
| 509 | mockClient.triggersTypes.retrieve.mockResolvedValue(mockTriggerType); |
| 510 | mockClient.triggerInstances.upsert.mockResolvedValue(mockTriggerUpsertResponse); |
| 511 | }); |
| 512 | |
| 513 | it('should pass user_id and the explicit connected account ID to upsert (no extra lookup)', async () => { |
| 514 | const result = await triggers.create(userId, slug, body); |
| 515 | |
| 516 | expect(mockClient.triggersTypes.retrieve).toHaveBeenCalledWith( |
| 517 | slug, |
| 518 | { |
| 519 | toolkit_versions: 'latest', |
| 520 | }, |
| 521 | undefined |
| 522 | ); |
| 523 | // The backend now resolves/validates the connection — the SDK no longer |
| 524 | // lists connected accounts to find one. |
| 525 | expect(mockClient.connectedAccounts.list).not.toHaveBeenCalled(); |
| 526 | expect(mockClient.triggerInstances.upsert).toHaveBeenCalledWith( |
| 527 | slug, |
| 528 | { |
| 529 | connected_account_id: body.connectedAccountId, |
| 530 | trigger_config: body.triggerConfig, |
| 531 | toolkit_versions: 'latest', |
| 532 | user_id: userId, |
| 533 | }, |
| 534 | undefined |
| 535 | ); |
| 536 | expect(result).toEqual(expectedUpsertResult); |
| 537 | }); |
| 538 | |
| 539 | it('should pass type and pollingInterval, and return the type, fallback reason and interval', async () => { |
| 540 | mockClient.triggerInstances.upsert.mockResolvedValue({ |
| 541 | trigger_id: 'trigger-123', |
| 542 | type: 'poll', |
| 543 | fallback_reason: 'No webhook endpoint is set up for this auth config.', |
| 544 | polling_interval: 15, |
| 545 | }); |
| 546 | |
| 547 | const result = await triggers.create(userId, slug, { |
| 548 | ...body, |
| 549 | type: 'poll', |
| 550 | pollingInterval: 15, |
| 551 | }); |
| 552 | |
| 553 | expect(mockClient.triggerInstances.upsert).toHaveBeenCalledWith( |
| 554 | slug, |
| 555 | { |
| 556 | connected_account_id: body.connectedAccountId, |
| 557 | trigger_config: body.triggerConfig, |
| 558 | type: 'poll', |
| 559 | polling_interval: 15, |
| 560 | toolkit_versions: 'latest', |
| 561 | user_id: userId, |
| 562 | }, |
| 563 | undefined |
| 564 | ); |
| 565 | expect(result).toEqual({ |
| 566 | triggerId: 'trigger-123', |
| 567 | type: 'poll', |
| 568 | fallbackReason: 'No webhook endpoint is set up for this auth config.', |
| 569 | pollingInterval: 15, |
| 570 | }); |
| 571 | }); |
| 572 | |
| 573 | it.each([ |
| 574 | { case: 'an unknown type', extra: { type: 'email' } }, |
| 575 | { case: 'a fractional pollingInterval', extra: { pollingInterval: 1.5 } }, |
| 576 | { case: 'a zero pollingInterval', extra: { pollingInterval: 0 } }, |
| 577 | ])('should reject $case before calling the API', async ({ extra }) => { |
| 578 | await expect(triggers.create(userId, slug, { ...body, ...extra } as unknown)).rejects.toThrow( |
| 579 | ValidationError |
| 580 | ); |
| 581 | expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled(); |
| 582 | }); |
| 583 | |
| 584 | it('should let the backend auto-resolve the connection when no connected account ID is provided', async () => { |
| 585 | const bodyWithoutConnectedAccount = { |
| 586 | triggerConfig: body.triggerConfig, |
| 587 | }; |
| 588 | |
| 589 | const result = await triggers.create(userId, slug, bodyWithoutConnectedAccount); |
| 590 | |
| 591 | expect(mockClient.connectedAccounts.list).not.toHaveBeenCalled(); |
| 592 | expect(mockClient.triggerInstances.upsert).toHaveBeenCalledWith( |
| 593 | slug, |
| 594 | { |
| 595 | connected_account_id: undefined, |
| 596 | trigger_config: bodyWithoutConnectedAccount.triggerConfig, |
| 597 | toolkit_versions: 'latest', |
| 598 | user_id: userId, |
| 599 | }, |
| 600 | undefined |
| 601 | ); |
| 602 | // `toEqual` treats a present-but-undefined key the same as an absent one, |
| 603 | // so assert explicitly that the SDK does not invent a connected account id |
| 604 | // (the client drops the undefined field on the wire, letting the backend |
| 605 | // resolve it). |
| 606 | const upsertParams = mockClient.triggerInstances.upsert.mock.calls[0][1]; |
| 607 | expect(upsertParams.connected_account_id).toBeUndefined(); |
| 608 | expect(result).toEqual(expectedUpsertResult); |
| 609 | }); |
| 610 | |
| 611 | it('should throw a validation error when userId is empty', async () => { |
| 612 | await expect(triggers.create('', slug, body)).rejects.toThrow(ValidationError); |
| 613 | await expect(triggers.create(' ', slug, body)).rejects.toThrow(ValidationError); |
| 614 | expect(mockClient.triggersTypes.retrieve).not.toHaveBeenCalled(); |
| 615 | expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled(); |
| 616 | }); |
| 617 | |
| 618 | it('should throw validation error for invalid body parameters', async () => { |
| 619 | const invalidBody = { |
| 620 | connectedAccountId: 123, // should be string |
| 621 | triggerConfig: null, |
| 622 | }; |
| 623 | |
| 624 | await expect(triggers.create(userId, slug, invalidBody as unknown)).rejects.toThrow( |
| 625 | ValidationError |
| 626 | ); |
| 627 | expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled(); |
| 628 | }); |
| 629 | |
| 630 | it('should throw error when trigger type is not found', async () => { |
| 631 | mockClient.triggersTypes.retrieve.mockRejectedValue( |
| 632 | new APIError(400, 'Trigger type not found', 'Trigger type not found', new Headers()) |
| 633 | ); |
| 634 | |
| 635 | await expect(triggers.create(userId, slug, body)).rejects.toThrow( |
| 636 | ComposioTriggerTypeNotFoundError |
| 637 | ); |
| 638 | expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled(); |
| 639 | }); |
| 640 | }); |
| 641 | |
| 642 | describe('update', () => { |
| 643 | it('should update a trigger instance status', async () => { |
| 644 | const triggerId = 'trigger-123'; |
| 645 | const body = { status: 'enable' as const }; |
| 646 | mockClient.triggerInstances.manage.update.mockResolvedValue(mockTriggerUpdateResponse); |
| 647 | |
| 648 | const result = await triggers.update(triggerId, body); |
| 649 | |
| 650 | expect(mockClient.triggerInstances.manage.update).toHaveBeenCalledWith( |
| 651 | triggerId, |
| 652 | body, |
| 653 | undefined |
| 654 | ); |
| 655 | expect(result).toEqual(mockTriggerUpdateResponse); |
| 656 | }); |
| 657 | }); |
| 658 | |
| 659 | describe('delete', () => { |
| 660 | it('should delete a trigger instance', async () => { |
| 661 | const triggerId = 'trigger-123'; |
| 662 | mockClient.triggerInstances.manage.delete.mockResolvedValue(mockTriggerDeleteResponse); |
| 663 | |
| 664 | const result = await triggers.delete(triggerId); |
| 665 | |
| 666 | expect(mockClient.triggerInstances.manage.delete).toHaveBeenCalledWith(triggerId, undefined); |
| 667 | expect(result).toEqual({ triggerId: mockTriggerDeleteResponse.trigger_id }); |
| 668 | }); |
| 669 | }); |
| 670 | |
| 671 | describe('disable', () => { |
| 672 | it('should disable a trigger instance', async () => { |
| 673 | const triggerId = 'trigger-123'; |
| 674 | mockClient.triggerInstances.manage.update.mockResolvedValue(mockTriggerUpdateResponse); |
| 675 | |
| 676 | const result = await triggers.disable(triggerId); |
| 677 | |
| 678 | expect(mockClient.triggerInstances.manage.update).toHaveBeenCalledWith( |
| 679 | triggerId, |
| 680 | { |
| 681 | status: 'disable', |
| 682 | }, |
| 683 | undefined |
| 684 | ); |
| 685 | expect(result).toEqual(mockTriggerUpdateResponse); |
| 686 | }); |
| 687 | }); |
| 688 | |
| 689 | describe('enable', () => { |
| 690 | it('should enable a trigger instance', async () => { |
| 691 | const triggerId = 'trigger-123'; |
| 692 | mockClient.triggerInstances.manage.update.mockResolvedValue(mockTriggerUpdateResponse); |
| 693 | |
| 694 | const result = await triggers.enable(triggerId); |
| 695 | |
| 696 | expect(mockClient.triggerInstances.manage.update).toHaveBeenCalledWith( |
| 697 | triggerId, |
| 698 | { |
| 699 | status: 'enable', |
| 700 | }, |
| 701 | undefined |
| 702 | ); |
| 703 | expect(result).toEqual(mockTriggerUpdateResponse); |
| 704 | }); |
| 705 | }); |
| 706 | |
| 707 | describe('listTypes', () => { |
| 708 | it('should list all trigger types', async () => { |
| 709 | mockClient.triggersTypes.list.mockResolvedValue(mockTriggerTypes); |
| 710 | |
| 711 | const result = await triggers.listTypes(); |
| 712 | |
| 713 | expect(mockClient.triggersTypes.list).toHaveBeenCalledWith( |
| 714 | { |
| 715 | cursor: undefined, |
| 716 | limit: undefined, |
| 717 | toolkit_slugs: undefined, |
| 718 | toolkit_versions: 'latest', |
| 719 | }, |
| 720 | undefined |
| 721 | ); |
| 722 | expect(result).toEqual({ |
| 723 | items: mockTriggerTypes.items.map(item => ({ |
| 724 | ...toTriggerType(item), |
| 725 | payload: item.payload ?? {}, |
| 726 | })), |
| 727 | nextCursor: mockTriggerTypes.next_cursor, |
| 728 | totalPages: mockTriggerTypes.total_pages, |
| 729 | }); |
| 730 | }); |
| 731 | |
| 732 | it('should list trigger types with query parameters', async () => { |
| 733 | const query = { limit: 10, toolkits: ['github'] }; |
| 734 | mockClient.triggersTypes.list.mockResolvedValue(mockTriggerTypes); |
| 735 | |
| 736 | const result = await triggers.listTypes(query); |
| 737 | |
| 738 | expect(mockClient.triggersTypes.list).toHaveBeenCalledWith( |
| 739 | { |
| 740 | cursor: undefined, |
| 741 | limit: query.limit, |
| 742 | toolkit_slugs: query.toolkits, |
| 743 | toolkit_versions: 'latest', |
| 744 | }, |
| 745 | undefined |
| 746 | ); |
| 747 | expect(result).toEqual({ |
| 748 | items: mockTriggerTypes.items.map(toTriggerType), |
| 749 | nextCursor: mockTriggerTypes.next_cursor, |
| 750 | totalPages: mockTriggerTypes.total_pages, |
| 751 | }); |
| 752 | }); |
| 753 | }); |
| 754 | |
| 755 | describe('getType', () => { |
| 756 | it('should retrieve a trigger type by slug with default global toolkit versions', async () => { |
| 757 | const slug = 'github_webhook'; |
| 758 | mockClient.triggersTypes.retrieve.mockResolvedValue(mockTriggerType); |
| 759 | |
| 760 | const result = await triggers.getType(slug); |
| 761 | |
| 762 | expect(mockClient.triggersTypes.retrieve).toHaveBeenCalledWith( |
| 763 | slug, |
| 764 | { |
| 765 | toolkit_versions: 'latest', // Uses global default |
| 766 | }, |
| 767 | undefined |
| 768 | ); |
| 769 | expect(result).toEqual(toTriggerType(mockTriggerType)); |
| 770 | }); |
| 771 | |
| 772 | it('should use custom global toolkit versions when configured', async () => { |
| 773 | // Create a new triggers instance with custom toolkit versions |
| 774 | const customToolkitVersions = { github: '01012025_00', slack: '15012025_01' }; |
| 775 | const customTriggers = new Triggers(mockClient as unknown as ComposioClient, { |
| 776 | toolkitVersions: customToolkitVersions, |
| 777 | }); |
| 778 | const slug = 'github_webhook'; |
| 779 | mockClient.triggersTypes.retrieve.mockResolvedValue(mockTriggerType); |
| 780 | |
| 781 | const result = await customTriggers.getType(slug); |
| 782 | |
| 783 | expect(mockClient.triggersTypes.retrieve).toHaveBeenCalledWith( |
| 784 | slug, |
| 785 | { |
| 786 | toolkit_versions: customToolkitVersions, // Uses configured global versions |
| 787 | }, |
| 788 | undefined |
| 789 | ); |
| 790 | expect(result).toEqual(toTriggerType(mockTriggerType)); |
| 791 | }); |
| 792 | |
| 793 | it('should use "latest" as default when no toolkit versions are configured', async () => { |
| 794 | const slug = 'github_webhook'; |
| 795 | mockClient.triggersTypes.retrieve.mockResolvedValue(mockTriggerType); |
| 796 | |
| 797 | const result = await triggers.getType(slug); |
| 798 | |
| 799 | expect(mockClient.triggersTypes.retrieve).toHaveBeenCalledWith( |
| 800 | slug, |
| 801 | { |
| 802 | toolkit_versions: 'latest', // Default to latest |
| 803 | }, |
| 804 | undefined |
| 805 | ); |
| 806 | expect(result).toEqual(toTriggerType(mockTriggerType)); |
| 807 | }); |
| 808 | }); |
| 809 | |
| 810 | describe('listEnum', () => { |
| 811 | it('should fetch the list of all available trigger enums', async () => { |
| 812 | mockClient.triggersTypes.retrieveEnum.mockResolvedValue(mockTriggerEnum); |
| 813 | |
| 814 | const result = await triggers.listEnum(); |
| 815 | |
| 816 | expect(mockClient.triggersTypes.retrieveEnum).toHaveBeenCalled(); |
| 817 | expect(result).toEqual(mockTriggerEnum); |
| 818 | }); |
| 819 | }); |
| 820 | |
| 821 | describe('subscribe', () => { |
| 822 | const mockCallback = vi.fn(); |
| 823 | |
| 824 | beforeEach(() => { |
| 825 | mockCallback.mockClear(); |
| 826 | vi.mocked(logger.debug).mockClear(); |
| 827 | }); |
| 828 | |
| 829 | it('should throw error if function is not provided', async () => { |
| 830 | await expect(triggers.subscribe(null as unknown)).rejects.toThrow( |
| 831 | 'Function is required for trigger subscription' |
| 832 | ); |
| 833 | }); |
| 834 | |
| 835 | it('should subscribe to triggers without filters', async () => { |
| 836 | await triggers.subscribe(mockCallback); |
| 837 | |
| 838 | expect(mockPusherService.subscribe).toHaveBeenCalled(); |
| 839 | expect(logger.debug).toHaveBeenCalledWith('🔄 Subscribing to triggers with filters: ', '{}'); |
| 840 | }); |
| 841 | |
| 842 | it('should pass the subscription error callback through to the pusher service', async () => { |
| 843 | const onSubscriptionError = vi.fn(); |
| 844 | |
| 845 | await triggers.subscribe(mockCallback, {}, onSubscriptionError); |
| 846 | |
| 847 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 848 | expect(subscribeCall[1]).toBe(onSubscriptionError); |
| 849 | }); |
| 850 | |
| 851 | it('should subscribe to triggers with filters', async () => { |
| 852 | const filters: TriggerSubscribeParams = { |
| 853 | toolkits: ['github'], |
| 854 | triggerId: 'trigger-123', |
| 855 | connectedAccountId: 'conn-123', |
| 856 | triggerSlug: ['github_webhook'], |
| 857 | triggerData: '{"action":"push"}', |
| 858 | userId: 'user-456', |
| 859 | }; |
| 860 | |
| 861 | await triggers.subscribe(mockCallback, filters); |
| 862 | |
| 863 | expect(mockPusherService.subscribe).toHaveBeenCalled(); |
| 864 | expect(logger.debug).toHaveBeenCalledWith( |
| 865 | '🔄 Subscribing to triggers with filters: ', |
| 866 | JSON.stringify(filters, null, 2) |
| 867 | ); |
| 868 | }); |
| 869 | |
| 870 | it('should filter triggers based on toolkits case-insensitively', async () => { |
| 871 | const filters: TriggerSubscribeParams = { toolkits: ['GITHUB'] }; |
| 872 | await triggers.subscribe(mockCallback, filters); |
| 873 | |
| 874 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 875 | const filterCallback = subscribeCall[0]; |
| 876 | |
| 877 | filterCallback(mockTriggerData); |
| 878 | |
| 879 | expect(mockCallback).toHaveBeenCalledWith(mockIncomingTriggerPayload); |
| 880 | expect(mockCallback).toHaveBeenCalledTimes(1); |
| 881 | }); |
| 882 | |
| 883 | it('should log debug message when toolkit filter does not match', async () => { |
| 884 | const filters: TriggerSubscribeParams = { toolkits: ['slack'] }; |
| 885 | await triggers.subscribe(mockCallback, filters); |
| 886 | |
| 887 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 888 | const filterCallback = subscribeCall[0]; |
| 889 | |
| 890 | filterCallback(mockTriggerData); |
| 891 | |
| 892 | expect(mockCallback).not.toHaveBeenCalled(); |
| 893 | expect(logger.debug).toHaveBeenCalledWith( |
| 894 | 'Trigger does not match toolkits filter', |
| 895 | expect.any(String) |
| 896 | ); |
| 897 | }); |
| 898 | |
| 899 | it('should log debug message when triggerId filter does not match', async () => { |
| 900 | const filters: TriggerSubscribeParams = { triggerId: 'trigger-456' }; |
| 901 | await triggers.subscribe(mockCallback, filters); |
| 902 | |
| 903 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 904 | const filterCallback = subscribeCall[0]; |
| 905 | |
| 906 | filterCallback(mockTriggerData); |
| 907 | |
| 908 | expect(mockCallback).not.toHaveBeenCalled(); |
| 909 | expect(logger.debug).toHaveBeenCalledWith( |
| 910 | 'Trigger does not match triggerId filter', |
| 911 | expect.any(String) |
| 912 | ); |
| 913 | }); |
| 914 | |
| 915 | it('should log debug message when connectedAccountId filter does not match', async () => { |
| 916 | const filters: TriggerSubscribeParams = { connectedAccountId: 'conn-456' }; |
| 917 | await triggers.subscribe(mockCallback, filters); |
| 918 | |
| 919 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 920 | const filterCallback = subscribeCall[0]; |
| 921 | |
| 922 | filterCallback(mockTriggerData); |
| 923 | |
| 924 | expect(mockCallback).not.toHaveBeenCalled(); |
| 925 | expect(logger.debug).toHaveBeenCalledWith( |
| 926 | 'Trigger does not match connectedAccountId filter', |
| 927 | expect.any(String) |
| 928 | ); |
| 929 | }); |
| 930 | |
| 931 | it('should log debug message when triggerSlug filter does not match', async () => { |
| 932 | const filters: TriggerSubscribeParams = { triggerSlug: ['slack_message'] }; |
| 933 | await triggers.subscribe(mockCallback, filters); |
| 934 | |
| 935 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 936 | const filterCallback = subscribeCall[0]; |
| 937 | |
| 938 | filterCallback(mockTriggerData); |
| 939 | |
| 940 | expect(mockCallback).not.toHaveBeenCalled(); |
| 941 | expect(logger.debug).toHaveBeenCalledWith( |
| 942 | 'Trigger does not match triggerSlug filter', |
| 943 | expect.any(String) |
| 944 | ); |
| 945 | }); |
| 946 | |
| 947 | it('should log debug message when triggerData filter does not match', async () => { |
| 948 | const filters: TriggerSubscribeParams = { triggerData: '{"action":"comment"}' }; |
| 949 | await triggers.subscribe(mockCallback, filters); |
| 950 | |
| 951 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 952 | const filterCallback = subscribeCall[0]; |
| 953 | |
| 954 | filterCallback(mockTriggerData); |
| 955 | |
| 956 | expect(mockCallback).not.toHaveBeenCalled(); |
| 957 | expect(logger.debug).toHaveBeenCalledWith( |
| 958 | 'Trigger does not match triggerData filter', |
| 959 | expect.any(String) |
| 960 | ); |
| 961 | }); |
| 962 | |
| 963 | it('should log debug message when userId filter does not match', async () => { |
| 964 | const filters: TriggerSubscribeParams = { userId: 'user-789' }; |
| 965 | await triggers.subscribe(mockCallback, filters); |
| 966 | |
| 967 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 968 | const filterCallback = subscribeCall[0]; |
| 969 | |
| 970 | filterCallback(mockTriggerData); |
| 971 | |
| 972 | expect(mockCallback).not.toHaveBeenCalled(); |
| 973 | expect(logger.debug).toHaveBeenCalledWith( |
| 974 | 'Trigger does not match userId filter', |
| 975 | expect.any(String) |
| 976 | ); |
| 977 | }); |
| 978 | |
| 979 | it('should log debug message when trigger does not match any filters', async () => { |
| 980 | const filters: TriggerSubscribeParams = { |
| 981 | toolkits: ['slack'], |
| 982 | triggerId: 'trigger-456', |
| 983 | triggerSlug: ['slack_message'], |
| 984 | }; |
| 985 | await triggers.subscribe(mockCallback, filters); |
| 986 | |
| 987 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 988 | const filterCallback = subscribeCall[0]; |
| 989 | |
| 990 | filterCallback(mockTriggerData); |
| 991 | |
| 992 | expect(mockCallback).not.toHaveBeenCalled(); |
| 993 | expect(logger.debug).toHaveBeenCalledWith( |
| 994 | 'Trigger does not match filters', |
| 995 | expect.any(String) |
| 996 | ); |
| 997 | }); |
| 998 | |
| 999 | it('should handle partial trigger data with missing optional fields', async () => { |
| 1000 | const partialTriggerData = { |
| 1001 | appName: 'github', |
| 1002 | clientId: 123, |
| 1003 | payload: { action: 'push' }, |
| 1004 | metadata: { |
| 1005 | id: 'trigger-123', |
| 1006 | nanoId: 'trigger-123-nano', |
| 1007 | triggerName: 'github_webhook', |
| 1008 | triggerConfig: {}, |
| 1009 | connection: { |
| 1010 | id: 'conn-123', |
| 1011 | connectedAccountNanoId: 'conn-123', |
| 1012 | integrationId: 'github', |
| 1013 | authConfigNanoId: 'auth-123', |
| 1014 | clientUniqueUserId: 'user-456', |
| 1015 | status: 'ACTIVE', |
| 1016 | }, |
| 1017 | }, |
| 1018 | }; |
| 1019 | |
| 1020 | await triggers.subscribe(mockCallback); |
| 1021 | |
| 1022 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 1023 | const filterCallback = subscribeCall[0]; |
| 1024 | |
| 1025 | // Should not throw for missing optional fields |
| 1026 | expect(() => filterCallback(partialTriggerData)).not.toThrow(); |
| 1027 | expect(mockCallback).toHaveBeenCalledTimes(1); |
| 1028 | expect(mockCallback).toHaveBeenCalledWith( |
| 1029 | expect.objectContaining({ |
| 1030 | id: 'trigger-123-nano', |
| 1031 | uuid: 'trigger-123', |
| 1032 | metadata: expect.objectContaining({ |
| 1033 | id: 'trigger-123-nano', |
| 1034 | uuid: 'trigger-123', |
| 1035 | connectedAccount: expect.objectContaining({ |
| 1036 | id: 'conn-123', |
| 1037 | uuid: 'conn-123', |
| 1038 | authConfigId: 'auth-123', |
| 1039 | authConfigUUID: 'github', |
| 1040 | userId: 'user-456', |
| 1041 | status: 'ACTIVE', |
| 1042 | }), |
| 1043 | }), |
| 1044 | }) |
| 1045 | ); |
| 1046 | }); |
| 1047 | |
| 1048 | it('should handle multiple callbacks with different filters', async () => { |
| 1049 | const callback1 = vi.fn(); |
| 1050 | const callback2 = vi.fn(); |
| 1051 | |
| 1052 | // Subscribe with different filters |
| 1053 | await triggers.subscribe(callback1, { toolkits: ['github'] }); |
| 1054 | await triggers.subscribe(callback2, { toolkits: ['slack'] }); |
| 1055 | |
| 1056 | const subscribeCall1 = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 1057 | const subscribeCall2 = vi.mocked(mockPusherService.subscribe).mock.calls[1]; |
| 1058 | |
| 1059 | // Trigger github event |
| 1060 | subscribeCall1[0](mockTriggerData); |
| 1061 | // Trigger should only call callback1 |
| 1062 | expect(callback1).toHaveBeenCalledTimes(1); |
| 1063 | expect(callback2).not.toHaveBeenCalled(); |
| 1064 | |
| 1065 | // Reset mocks |
| 1066 | callback1.mockClear(); |
| 1067 | callback2.mockClear(); |
| 1068 | |
| 1069 | // Trigger slack event |
| 1070 | const slackTriggerData = { |
| 1071 | ...mockTriggerData, |
| 1072 | appName: 'slack', |
| 1073 | metadata: { |
| 1074 | ...mockTriggerData.metadata, |
| 1075 | triggerName: 'slack_message', |
| 1076 | }, |
| 1077 | }; |
| 1078 | |
| 1079 | subscribeCall2[0](slackTriggerData); |
| 1080 | // Trigger should only call callback2 |
| 1081 | expect(callback1).not.toHaveBeenCalled(); |
| 1082 | expect(callback2).toHaveBeenCalledTimes(1); |
| 1083 | }); |
| 1084 | |
| 1085 | it('should pass the parsed trigger data to callback when filters match', async () => { |
| 1086 | await triggers.subscribe(mockCallback); |
| 1087 | |
| 1088 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 1089 | const filterCallback = subscribeCall[0]; |
| 1090 | |
| 1091 | filterCallback(mockTriggerData); |
| 1092 | |
| 1093 | expect(mockCallback).toHaveBeenCalledTimes(1); |
| 1094 | expect(mockCallback).toHaveBeenCalledWith( |
| 1095 | expect.objectContaining({ |
| 1096 | id: 'trigger-123-nano', |
| 1097 | uuid: 'trigger-123', |
| 1098 | metadata: expect.objectContaining({ |
| 1099 | id: 'trigger-123-nano', |
| 1100 | uuid: 'trigger-123', |
| 1101 | connectedAccount: expect.objectContaining({ |
| 1102 | id: 'conn-123', |
| 1103 | uuid: 'conn-123', |
| 1104 | authConfigId: 'auth-123', |
| 1105 | authConfigUUID: 'github', |
| 1106 | userId: 'user-456', |
| 1107 | status: 'ACTIVE', |
| 1108 | }), |
| 1109 | }), |
| 1110 | }) |
| 1111 | ); |
| 1112 | }); |
| 1113 | }); |
| 1114 | |
| 1115 | describe('unsubscribe', () => { |
| 1116 | it('should unsubscribe from triggers', async () => { |
| 1117 | await triggers.unsubscribe(); |
| 1118 | expect(mockPusherService.unsubscribe).toHaveBeenCalled(); |
| 1119 | }); |
| 1120 | }); |
| 1121 | |
| 1122 | describe('error handling', () => { |
| 1123 | it('should handle API errors gracefully', async () => { |
| 1124 | const apiError = new Error('API request failed'); |
| 1125 | mockClient.triggerInstances.listActive.mockRejectedValue(apiError); |
| 1126 | |
| 1127 | await expect(triggers.listActive()).rejects.toThrow('API request failed'); |
| 1128 | }); |
| 1129 | |
| 1130 | it('should handle pusher service errors gracefully', async () => { |
| 1131 | const pusherError = new ComposioFailedToSubscribeToPusherChannelError( |
| 1132 | 'Failed to subscribe to Pusher channel' |
| 1133 | ); |
| 1134 | mockPusherService.subscribe.mockRejectedValue(pusherError); |
| 1135 | |
| 1136 | await expect(triggers.subscribe(vi.fn())).rejects.toThrow( |
| 1137 | ComposioFailedToSubscribeToPusherChannelError |
| 1138 | ); |
| 1139 | }); |
| 1140 | }); |
| 1141 | |
| 1142 | describe('subscribe callback handling', () => { |
| 1143 | const mockCallback = vi.fn(); |
| 1144 | |
| 1145 | beforeEach(() => { |
| 1146 | mockCallback.mockClear(); |
| 1147 | vi.mocked(logger.debug).mockClear(); |
| 1148 | }); |
| 1149 | |
| 1150 | it('should not call callback when trigger data does not match filters', async () => { |
| 1151 | const filters: TriggerSubscribeParams = { |
| 1152 | toolkits: ['slack'], // Different toolkit than the mock data |
| 1153 | }; |
| 1154 | |
| 1155 | await triggers.subscribe(mockCallback, filters); |
| 1156 | |
| 1157 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 1158 | const filterCallback = subscribeCall[0]; |
| 1159 | |
| 1160 | filterCallback(mockTriggerData); |
| 1161 | |
| 1162 | expect(mockCallback).not.toHaveBeenCalled(); |
| 1163 | }); |
| 1164 | |
| 1165 | it('should handle errors in user callback without breaking the subscription', async () => { |
| 1166 | const errorCallback = vi.fn().mockImplementation(() => { |
| 1167 | throw new Error('Error in user callback'); |
| 1168 | }); |
| 1169 | |
| 1170 | await triggers.subscribe(errorCallback); |
| 1171 | |
| 1172 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 1173 | const filterCallback = subscribeCall[0]; |
| 1174 | |
| 1175 | // This should not throw even though the callback throws |
| 1176 | expect(() => filterCallback(mockTriggerData)).not.toThrow(); |
| 1177 | |
| 1178 | expect(errorCallback).toHaveBeenCalledTimes(1); |
| 1179 | expect(logger.error).toHaveBeenCalledWith( |
| 1180 | '❌ Error in trigger callback:', |
| 1181 | 'Error in user callback' |
| 1182 | ); |
| 1183 | }); |
| 1184 | |
| 1185 | it('should contain rejections from async user callbacks', async () => { |
| 1186 | const unhandledRejection = vi.fn(); |
| 1187 | process.on('unhandledRejection', unhandledRejection); |
| 1188 | try { |
| 1189 | // A plain async function: a vi.fn() spy would attach its own handlers |
| 1190 | // to the returned promise and hide an unhandled rejection. |
| 1191 | let calls = 0; |
| 1192 | const asyncErrorCallback = async () => { |
| 1193 | calls++; |
| 1194 | throw new Error('Async error in user callback'); |
| 1195 | }; |
| 1196 | |
| 1197 | await triggers.subscribe(asyncErrorCallback); |
| 1198 | |
| 1199 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 1200 | const filterCallback = subscribeCall[0]; |
| 1201 | |
| 1202 | expect(() => filterCallback(mockTriggerData)).not.toThrow(); |
| 1203 | |
| 1204 | // let the rejected promise settle and the containment log run |
| 1205 | await new Promise<void>(resolve => { |
| 1206 | setImmediate(resolve); |
| 1207 | }); |
| 1208 | |
| 1209 | expect(calls).toBe(1); |
| 1210 | expect(logger.error).toHaveBeenCalledWith( |
| 1211 | '❌ Error in trigger callback:', |
| 1212 | 'Async error in user callback' |
| 1213 | ); |
| 1214 | expect(unhandledRejection).not.toHaveBeenCalled(); |
| 1215 | } finally { |
| 1216 | process.off('unhandledRejection', unhandledRejection); |
| 1217 | } |
| 1218 | }); |
| 1219 | |
| 1220 | it('should log the details of a thrown non-Error value', async () => { |
| 1221 | vi.mocked(logger.error).mockClear(); |
| 1222 | const failure = { message: 'Request failed', code: 429 }; |
| 1223 | |
| 1224 | await triggers.subscribe(() => { |
| 1225 | throw failure; |
| 1226 | }); |
| 1227 | await triggers.subscribe(async () => { |
| 1228 | throw failure; |
| 1229 | }); |
| 1230 | |
| 1231 | for (const [filterCallback] of vi.mocked(mockPusherService.subscribe).mock.calls) { |
| 1232 | filterCallback(mockTriggerData); |
| 1233 | } |
| 1234 | await new Promise<void>(resolve => { |
| 1235 | setImmediate(resolve); |
| 1236 | }); |
| 1237 | |
| 1238 | // Once for the synchronous throw, once for the rejection. |
| 1239 | expect( |
| 1240 | vi |
| 1241 | .mocked(logger.error) |
| 1242 | .mock.calls.filter(([prefix]) => prefix === '❌ Error in trigger callback:') |
| 1243 | ).toEqual([ |
| 1244 | ['❌ Error in trigger callback:', '{"message":"Request failed","code":429}'], |
| 1245 | ['❌ Error in trigger callback:', '{"message":"Request failed","code":429}'], |
| 1246 | ]); |
| 1247 | }); |
| 1248 | |
| 1249 | it('should log rejection values that JSON.stringify or String() cannot handle without letting them escape', async () => { |
| 1250 | // The failure log runs as a rejection handler, so it must not throw for |
| 1251 | // any value, or the rejection escapes again. The logger is mocked here, |
| 1252 | // so these pin the string that is logged: passing a circular value to |
| 1253 | // the real logger would make its own JSON.stringify throw. |
| 1254 | vi.mocked(logger.error).mockClear(); |
| 1255 | const unhandledRejection = vi.fn(); |
| 1256 | process.on('unhandledRejection', unhandledRejection); |
| 1257 | try { |
| 1258 | const circular: Record<string, unknown> = { code: 429 }; |
| 1259 | circular.self = circular; |
| 1260 | // String() throws on an object without a prototype. |
| 1261 | const nullPrototype = Object.assign(Object.create(null), { code: 429 }); |
| 1262 | const nullPrototypeCircular = Object.create(null); |
| 1263 | nullPrototypeCircular.self = nullPrototypeCircular; |
| 1264 | |
| 1265 | for (const value of [circular, nullPrototype, nullPrototypeCircular]) { |
| 1266 | await triggers.subscribe(async () => { |
| 1267 | throw value; |
| 1268 | }); |
| 1269 | } |
| 1270 | for (const [filterCallback] of vi.mocked(mockPusherService.subscribe).mock.calls) { |
| 1271 | filterCallback(mockTriggerData); |
| 1272 | } |
| 1273 | await new Promise<void>(resolve => { |
| 1274 | setImmediate(resolve); |
| 1275 | }); |
| 1276 | |
| 1277 | expect( |
| 1278 | vi |
| 1279 | .mocked(logger.error) |
| 1280 | .mock.calls.filter(([prefix]) => prefix === '❌ Error in trigger callback:') |
| 1281 | ).toEqual([ |
| 1282 | ['❌ Error in trigger callback:', '[object Object]'], |
| 1283 | ['❌ Error in trigger callback:', '{"code":429}'], |
| 1284 | ['❌ Error in trigger callback:', '[unprintable value]'], |
| 1285 | ]); |
| 1286 | expect(unhandledRejection).not.toHaveBeenCalled(); |
| 1287 | } finally { |
| 1288 | process.off('unhandledRejection', unhandledRejection); |
| 1289 | } |
| 1290 | }); |
| 1291 | }); |
| 1292 | |
| 1293 | describe('parsePusherPayload (V1/V2/V3 format support)', () => { |
| 1294 | const mockCallback = vi.fn(); |
| 1295 | |
| 1296 | // V1 mock payload matching WebhookPayloadV1Schema |
| 1297 | const mockV1Payload = { |
| 1298 | trigger_name: 'GMAIL_NEW_GMAIL_MESSAGE', |
| 1299 | connection_id: 'conn-123', |
| 1300 | trigger_id: 'trigger-456', |
| 1301 | payload: { subject: 'Test email', from: 'test@example.com' }, |
| 1302 | log_id: 'log-789', |
| 1303 | }; |
| 1304 | |
| 1305 | // V2 mock payload matching WebhookPayloadV2Schema |
| 1306 | const mockV2Payload = { |
| 1307 | type: 'GMAIL_NEW_GMAIL_MESSAGE', |
| 1308 | timestamp: '2026-01-28T12:00:00Z', |
| 1309 | log_id: 'log-789', |
| 1310 | data: { |
| 1311 | connection_id: 'conn-uuid', |
| 1312 | connection_nano_id: 'conn-123', |
| 1313 | trigger_nano_id: 'trigger-456', |
| 1314 | trigger_id: 'trigger-uuid', |
| 1315 | user_id: 'user-789', |
| 1316 | subject: 'Test email', |
| 1317 | from: 'test@example.com', |
| 1318 | }, |
| 1319 | }; |
| 1320 | |
| 1321 | // V3 mock payload matching WebhookPayloadV3Schema |
| 1322 | const mockV3Payload = { |
| 1323 | id: 'msg-123', |
| 1324 | timestamp: '2026-01-28T12:00:00Z', |
| 1325 | type: 'composio.trigger.message', |
| 1326 | metadata: { |
| 1327 | log_id: 'log-789', |
| 1328 | trigger_slug: 'GMAIL_NEW_GMAIL_MESSAGE', |
| 1329 | trigger_id: 'trigger-456', |
| 1330 | connected_account_id: 'conn-123', |
| 1331 | auth_config_id: 'auth-456', |
| 1332 | user_id: 'user-789', |
| 1333 | }, |
| 1334 | data: { subject: 'Test email', from: 'test@example.com' }, |
| 1335 | }; |
| 1336 | |
| 1337 | beforeEach(() => { |
| 1338 | mockCallback.mockClear(); |
| 1339 | vi.mocked(logger.debug).mockClear(); |
| 1340 | vi.mocked(logger.warn).mockClear(); |
| 1341 | }); |
| 1342 | |
| 1343 | it('should parse V3 Pusher payload', async () => { |
| 1344 | await triggers.subscribe(mockCallback); |
| 1345 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 1346 | const filterCallback = subscribeCall[0]; |
| 1347 | |
| 1348 | filterCallback(mockV3Payload); |
| 1349 | |
| 1350 | expect(mockCallback).toHaveBeenCalledTimes(1); |
| 1351 | expect(mockCallback).toHaveBeenCalledWith( |
| 1352 | expect.objectContaining({ |
| 1353 | id: 'trigger-456', |
| 1354 | triggerSlug: 'GMAIL_NEW_GMAIL_MESSAGE', |
| 1355 | userId: 'user-789', |
| 1356 | toolkitSlug: 'GMAIL', |
| 1357 | payload: { subject: 'Test email', from: 'test@example.com' }, |
| 1358 | metadata: expect.objectContaining({ |
| 1359 | id: 'trigger-456', |
| 1360 | triggerSlug: 'GMAIL_NEW_GMAIL_MESSAGE', |
| 1361 | connectedAccount: expect.objectContaining({ |
| 1362 | id: 'conn-123', |
| 1363 | userId: 'user-789', |
| 1364 | authConfigId: 'auth-456', |
| 1365 | }), |
| 1366 | }), |
| 1367 | }) |
| 1368 | ); |
| 1369 | expect(logger.debug).toHaveBeenCalledWith('Parsed Pusher payload as V3 format'); |
| 1370 | }); |
| 1371 | |
| 1372 | it('should not call callback when V3 auth config does not match', async () => { |
| 1373 | await triggers.subscribe(mockCallback, { authConfigId: 'auth-other' }); |
| 1374 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 1375 | const filterCallback = subscribeCall[0]; |
| 1376 | |
| 1377 | filterCallback(mockV3Payload); |
| 1378 | |
| 1379 | expect(mockCallback).not.toHaveBeenCalled(); |
| 1380 | }); |
| 1381 | |
| 1382 | it('should parse V2 Pusher payload', async () => { |
| 1383 | await triggers.subscribe(mockCallback); |
| 1384 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 1385 | const filterCallback = subscribeCall[0]; |
| 1386 | |
| 1387 | filterCallback(mockV2Payload); |
| 1388 | |
| 1389 | expect(mockCallback).toHaveBeenCalledTimes(1); |
| 1390 | expect(mockCallback).toHaveBeenCalledWith( |
| 1391 | expect.objectContaining({ |
| 1392 | id: 'trigger-456', |
| 1393 | uuid: 'trigger-uuid', |
| 1394 | triggerSlug: 'GMAIL_NEW_GMAIL_MESSAGE', |
| 1395 | userId: 'user-789', |
| 1396 | toolkitSlug: 'GMAIL', |
| 1397 | metadata: expect.objectContaining({ |
| 1398 | id: 'trigger-456', |
| 1399 | uuid: 'trigger-uuid', |
| 1400 | connectedAccount: expect.objectContaining({ |
| 1401 | id: 'conn-123', |
| 1402 | uuid: 'conn-uuid', |
| 1403 | userId: 'user-789', |
| 1404 | }), |
| 1405 | }), |
| 1406 | }) |
| 1407 | ); |
| 1408 | expect(logger.debug).toHaveBeenCalledWith('Parsed Pusher payload as V2 format'); |
| 1409 | }); |
| 1410 | |
| 1411 | it('should parse V1 Pusher payload', async () => { |
| 1412 | await triggers.subscribe(mockCallback); |
| 1413 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 1414 | const filterCallback = subscribeCall[0]; |
| 1415 | |
| 1416 | filterCallback(mockV1Payload); |
| 1417 | |
| 1418 | expect(mockCallback).toHaveBeenCalledTimes(1); |
| 1419 | expect(mockCallback).toHaveBeenCalledWith( |
| 1420 | expect.objectContaining({ |
| 1421 | id: 'trigger-456', |
| 1422 | triggerSlug: 'GMAIL_NEW_GMAIL_MESSAGE', |
| 1423 | toolkitSlug: 'GMAIL', |
| 1424 | payload: { subject: 'Test email', from: 'test@example.com' }, |
| 1425 | metadata: expect.objectContaining({ |
| 1426 | id: 'trigger-456', |
| 1427 | triggerSlug: 'GMAIL_NEW_GMAIL_MESSAGE', |
| 1428 | connectedAccount: expect.objectContaining({ |
| 1429 | id: 'conn-123', |
| 1430 | }), |
| 1431 | }), |
| 1432 | }) |
| 1433 | ); |
| 1434 | expect(logger.debug).toHaveBeenCalledWith('Parsed Pusher payload as V1 format'); |
| 1435 | }); |
| 1436 | |
| 1437 | it('should parse legacy TriggerData payload for backwards compatibility', async () => { |
| 1438 | await triggers.subscribe(mockCallback); |
| 1439 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 1440 | const filterCallback = subscribeCall[0]; |
| 1441 | |
| 1442 | filterCallback(mockTriggerData); |
| 1443 | |
| 1444 | expect(mockCallback).toHaveBeenCalledTimes(1); |
| 1445 | expect(mockCallback).toHaveBeenCalledWith(mockIncomingTriggerPayload); |
| 1446 | expect(logger.debug).toHaveBeenCalledWith( |
| 1447 | 'Parsed Pusher payload as legacy TriggerData format' |
| 1448 | ); |
| 1449 | }); |
| 1450 | |
| 1451 | it('should log warning for unknown payload format and attempt legacy transformation', async () => { |
| 1452 | const unknownPayload = { |
| 1453 | someField: 'value', |
| 1454 | anotherField: 123, |
| 1455 | }; |
| 1456 | |
| 1457 | await triggers.subscribe(mockCallback); |
| 1458 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 1459 | const filterCallback = subscribeCall[0]; |
| 1460 | |
| 1461 | // This should not throw, but should log a warning |
| 1462 | expect(() => filterCallback(unknownPayload)).not.toThrow(); |
| 1463 | expect(logger.warn).toHaveBeenCalledWith( |
| 1464 | expect.stringContaining('Unknown Pusher payload format') |
| 1465 | ); |
| 1466 | }); |
| 1467 | |
| 1468 | it('should handle non-string values in fallback payload without crashing', async () => { |
| 1469 | const malformedPayload = { |
| 1470 | toolkitSlug: 123, // number instead of string |
| 1471 | triggerSlug: { foo: 1 }, // object instead of string |
| 1472 | id: null, |
| 1473 | userId: undefined, |
| 1474 | trigger_name: 456, // number instead of string for fallback field |
| 1475 | }; |
| 1476 | |
| 1477 | await triggers.subscribe(mockCallback); |
| 1478 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 1479 | const filterCallback = subscribeCall[0]; |
| 1480 | |
| 1481 | // Should not throw, even with non-string values |
| 1482 | expect(() => filterCallback(malformedPayload)).not.toThrow(); |
| 1483 | expect(mockCallback).toHaveBeenCalledTimes(1); |
| 1484 | |
| 1485 | // The callback should receive a payload with string values that are safe to use with string methods |
| 1486 | const receivedPayload = mockCallback.mock.calls[0][0]; |
| 1487 | expect(typeof receivedPayload.toolkitSlug).toBe('string'); |
| 1488 | expect(typeof receivedPayload.triggerSlug).toBe('string'); |
| 1489 | expect(typeof receivedPayload.id).toBe('string'); |
| 1490 | expect(typeof receivedPayload.userId).toBe('string'); |
| 1491 | |
| 1492 | // Verify that calling toLowerCase() doesn't crash (this is what shouldSendTriggerAfterFilters does) |
| 1493 | expect(() => receivedPayload.toolkitSlug.toLowerCase()).not.toThrow(); |
| 1494 | expect(() => receivedPayload.triggerSlug.toLowerCase()).not.toThrow(); |
| 1495 | }); |
| 1496 | |
| 1497 | it('should safely convert various non-string types in fallback payload', async () => { |
| 1498 | const payloadWithVariousTypes = { |
| 1499 | id: 12345, // number |
| 1500 | uuid: true, // boolean |
| 1501 | toolkitSlug: ['array'], // array |
| 1502 | triggerSlug: { nested: 'object' }, // object |
| 1503 | userId: Symbol('symbol'), // symbol - will convert to 'Symbol(symbol)' |
| 1504 | appName: null, // null |
| 1505 | trigger_name: undefined, // undefined |
| 1506 | }; |
| 1507 | |
| 1508 | await triggers.subscribe(mockCallback); |
| 1509 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 1510 | const filterCallback = subscribeCall[0]; |
| 1511 | |
| 1512 | // Should not throw |
| 1513 | expect(() => filterCallback(payloadWithVariousTypes)).not.toThrow(); |
| 1514 | expect(mockCallback).toHaveBeenCalledTimes(1); |
| 1515 | |
| 1516 | const receivedPayload = mockCallback.mock.calls[0][0]; |
| 1517 | |
| 1518 | // All values should be strings |
| 1519 | expect(typeof receivedPayload.id).toBe('string'); |
| 1520 | expect(typeof receivedPayload.uuid).toBe('string'); |
| 1521 | expect(typeof receivedPayload.toolkitSlug).toBe('string'); |
| 1522 | expect(typeof receivedPayload.triggerSlug).toBe('string'); |
| 1523 | expect(typeof receivedPayload.userId).toBe('string'); |
| 1524 | |
| 1525 | // Numeric ID should be converted to string |
| 1526 | expect(receivedPayload.id).toBe('12345'); |
| 1527 | }); |
| 1528 | |
| 1529 | it('should filter V3 payloads correctly by triggerId', async () => { |
| 1530 | const filters = { triggerId: 'trigger-456' }; |
| 1531 | await triggers.subscribe(mockCallback, filters); |
| 1532 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 1533 | const filterCallback = subscribeCall[0]; |
| 1534 | |
| 1535 | filterCallback(mockV3Payload); |
| 1536 | |
| 1537 | expect(mockCallback).toHaveBeenCalledTimes(1); |
| 1538 | }); |
| 1539 | |
| 1540 | it('should filter V3 payloads correctly and reject non-matching triggerId', async () => { |
| 1541 | const filters = { triggerId: 'wrong-trigger-id' }; |
| 1542 | await triggers.subscribe(mockCallback, filters); |
| 1543 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 1544 | const filterCallback = subscribeCall[0]; |
| 1545 | |
| 1546 | filterCallback(mockV3Payload); |
| 1547 | |
| 1548 | expect(mockCallback).not.toHaveBeenCalled(); |
| 1549 | }); |
| 1550 | |
| 1551 | it('should filter V2 payloads by toolkit', async () => { |
| 1552 | const filters = { toolkits: ['GMAIL'] }; |
| 1553 | await triggers.subscribe(mockCallback, filters); |
| 1554 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 1555 | const filterCallback = subscribeCall[0]; |
| 1556 | |
| 1557 | filterCallback(mockV2Payload); |
| 1558 | |
| 1559 | expect(mockCallback).toHaveBeenCalledTimes(1); |
| 1560 | }); |
| 1561 | |
| 1562 | it('should filter V1 payloads by triggerSlug', async () => { |
| 1563 | const filters = { triggerSlug: ['GMAIL_NEW_GMAIL_MESSAGE'] }; |
| 1564 | await triggers.subscribe(mockCallback, filters); |
| 1565 | const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0]; |
| 1566 | const filterCallback = subscribeCall[0]; |
| 1567 | |
| 1568 | filterCallback(mockV1Payload); |
| 1569 | |
| 1570 | expect(mockCallback).toHaveBeenCalledTimes(1); |
| 1571 | }); |
| 1572 | |
| 1573 | // Toolkit slugs such as `one_drive`, `launch_darkly` and `agent_mail` contain an |
| 1574 | // underscore, so the toolkit derived from the trigger slug's first segment is |
| 1575 | // `ONE`, not `ONE_DRIVE`. |
| 1576 | const oneDriveV3Payload = { |
| 1577 | ...mockV3Payload, |
| 1578 | metadata: { ...mockV3Payload.metadata, trigger_slug: 'ONE_DRIVE_FILE_CREATED_TRIGGER' }, |
| 1579 | }; |
| 1580 | |
| 1581 | it('should match a toolkit filter whose slug contains an underscore', async () => { |
| 1582 | await triggers.subscribe(mockCallback, { toolkits: ['one_drive'] }); |
| 1583 | const filterCallback = vi.mocked(mockPusherService.subscribe).mock.calls[0][0]; |
| 1584 | |
| 1585 | filterCallback(oneDriveV3Payload); |
| 1586 | |
| 1587 | expect(mockCallback).toHaveBeenCalledTimes(1); |
| 1588 | }); |
| 1589 | |
| 1590 | it('should match an underscore toolkit filter case-insensitively', async () => { |
| 1591 | await triggers.subscribe(mockCallback, { toolkits: ['ONE_DRIVE'] }); |
| 1592 | const filterCallback = vi.mocked(mockPusherService.subscribe).mock.calls[0][0]; |
| 1593 | |
| 1594 | filterCallback(oneDriveV3Payload); |
| 1595 | |
| 1596 | expect(mockCallback).toHaveBeenCalledTimes(1); |
| 1597 | }); |
| 1598 | |
| 1599 | it('should not match a toolkit filter that only shares a prefix with the trigger slug', async () => { |
| 1600 | await triggers.subscribe(mockCallback, { toolkits: ['one_drive'] }); |
| 1601 | const filterCallback = vi.mocked(mockPusherService.subscribe).mock.calls[0][0]; |
| 1602 | |
| 1603 | filterCallback({ |
| 1604 | ...mockV3Payload, |
| 1605 | metadata: { ...mockV3Payload.metadata, trigger_slug: 'ONE_DRIVEX_FILE_CREATED' }, |
| 1606 | }); |
| 1607 | |
| 1608 | expect(mockCallback).not.toHaveBeenCalled(); |
| 1609 | }); |
| 1610 | }); |
| 1611 | }); |