1
+/**
2
+ * @fileoverview The `composio.webhooks` namespace: project webhook
3
+ * subscriptions (outbound event delivery) and webhook endpoints (inbound
4
+ * per-toolkit ingress URLs).
5
+ *
6
+ * @module Webhooks
7
+ */
8
+import ComposioClient from '@composio/client';
9
+import { z } from 'zod/v3';
10
+import {
11
+ DefaultWebhookSubscriptionEvents,
12
+ WebhookSubscription,
13
+ WebhookVersions,
14
+} from '../types/triggers.types';
15
+import {
16
+ WebhookEndpoint,
17
+ WebhookEndpointCreateParams,
18
+ WebhookEndpointCreateParamsSchema,
19
+ WebhookEndpointListParams,
20
+ WebhookEndpointListParamsSchema,
21
+ WebhookEndpointListResponse,
22
+ WebhookEndpointReplaceParams,
23
+ WebhookEndpointReplaceParamsSchema,
24
+ WebhookEndpointUpdateParams,
25
+ WebhookEndpointUpdateParamsSchema,
26
+ WebhookSubscriptionEventTypesResponse,
27
+ WebhookSubscriptionDeleteResponse,
28
+ WebhookSubscriptionListParams,
29
+ WebhookSubscriptionListParamsSchema,
30
+ WebhookSubscriptionListResponse,
31
+ WebhookSubscriptionRotateSecretResponse,
32
+ WebhookSubscriptionSetParams,
33
+ WebhookSubscriptionSetParamsSchema,
34
+ WebhookSubscriptionUpdateParams,
35
+ WebhookSubscriptionUpdateParamsSchema,
36
+} from '../types/webhooks.types';
37
+import { ComposioRequestOptions } from '../types/requestOptions.types';
38
+import { ValidationError } from '../errors/ValidationErrors';
39
+import { telemetry } from '../telemetry/Telemetry';
40
+import { withCancellation } from '../utils/cancellation';
41
+import {
42
+ transformWebhookEndpoint,
43
+ transformWebhookEndpointListResponse,
44
+ transformWebhookSubscriptionEventTypesResponse,
45
+ transformWebhookSubscription,
46
+ transformWebhookSubscriptionDeleteResponse,
47
+ transformWebhookSubscriptionListResponse,
48
+ transformWebhookSubscriptionRotateSecretResponse,
49
+} from '../utils/transformers/webhooks';
50
+
51
+/**
52
+ * The only part of the `list({ limit: 1 })` probe the upsert needs: the id of
53
+ * the first (and, since the API allows one subscription per project, only)
54
+ * subscription. Parsed at the boundary so a malformed payload never reaches
55
+ * the update path.
56
+ */
57
+const FirstWebhookSubscriptionIdSchema = z
58
+ .object({
59
+ items: z.array(z.object({ id: z.string().min(1) }).passthrough()),
60
+ })
61
+ .passthrough()
62
+ .transform(response => response.items[0]?.id);
63
+
64
+/**
65
+ * Create-or-update the project webhook subscription.
66
+ *
67
+ * Shared by `composio.webhooks.subscriptions.set()` and the legacy
68
+ * `composio.triggers.setWebhookSubscription()` so both issue the exact same
69
+ * call sequence: `webhookSubscriptions.list({ limit: 1 })`, then
70
+ * `webhookSubscriptions.update(id, body)` when a subscription exists,
71
+ * otherwise `webhookSubscriptions.create(body)`.
72
+ *
73
+ * @internal
74
+ */
75
+export async function upsertWebhookSubscription(
76
+ client: ComposioClient,
77
+ params: WebhookSubscriptionSetParams,
78
+ requestOptions?: ComposioRequestOptions
79
+): Promise<WebhookSubscription> {
80
+ const parsedParams = WebhookSubscriptionSetParamsSchema.safeParse(params);
81
+
82
+ if (!parsedParams.success) {
83
+ throw new ValidationError(`Invalid parameters passed to set webhook subscription`, {
84
+ cause: parsedParams.error,
85
+ });
86
+ }
87
+
88
+ const body = {
89
+ webhook_url: parsedParams.data.webhookUrl,
90
+ enabled_events: parsedParams.data.enabledEvents ?? [...DefaultWebhookSubscriptionEvents],
91
+ version: parsedParams.data.version ?? WebhookVersions.V3,
92
+ };
93
+
94
+ const existing = await withCancellation(
95
+ () => client.webhookSubscriptions.list({ limit: 1 }, requestOptions),
96
+ requestOptions?.signal
97
+ );
98
+ const parsedExisting = FirstWebhookSubscriptionIdSchema.safeParse(existing);
99
+ if (!parsedExisting.success) {
100
+ throw new ValidationError('Failed to parse webhook subscription list response', {
101
+ cause: parsedExisting.error,
102
+ });
103
+ }
104
+ const subscriptionId = parsedExisting.data;
105
+
106
+ const subscription = await withCancellation(
107
+ () =>
108
+ subscriptionId
109
+ ? client.webhookSubscriptions.update(subscriptionId, body, requestOptions)
110
+ : client.webhookSubscriptions.create(body, requestOptions),
111
+ requestOptions?.signal
112
+ );
113
+
114
+ return transformWebhookSubscription(subscription);
115
+}
116
+
117
+/**
118
+ * `composio.webhooks.subscriptions` — the project's outbound webhook
119
+ * subscription. The API allows one subscription per project; every response
120
+ * includes the signing `secret` used to verify deliveries with
121
+ * `composio.triggers.verifyWebhook()` / `composio.triggers.parse()`.
122
+ */
123
+export class WebhookSubscriptions {
124
+ private client: ComposioClient;
125
+
126
+ constructor(client: ComposioClient) {
127
+ this.client = client;
128
+ telemetry.instrument(this, 'WebhookSubscriptions');
129
+ }
130
+
131
+ /**
132
+ * List the project's webhook subscriptions.
133
+ *
134
+ * @param {WebhookSubscriptionListParams} [query] - Pagination options
135
+ * @returns {Promise<WebhookSubscriptionListResponse>} Paginated subscriptions
136
+ *
137
+ * @example
138
+ * ```typescript
139
+ * const { items } = await composio.webhooks.subscriptions.list();
140
+ * console.log(items[0]?.webhookUrl);
141
+ * ```
142
+ */
143
+ async list(
144
+ query?: WebhookSubscriptionListParams,
145
+ requestOptions?: ComposioRequestOptions
146
+ ): Promise<WebhookSubscriptionListResponse> {
147
+ const parsedQuery = WebhookSubscriptionListParamsSchema.safeParse(query ?? {});
148
+ if (!parsedQuery.success) {
149
+ throw new ValidationError('Failed to parse webhook subscription list query', {
150
+ cause: parsedQuery.error,
151
+ });
152
+ }
153
+ const listParams = {
154
+ limit: parsedQuery.data.limit,
155
+ cursor: parsedQuery.data.cursor,
156
+ };
157
+ const result = await withCancellation(
158
+ () => this.client.webhookSubscriptions.list(listParams, requestOptions),
159
+ requestOptions?.signal
160
+ );
161
+ return transformWebhookSubscriptionListResponse(result);
162
+ }
163
+
164
+ /**
165
+ * Retrieve a webhook subscription by id.
166
+ *
167
+ * @param {string} id - The subscription id
168
+ * @returns {Promise<WebhookSubscription>} The subscription, including its signing secret
169
+ *
170
+ * @example
171
+ * ```typescript
172
+ * const subscription = await composio.webhooks.subscriptions.get('whs_abc123');
173
+ * console.log(subscription.enabledEvents);
174
+ * ```
175
+ */
176
+ async get(id: string, requestOptions?: ComposioRequestOptions): Promise<WebhookSubscription> {
177
+ const result = await withCancellation(
178
+ () => this.client.webhookSubscriptions.retrieve(id, requestOptions),
179
+ requestOptions?.signal
180
+ );
181
+ return transformWebhookSubscription(result);
182
+ }
183
+
184
+ /**
185
+ * Create or update the project webhook subscription.
186
+ *
187
+ * If a subscription already exists it is updated in place, otherwise a new
188
+ * one is created. By default this subscribes to V3 trigger message events.
189
+ *
190
+ * @param {WebhookSubscriptionSetParams} params - `webhookUrl`, optional `enabledEvents` and `version`
191
+ * @returns {Promise<WebhookSubscription>} The resulting subscription
192
+ * @throws {ValidationError} If the params fail validation
193
+ *
194
+ * @example
195
+ * ```typescript
196
+ * const subscription = await composio.webhooks.subscriptions.set({
197
+ * webhookUrl: `${APP_URL}/webhooks/composio`,
198
+ * enabledEvents: ['composio.trigger.message', 'composio.connected_account.expired'],
199
+ * });
200
+ * process.env.COMPOSIO_WEBHOOK_SECRET = subscription.secret;
201
+ * ```
202
+ */
203
+ async set(
204
+ params: WebhookSubscriptionSetParams,
205
+ requestOptions?: ComposioRequestOptions
206
+ ): Promise<WebhookSubscription> {
207
+ return upsertWebhookSubscription(this.client, params, requestOptions);
208
+ }
209
+
210
+ /**
211
+ * Update an existing webhook subscription. Only the provided fields change.
212
+ *
213
+ * @param {string} id - The subscription id
214
+ * @param {WebhookSubscriptionUpdateParams} params - Fields to update
215
+ * @returns {Promise<WebhookSubscription>} The updated subscription
216
+ * @throws {ValidationError} If the params fail validation
217
+ *
218
+ * @example
219
+ * ```typescript
220
+ * await composio.webhooks.subscriptions.update('whs_abc123', {
221
+ * enabledEvents: ['composio.trigger.message'],
222
+ * });
223
+ * ```
224
+ */
225
+ async update(
226
+ id: string,
227
+ params: WebhookSubscriptionUpdateParams,
228
+ requestOptions?: ComposioRequestOptions
229
+ ): Promise<WebhookSubscription> {
230
+ const parsedParams = WebhookSubscriptionUpdateParamsSchema.safeParse(params);
231
+ if (!parsedParams.success) {
232
+ throw new ValidationError('Failed to parse webhook subscription update params', {
233
+ cause: parsedParams.error,
234
+ });
235
+ }
236
+ const body = {
237
+ webhook_url: parsedParams.data.webhookUrl,
238
+ enabled_events: parsedParams.data.enabledEvents,
239
+ version: parsedParams.data.version,
240
+ };
241
+ const result = await withCancellation(
242
+ () => this.client.webhookSubscriptions.update(id, body, requestOptions),
243
+ requestOptions?.signal
244
+ );
245
+ return transformWebhookSubscription(result);
246
+ }
247
+
248
+ /**
249
+ * Delete a webhook subscription. Deliveries stop immediately.
250
+ *
251
+ * @param {string} id - The subscription id
252
+ * @returns {Promise<WebhookSubscriptionDeleteResponse>} `{ success }`
253
+ *
254
+ * @example
255
+ * ```typescript
256
+ * await composio.webhooks.subscriptions.delete('whs_abc123');
257
+ * ```
258
+ */
259
+ async delete(
260
+ id: string,
261
+ requestOptions?: ComposioRequestOptions
262
+ ): Promise<WebhookSubscriptionDeleteResponse> {
263
+ const result = await withCancellation(
264
+ () => this.client.webhookSubscriptions.delete(id, requestOptions),
265
+ requestOptions?.signal
266
+ );
267
+ return transformWebhookSubscriptionDeleteResponse(result);
268
+ }
269
+
270
+ /**
271
+ * Rotate the signing secret of a webhook subscription. The previous secret
272
+ * stops validating, so update your verifier with the returned `secret`.
273
+ *
274
+ * @param {string} id - The subscription id
275
+ * @returns {Promise<WebhookSubscriptionRotateSecretResponse>} `{ id, secret }`
276
+ *
277
+ * @example
278
+ * ```typescript
279
+ * const { secret } = await composio.webhooks.subscriptions.rotateSecret('whs_abc123');
280
+ * ```
281
+ */
282
+ async rotateSecret(
283
+ id: string,
284
+ requestOptions?: ComposioRequestOptions
285
+ ): Promise<WebhookSubscriptionRotateSecretResponse> {
286
+ const result = await withCancellation(
287
+ () => this.client.webhookSubscriptions.rotateSecret(id, requestOptions),
288
+ requestOptions?.signal
289
+ );
290
+ return transformWebhookSubscriptionRotateSecretResponse(result);
291
+ }
292
+
293
+ /**
294
+ * List the event types a subscription can enable, with the payload
295
+ * versions each one supports.
296
+ *
297
+ * @returns {Promise<WebhookSubscriptionEventTypesResponse>} The available event types
298
+ *
299
+ * @example
300
+ * ```typescript
301
+ * const { items } = await composio.webhooks.subscriptions.listEventTypes();
302
+ * console.log(items.map(item => item.eventType));
303
+ * ```
304
+ */
305
+ async listEventTypes(
306
+ requestOptions?: ComposioRequestOptions
307
+ ): Promise<WebhookSubscriptionEventTypesResponse> {
308
+ const result = await withCancellation(
309
+ () => this.client.webhookSubscriptions.listEventTypes(requestOptions),
310
+ requestOptions?.signal
311
+ );
312
+ return transformWebhookSubscriptionEventTypesResponse(result);
313
+ }
314
+}
315
+
316
+/**
317
+ * `composio.webhooks.endpoints` — inbound webhook endpoints. Each endpoint is
318
+ * the ingress URL Composio exposes for one toolkit + OAuth app pair, which you
319
+ * register with the third-party provider so it can push events to Composio.
320
+ */
321
+export class WebhookEndpoints {
322
+ private client: ComposioClient;
323
+
324
+ constructor(client: ComposioClient) {
325
+ this.client = client;
326
+ telemetry.instrument(this, 'WebhookEndpoints');
327
+ }
328
+
329
+ /**
330
+ * List webhook endpoints, optionally filtered by toolkit.
331
+ *
332
+ * @param {WebhookEndpointListParams} [query] - Optional `toolkitSlug` filter
333
+ * @returns {Promise<WebhookEndpointListResponse>} The endpoints
334
+ *
335
+ * @example
336
+ * ```typescript
337
+ * const { items } = await composio.webhooks.endpoints.list({ toolkitSlug: 'slack' });
338
+ * ```
339
+ */
340
+ async list(
341
+ query?: WebhookEndpointListParams,
342
+ requestOptions?: ComposioRequestOptions
343
+ ): Promise<WebhookEndpointListResponse> {
344
+ const parsedQuery = WebhookEndpointListParamsSchema.safeParse(query ?? {});
345
+ if (!parsedQuery.success) {
346
+ throw new ValidationError('Failed to parse webhook endpoint list query', {
347
+ cause: parsedQuery.error,
348
+ });
349
+ }
350
+ const listParams = { toolkit_slug: parsedQuery.data.toolkitSlug };
351
+ const result = await withCancellation(
352
+ () => this.client.webhookEndpoints.list(listParams, requestOptions),
353
+ requestOptions?.signal
354
+ );
355
+ return transformWebhookEndpointListResponse(result);
356
+ }
357
+
358
+ /**
359
+ * Retrieve a webhook endpoint by its nano id.
360
+ *
361
+ * @param {string} nanoId - The endpoint nano id (e.g. `we_abc123`)
362
+ * @returns {Promise<WebhookEndpoint>} The endpoint, with secret setup values masked
363
+ *
364
+ * @example
365
+ * ```typescript
366
+ * const endpoint = await composio.webhooks.endpoints.get('we_abc123');
367
+ * console.log(endpoint.webhookUrl);
368
+ * ```
369
+ */
370
+ async get(nanoId: string, requestOptions?: ComposioRequestOptions): Promise<WebhookEndpoint> {
371
+ const result = await withCancellation(
372
+ () => this.client.webhookEndpoints.retrieve(nanoId, requestOptions),
373
+ requestOptions?.signal
374
+ );
375
+ return transformWebhookEndpoint(result);
376
+ }
377
+
378
+ /**
379
+ * Create a webhook endpoint for a toolkit + OAuth app pair. Returns the
380
+ * existing endpoint when one already exists for that pair.
381
+ *
382
+ * @param {WebhookEndpointCreateParams} params - `toolkitSlug` and `clientId`
383
+ * @returns {Promise<WebhookEndpoint>} The endpoint; register `webhookUrl` with the provider
384
+ * @throws {ValidationError} If the params fail validation
385
+ *
386
+ * @example
387
+ * ```typescript
388
+ * const endpoint = await composio.webhooks.endpoints.create({
389
+ * toolkitSlug: 'slack',
390
+ * clientId: 'my-slack-app-client-id',
391
+ * });
392
+ * ```
393
+ */
394
+ async create(
395
+ params: WebhookEndpointCreateParams,
396
+ requestOptions?: ComposioRequestOptions
397
+ ): Promise<WebhookEndpoint> {
398
+ const parsedParams = WebhookEndpointCreateParamsSchema.safeParse(params);
399
+ if (!parsedParams.success) {
400
+ throw new ValidationError('Failed to parse webhook endpoint create params', {
401
+ cause: parsedParams.error,
402
+ });
403
+ }
404
+ const body = {
405
+ toolkit_slug: parsedParams.data.toolkitSlug,
406
+ client_id: parsedParams.data.clientId,
407
+ };
408
+ const result = await withCancellation(
409
+ () => this.client.webhookEndpoints.create(body, requestOptions),
410
+ requestOptions?.signal
411
+ );
412
+ return transformWebhookEndpoint(result);
413
+ }
414
+
415
+ /**
416
+ * Replace the setup fields of a webhook endpoint. All required setup fields
417
+ * for the toolkit must be provided — this is the initial configuration.
418
+ *
419
+ * @param {string} nanoId - The endpoint nano id
420
+ * @param {WebhookEndpointReplaceParams} params - `data` with every required setup field
421
+ * @returns {Promise<WebhookEndpoint>} The configured endpoint
422
+ * @throws {ValidationError} If the params fail validation
423
+ *
424
+ * @example
425
+ * ```typescript
426
+ * await composio.webhooks.endpoints.replace('we_abc123', {
427
+ * data: { signing_secret: process.env.SLACK_SIGNING_SECRET! },
428
+ * });
429
+ * ```
430
+ */
431
+ async replace(
432
+ nanoId: string,
433
+ params: WebhookEndpointReplaceParams,
434
+ requestOptions?: ComposioRequestOptions
435
+ ): Promise<WebhookEndpoint> {
436
+ const parsedParams = WebhookEndpointReplaceParamsSchema.safeParse(params);
437
+ if (!parsedParams.success) {
438
+ throw new ValidationError('Failed to parse webhook endpoint replace params', {
439
+ cause: parsedParams.error,
440
+ });
441
+ }
442
+ const result = await withCancellation(
443
+ () =>
444
+ this.client.webhookEndpoints.replace(
445
+ nanoId,
446
+ { data: parsedParams.data.data },
447
+ requestOptions
448
+ ),
449
+ requestOptions?.signal
450
+ );
451
+ return transformWebhookEndpoint(result);
452
+ }
453
+
454
+ /**
455
+ * Merge setup fields into a webhook endpoint. Omitted fields are preserved.
456
+ *
457
+ * @param {string} nanoId - The endpoint nano id
458
+ * @param {WebhookEndpointUpdateParams} params - `data` with the fields to change
459
+ * @returns {Promise<WebhookEndpoint>} The updated endpoint
460
+ * @throws {ValidationError} If the params fail validation
461
+ *
462
+ * @example
463
+ * ```typescript
464
+ * await composio.webhooks.endpoints.update('we_abc123', {
465
+ * data: { signing_secret: 'rotated-secret' },
466
+ * });
467
+ * ```
468
+ */
469
+ async update(
470
+ nanoId: string,
471
+ params: WebhookEndpointUpdateParams,
472
+ requestOptions?: ComposioRequestOptions
473
+ ): Promise<WebhookEndpoint> {
474
+ const parsedParams = WebhookEndpointUpdateParamsSchema.safeParse(params);
475
+ if (!parsedParams.success) {
476
+ throw new ValidationError('Failed to parse webhook endpoint update params', {
477
+ cause: parsedParams.error,
478
+ });
479
+ }
480
+ const result = await withCancellation(
481
+ () =>
482
+ this.client.webhookEndpoints.update(
483
+ nanoId,
484
+ { data: parsedParams.data.data },
485
+ requestOptions
486
+ ),
487
+ requestOptions?.signal
488
+ );
489
+ return transformWebhookEndpoint(result);
490
+ }
491
+}
492
+
493
+/**
494
+ * `composio.webhooks` namespace.
495
+ *
496
+ * - `subscriptions`: the project's outbound webhook subscription (where
497
+ * Composio delivers trigger and lifecycle events).
498
+ * - `endpoints`: inbound ingress URLs for third-party providers, one per
499
+ * toolkit + OAuth app pair.
500
+ *
501
+ * @example
502
+ * ```typescript
503
+ * const subscription = await composio.webhooks.subscriptions.set({
504
+ * webhookUrl: 'https://example.com/webhooks/composio',
505
+ * });
506
+ * const endpoints = await composio.webhooks.endpoints.list({ toolkitSlug: 'slack' });
507
+ * ```
508
+ */
509
+export class Webhooks {
510
+ /** Manage the project's outbound webhook subscription. */
511
+ subscriptions: WebhookSubscriptions;
512
+ /** Manage inbound webhook endpoints per toolkit + OAuth app. */
513
+ endpoints: WebhookEndpoints;
514
+
515
+ constructor(client: ComposioClient) {
516
+ this.subscriptions = new WebhookSubscriptions(client);
517
+ this.endpoints = new WebhookEndpoints(client);
518
+ telemetry.instrument(this, 'Webhooks');
519
+ }
520
+}