Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Chore: cleanup trigger instances

haxzie266af11d57ed
diff --git a/packages/core/src/errors/PusherErrors.ts b/packages/core/src/errors/PusherErrors.ts
new file mode 100644
index 000000000..fa94cb02e
--- /dev/null
+++ b/packages/core/src/errors/PusherErrors.ts
@@ -0,0 +1,28 @@
+import { ComposioError } from './ComposioError';
+
+export const PusherErrorCodes = {
+ PUSHER_CLIENT_NOT_FOUND: 'PUSHER_CLIENT_NOT_FOUND',
+ PUSHER_SUBSCRIPTION_ERROR: 'PUSHER_SUBSCRIPTION_ERROR',
+} as const;
+
+export class PusherClientNotFoundError extends ComposioError {
+ public name = 'PusherClientNotFoundError';
+ public code = PusherErrorCodes.PUSHER_CLIENT_NOT_FOUND;
+ public statusCode = 404;
+ public possibleFixes = ['Please contact support.'];
+
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options);
+ }
+}
+
+export class PusherSubscriptionError extends ComposioError {
+ public name = 'PusherSubscriptionError';
+ public code = PusherErrorCodes.PUSHER_SUBSCRIPTION_ERROR;
+ public statusCode = 400;
+ public possibleFixes = ['Please contact support.'];
+
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options);
+ }
+}
diff --git a/packages/core/src/models/Triggers.ts b/packages/core/src/models/Triggers.ts
index a2f0a213d..d02bf87e6 100644
--- a/packages/core/src/models/Triggers.ts
+++ b/packages/core/src/models/Triggers.ts
@@ -1,23 +1,35 @@
import ComposioClient from '@composio/client';
-import { RequestOptions } from '@composio/client/internal/request-options';
import {
- TriggerInstanceListActiveParams,
- TriggerInstanceUpsertParams,
- TriggerInstanceUpsertResponse,
+ TriggerInstanceListActiveResponse as TriggerInstanceListActiveResponseComposio,
TriggersTypeListParams,
TriggersTypeListResponse,
TriggersTypeRetrieveEnumResponse,
TriggersTypeRetrieveResponse,
} from '@composio/client/resources/index';
-import { TriggerStatusEnum, TriggerSubscribeParams } from '../types/triggers.types';
+import {
+ TriggerInstanceUpsertResponseSchema,
+ TriggerInstanceUpsertResponse,
+ TriggerInstanceUpsertParamsSchema,
+ TriggerInstanceUpsertParams,
+ TriggerInstanceListActiveParams,
+ TriggerInstanceListActiveParamsSchema,
+ TriggerInstanceListActiveResponse,
+ TriggerInstanceListActiveResponseItemSchema,
+ TriggerInstanceListActiveResponseSchema,
+ TriggerSubscribeParams,
+ TriggerInstanceManageUpdateParams,
+ TriggerInstanceManageUpdateResponse,
+ TriggerInstanceManageDeleteResponse,
+ TriggerInstanceManageDeleteResponseSchema,
+ TriggerSubscribeParamSchema,
+ IncomingTriggerPayloadSchema,
+ IncomingTriggerPayload,
+} from '../types/triggers.types';
import { PusherUtils, TriggerData } from '../utils/pusher';
import logger from '../utils/logger';
import { Session } from './Session';
import { telemetry } from '../telemetry/Telemetry';
-import {
- ManageDeleteResponse,
- ManageUpdateParams,
-} from '@composio/client/resources/trigger-instances/manage';
+import { ValidationError } from '../errors';
/**
* Trigger (Instance) class
* /api/v3/trigger_instances
@@ -31,12 +43,91 @@ export class Triggers {
telemetry.instrument(this);
}
+ /**
+ * Parse the trigger instance list active item
+ *
+ * @param response - The response from the composio client
+ * @returns The parsed trigger instance list active item
+ */
+ private parseTriggerInstanceListActiveItem(
+ response: TriggerInstanceListActiveResponseComposio['items'][0]
+ ) {
+ const parsed = TriggerInstanceListActiveResponseItemSchema.safeParse({
+ id: response.id,
+ connectedAccountId: response.connected_account_id,
+ disabledAt: response.disabled_at,
+ state: response.state,
+ triggerConfig: response.trigger_config,
+ triggerName: response.trigger_name,
+ updatedAt: response.updated_at,
+ triggerData: response.trigger_data,
+ uuid: response.uuid,
+ });
+ if (!parsed.success) {
+ throw new ValidationError(`Invalid trigger instance list active item`, {
+ cause: parsed.error,
+ });
+ }
+ return parsed.data;
+ }
+
/**
* Fetch list of all the active triggers
- * @returns {Promise<TriggerInstance[]>} List of trigger instances
+ *
+ * @param {TriggerInstanceListActiveParams} query - The query parameters to filter the trigger instances
+ * @returns {Promise<TriggerInstanceListActiveResponse>} List of trigger instances
+ *
+ * @throws {ValidationError} If the parameters are invalid
+ * @throws {Error} If the client is not authenticated
+ *
+ * @example
+ * ```ts
+ * const triggers = await triggers.listActive({
+ * authConfigIds: ['123'],
+ * connectedAccountIds: ['456'],
+ * });
+ * ```
*/
- async list(query?: TriggerInstanceListActiveParams, options?: RequestOptions) {
- return this.client.triggerInstances.listActive(query, options);
+ async listActive(
+ query?: TriggerInstanceListActiveParams
+ ): Promise<TriggerInstanceListActiveResponse> {
+ // Validate the parameters if provided
+
+ const parsedParams = TriggerInstanceListActiveParamsSchema.safeParse(query ?? {});
+
+ if (!parsedParams.success) {
+ throw new ValidationError(`Invalid parameters passed to list triggers`, {
+ cause: parsedParams.error,
+ });
+ }
+
+ const result = await this.client.triggerInstances.listActive(
+ query
+ ? {
+ auth_config_ids: parsedParams.data.authConfigIds,
+ connected_account_ids: parsedParams.data.connectedAccountIds,
+ limit: parsedParams.data.limit,
+ page: parsedParams.data.page,
+ show_disabled: parsedParams.data.showDisabled,
+ trigger_ids: parsedParams.data.triggerIds,
+ trigger_names: parsedParams.data.triggerNames,
+ }
+ : undefined
+ );
+
+ const parsedResult = TriggerInstanceListActiveResponseSchema.safeParse({
+ items: result.items.map(item => this.parseTriggerInstanceListActiveItem(item)),
+ nextCursor: result.next_cursor,
+ totalPages: result.total_pages,
+ } as TriggerInstanceListActiveResponse);
+
+ if (!parsedResult.success) {
+ throw new ValidationError(`Invalid trigger instance list active response`, {
+ cause: parsedResult.error,
+ });
+ }
+
+ return parsedResult.data;
}
/**
@@ -48,24 +139,45 @@ export class Triggers {
*/
async create(
slug: string,
- body: TriggerInstanceUpsertParams,
- options?: RequestOptions
+ body: TriggerInstanceUpsertParams
): Promise<TriggerInstanceUpsertResponse> {
- return this.client.triggerInstances.upsert(slug, body, options);
+ const parsedBody = TriggerInstanceUpsertParamsSchema.safeParse(body);
+
+ if (!parsedBody.success) {
+ throw new ValidationError(`Invalid parameters passed to create trigger`, {
+ cause: parsedBody.error,
+ });
+ }
+
+ const result = await this.client.triggerInstances.upsert(slug, {
+ connected_account_id: parsedBody.data.connectedAccountId,
+ trigger_config: parsedBody.data.triggerConfig,
+ });
+ const parsedResult = TriggerInstanceUpsertResponseSchema.safeParse({
+ triggerId: result.trigger_id,
+ } as TriggerInstanceUpsertResponse);
+
+ if (!parsedResult.success) {
+ throw new ValidationError(`Invalid trigger instance upsert response`, {
+ cause: parsedResult.error,
+ });
+ }
+
+ return parsedResult.data;
}
/**
* Update an existing trigger instance
*
* @param {string} slug - The slug of the trigger instance
- * @param {TriggerInstanceUpsertParams} body - The parameters to create the trigger instance
+ * @param {TriggerInstanceManageUpdateParams} body - The parameters to create the trigger instance
* @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
*/
async update(
slug: string,
- body: TriggerInstanceUpsertParams
- ): Promise<TriggerInstanceUpsertResponse> {
- return this.client.triggerInstances.upsert(slug, body);
+ body: TriggerInstanceManageUpdateParams
+ ): Promise<TriggerInstanceManageUpdateResponse> {
+ return this.client.triggerInstances.manage.update(slug, body);
}
/**
@@ -74,31 +186,25 @@ export class Triggers {
* @param {string} triggerId - The slug of the trigger instance
* @returns
*/
- async delete(triggerId: string): Promise<ManageDeleteResponse> {
- return this.client.triggerInstances.manage.delete(triggerId);
- }
+ async delete(triggerId: string): Promise<TriggerInstanceManageDeleteResponse> {
+ const result = await this.client.triggerInstances.manage.delete(triggerId);
+ const parsedResult = TriggerInstanceManageDeleteResponseSchema.safeParse({
+ triggerId: result.trigger_id,
+ } as TriggerInstanceManageDeleteResponse);
- /**
- * Update the status of a trigger
- *
- * @param {TriggerStatusEnum} status - The new status of the trigger
- * @param {TriggerInstanceUpdateStatusParams} params - The parameters to update the trigger instance
- * @param {RequestOptions} options - Request options
- * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
- */
- async updateStatus(
- status: TriggerStatusEnum,
- params: ManageUpdateParams,
- options?: RequestOptions
- ) {
- return this.client.triggerInstances.manage.update(status, params, options);
+ if (!parsedResult.success) {
+ throw new ValidationError(`Invalid trigger instance manage delete response`, {
+ cause: parsedResult.error,
+ });
+ }
+
+ return parsedResult.data;
}
/**
* Disable a trigger instance
*
* @param {string} triggerId - The id of the trigger instance
- * @param {RequestOptions options - Request options
* @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
*/
async disable(triggerId: string) {
@@ -111,7 +217,6 @@ export class Triggers {
* Enable a trigger instance
*
* @param {string} triggerId - The id of the trigger instance
- * @param {RequestOptions options - Request options
* @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
*/
async enable(triggerId: string) {
@@ -130,11 +235,8 @@ export class Triggers {
* @param {RequestOptions} options - Request options
* @returns {Promise<TriggersTypeListResponse>} The list of trigger types
*/
- async listTypes(
- query?: TriggersTypeListParams,
- options?: RequestOptions
- ): Promise<TriggersTypeListResponse> {
- return this.client.triggersTypes.list(query, options);
+ async listTypes(query?: TriggersTypeListParams): Promise<TriggersTypeListResponse> {
+ return this.client.triggersTypes.list(query);
}
/**
@@ -144,8 +246,8 @@ export class Triggers {
* @param {RequestOptions} options - request options
* @returns {Promise<TriggersTypeRetrieveResponse>} The trigger type object
*/
- async getType(slug: string, options?: RequestOptions): Promise<TriggersTypeRetrieveResponse> {
- return this.client.triggersTypes.retrieve(slug, options);
+ async getType(slug: string): Promise<TriggersTypeRetrieveResponse> {
+ return this.client.triggersTypes.retrieve(slug);
}
/**
@@ -155,13 +257,38 @@ export class Triggers {
* @param options
* @returns
*/
- async listEnum(options?: RequestOptions): Promise<TriggersTypeRetrieveEnumResponse> {
- return this.client.triggersTypes.retrieveEnum(options);
+ async listEnum(): Promise<TriggersTypeRetrieveEnumResponse> {
+ return this.client.triggersTypes.retrieveEnum();
}
- async subscribe(fn: (_data: TriggerData) => void, filters: TriggerSubscribeParams = {}) {
+ /**
+ * Subscribe to all the triggers
+ *
+ * @param fn - The function to call when a trigger is received
+ * @param filters - The filters to apply to the triggers
+ *
+ * @example
+ * ```ts
+ *
+ * triggers.subscribe((data) => {
+ * console.log(data);
+ * }, );
+ * ```
+ */
+ async subscribe(
+ fn: (_data: IncomingTriggerPayload) => void,
+ filters: TriggerSubscribeParams = {}
+ ) {
if (!fn) throw new Error('Function is required for trigger subscription');
+ const parsedFilters = TriggerSubscribeParamSchema.safeParse(filters);
+
+ if (!parsedFilters.success) {
+ throw new ValidationError(`Invalid parameters passed to subscribe to triggers`, {
+ cause: parsedFilters.error,
+ });
+ }
+
// @TODO: Get the client id from the backend
const session = new Session(this.client);
const sessionInfo = await session.getInfo();
@@ -172,35 +299,142 @@ export class Triggers {
await PusherUtils.getPusherClient(this.client.baseURL, this.client.apiKey);
- const shouldSendTrigger = (data: TriggerData) => {
- if (Object.keys(filters).length === 0) return true;
- else {
- return (
- (!filters.appName || data.appName.toLowerCase() === filters.appName.toLowerCase()) &&
- (!filters.triggerId ||
- data.metadata.id.toLowerCase() === filters.triggerId.toLowerCase()) &&
- (!filters.connectionId ||
- data.metadata.connectionId.toLowerCase() === filters.connectionId.toLowerCase()) &&
- (!filters.triggerName ||
- data.metadata.triggerName.toLowerCase() === filters.triggerName.toLowerCase()) &&
- (!filters.entityId ||
- data.metadata.connection.clientUniqueUserId.toLowerCase() ===
- filters.entityId.toLowerCase()) &&
- (!filters.integrationId ||
- data.metadata.connection.integrationId.toLowerCase() ===
- filters.integrationId.toLowerCase())
+ /**
+ * Applies compound filters to the trigger data
+ * @param data data to apply filters to
+ * @returns True if the trigger data matches the filters, false otherwise
+ */
+ const shouldSendTriggerAfterFilters = (data: IncomingTriggerPayload): boolean => {
+ // Check if toolkits filter is provided and matches
+ if (
+ parsedFilters.data.toolkits?.length &&
+ !parsedFilters.data.toolkits
+ .map(toolkit => toolkit.toLowerCase())
+ .includes(data.toolkitSlug.toLowerCase())
+ ) {
+ logger.debug(
+ 'Trigger does not match toolkits filter',
+ JSON.stringify(parsedFilters.data.toolkits, null, 2)
+ );
+ return false;
+ }
+
+ // Check if triggerId filter matches
+ if (parsedFilters.data.triggerId && parsedFilters.data.triggerId !== data.id) {
+ logger.debug(
+ 'Trigger does not match triggerId filter',
+ JSON.stringify(parsedFilters.data.triggerId, null, 2)
+ );
+ return false;
+ }
+
+ // Check if connectedAccountId filter matches
+ if (
+ parsedFilters.data.connectedAccountId &&
+ parsedFilters.data.connectedAccountId !== data.metadata.connectedAccountId
+ ) {
+ logger.debug(
+ 'Trigger does not match connectedAccountId filter',
+ JSON.stringify(parsedFilters.data.connectedAccountId, null, 2)
+ );
+ return false;
+ }
+
+ // Check if triggerName filter matches
+ if (
+ parsedFilters.data.triggerName &&
+ parsedFilters.data.triggerName !== data.metadata.triggerName
+ ) {
+ logger.debug(
+ 'Trigger does not match triggerName filter',
+ JSON.stringify(parsedFilters.data.triggerName, null, 2)
+ );
+ return false;
+ }
+
+ // Check if triggerData filter matches
+ if (
+ parsedFilters.data.triggerData &&
+ parsedFilters.data.triggerData !== data.metadata.triggerData
+ ) {
+ logger.debug(
+ 'Trigger does not match triggerData filter',
+ JSON.stringify(parsedFilters.data.triggerData, null, 2)
+ );
+ return false;
+ }
+
+ // Check if userId (clientUniqueUserId) filter matches
+ if (
+ parsedFilters.data.userId &&
+ parsedFilters.data.userId !== data.metadata.connection.clientUniqueUserId
+ ) {
+ logger.debug(
+ 'Trigger does not match userId filter',
+ JSON.stringify(parsedFilters.data.userId, null, 2)
);
+ return false;
}
+
+ logger.debug('Trigger matches all filters', JSON.stringify(parsedFilters.data, null, 2));
+ // If all filters pass or no filters were provided, return true
+ return true;
};
- logger.debug('Subscribing to triggers', filters);
+ logger.debug('Subscribing to triggers', JSON.stringify(filters, null, 2));
PusherUtils.triggerSubscribe(clientId, (data: TriggerData) => {
- if (shouldSendTrigger(data)) {
- fn(data);
+ logger.debug('Received trigger data', JSON.stringify(data, null, 2));
+
+ const parsedData = IncomingTriggerPayloadSchema.safeParse({
+ id: data.metadata.id,
+ clientId: String(data.clientId),
+ triggerSlug: data.metadata.triggerName,
+ toolkitSlug: data.appName,
+ payload: data.payload,
+ originalPayload: data.originalPayload,
+ metadata: {
+ ...data.metadata,
+ id: data.metadata.id,
+ connectedAccountId: data.metadata.connection.id,
+ triggerSlug: data.metadata.triggerName,
+ triggerName: data.metadata.triggerName,
+ triggerData: data.metadata.triggerData,
+ triggerConfig: data.metadata.triggerConfig,
+ connection: {
+ id: data.metadata.connection.id,
+ integrationId: data.metadata.connection.integrationId,
+ clientUniqueUserId: data.metadata.connection.clientUniqueUserId,
+ status: data.metadata.connection.status,
+ },
+ },
+ } as IncomingTriggerPayload);
+ if (!parsedData.success) {
+ throw new ValidationError(`Invalid trigger payload`, {
+ cause: parsedData.error,
+ });
+ }
+ if (shouldSendTriggerAfterFilters(parsedData.data)) {
+ fn(parsedData.data);
+ } else {
+ logger.debug('Trigger does not match filters', JSON.stringify(parsedFilters.data, null, 2));
}
});
}
+ /**
+ * Unsubscribe from all the triggers
+ *
+ * @returns {Promise<void>}
+ *
+ * @example
+ * ```ts
+ * composio.trigger.subscribe((data) => {
+ * console.log(data);
+ * });
+ *
+ * await triggers.unsubscribe();
+ * ```
+ */
async unsubscribe() {
const session = new Session(this.client);
const sessionInfo = await session.getInfo();
diff --git a/packages/core/src/types/triggers.types.ts b/packages/core/src/types/triggers.types.ts
index 8c8c39512..0197ded44 100644
--- a/packages/core/src/types/triggers.types.ts
+++ b/packages/core/src/types/triggers.types.ts
@@ -1,14 +1,118 @@
-import { z } from "zod";
+import { z } from 'zod';
-export type TriggerStatusEnum = "enable" | "disable";
+export const TriggerStatuses = {
+ ENABLE: 'enable',
+ DISABLE: 'disable',
+} as const;
+export type TriggerStatusType = (typeof TriggerStatuses)[keyof typeof TriggerStatuses];
+export const TriggerStatusEnum = z.enum(['enable', 'disable']);
-export const ZTriggerSubscribeParam = z.object({
- appName: z.string().optional(),
- triggerId: z.string().optional(),
- connectionId: z.string().optional(),
- integrationId: z.string().optional(),
- triggerName: z.string().optional(),
- triggerData: z.string().optional(),
- entityId: z.string().optional(),
+export const TriggerSubscribeParamSchema = z.object({
+ toolkits: z.array(z.string()).optional(),
+ triggerId: z.string().optional(),
+ connectedAccountId: z.string().optional(),
+ authConfigId: z.string().optional(),
+ triggerName: z.string().optional(),
+ triggerData: z.string().optional(),
+ userId: z.string().optional(),
});
-export type TriggerSubscribeParams = z.infer<typeof ZTriggerSubscribeParam>;
\ No newline at end of file
+export type TriggerSubscribeParams = z.infer<typeof TriggerSubscribeParamSchema>;
+
+export const TriggerInstanceListActiveParamsSchema = z.object({
+ authConfigIds: z.array(z.string()).nullable().optional(),
+ connectedAccountIds: z.array(z.string()).nullable().optional(),
+ limit: z.number().optional(),
+ page: z.number().optional(),
+ showDisabled: z.boolean().nullable().optional(),
+ triggerIds: z.array(z.string()).nullable().optional(),
+ triggerNames: z.array(z.string()).nullable().optional(),
+});
+
+export type TriggerInstanceListActiveParams = z.infer<typeof TriggerInstanceListActiveParamsSchema>;
+
+export const TriggerInstanceListActiveResponseItemSchema = z.object({
+ id: z.string(),
+ connectedAccountId: z.string(),
+ disabledAt: z.string().nullable(),
+ state: z.record(z.unknown()),
+ triggerConfig: z.record(z.unknown()),
+ triggerName: z.string(),
+ updatedAt: z.string(),
+ triggerData: z.string().optional(),
+ uuid: z.string().optional(),
+});
+
+export const TriggerInstanceListActiveResponseSchema = z.object({
+ items: z.array(TriggerInstanceListActiveResponseItemSchema),
+ nextCursor: z.string().nullable(),
+ totalPages: z.number(),
+});
+
+export type TriggerInstanceListActiveResponse = z.infer<
+ typeof TriggerInstanceListActiveResponseSchema
+>;
+export type TriggerInstanceListActiveResponseItem = z.infer<
+ typeof TriggerInstanceListActiveResponseItemSchema
+>;
+
+export const TriggerInstanceUpsertParamsSchema = z.object({
+ connectedAccountId: z.string().optional(),
+ triggerConfig: z.record(z.unknown()).optional(),
+});
+
+export type TriggerInstanceUpsertParams = z.infer<typeof TriggerInstanceUpsertParamsSchema>;
+
+export const TriggerInstanceUpsertResponseSchema = z.object({
+ triggerId: z.string(),
+});
+
+export type TriggerInstanceUpsertResponse = z.infer<typeof TriggerInstanceUpsertResponseSchema>;
+
+export const TriggerInstanceManageUpdateParamsSchema = z.object({
+ status: z.enum(['enable', 'disable']),
+});
+
+export type TriggerInstanceManageUpdateParams = z.infer<
+ typeof TriggerInstanceManageUpdateParamsSchema
+>;
+
+export const TriggerInstanceManageUpdateResponseSchema = z.object({
+ status: z.enum(['success']),
+});
+
+export type TriggerInstanceManageUpdateResponse = z.infer<
+ typeof TriggerInstanceManageUpdateResponseSchema
+>;
+
+export const TriggerInstanceManageDeleteResponseSchema = z.object({
+ triggerId: z.string(),
+});
+
+export type TriggerInstanceManageDeleteResponse = z.infer<
+ typeof TriggerInstanceManageDeleteResponseSchema
+>;
+
+export const IncomingTriggerPayloadSchema = z.object({
+ id: z.string().describe('The ID of the trigger'),
+ clientId: z.string().describe('The ID of the client that triggered the event'),
+ triggerSlug: z.string().describe('The slug of the trigger that triggered the event'),
+ toolkitSlug: z.string().describe('The slug of the toolkit that triggered the event'),
+ payload: z.record(z.unknown()).describe('The payload of the trigger'),
+ originalPayload: z.record(z.unknown()).describe('The original payload of the trigger'),
+ metadata: z.object({
+ id: z.string(),
+ connectedAccountId: z.string(),
+ triggerSlug: z.string(),
+ triggerName: z.string(),
+ triggerData: z.string(),
+ triggerConfig: z.record(z.unknown()),
+ connection: z.object({
+ id: z.string(),
+ integrationId: z.string(),
+ clientUniqueUserId: z.string(),
+ status: z.enum(['enable', 'disable']),
+ }),
+ }),
+});
+
+export type IncomingTriggerPayload = z.infer<typeof IncomingTriggerPayloadSchema>;
diff --git a/packages/core/src/utils/pusher.ts b/packages/core/src/utils/pusher.ts
index 62fbd0862..1f2688474 100644
--- a/packages/core/src/utils/pusher.ts
+++ b/packages/core/src/utils/pusher.ts
@@ -1,24 +1,22 @@
-import logger from "./logger";
+import { PusherSubscriptionError } from '../errors/PusherErrors';
+import logger from './logger';
-const PUSHER_KEY = process.env.CLIENT_PUSHER_KEY || "ff9f18c208855d77a152";
-const PUSHER_CLUSTER = "mt1";
+const PUSHER_KEY = process.env.CLIENT_PUSHER_KEY || 'ff9f18c208855d77a152';
+const PUSHER_CLUSTER = 'mt1';
type Channel = {
subscribe: (channelName: string) => unknown;
unsubscribe: (channelName: string) => unknown;
- bind: (
- event: string,
- callback: (data: Record<string, unknown>) => void
- ) => unknown;
+ bind: (event: string, callback: (data: Record<string, unknown>) => void) => unknown;
};
type PusherClient = {
subscribe: (channelName: string) => Channel;
unsubscribe: (channelName: string) => unknown;
- bind: (
- event: string,
- callback: (data: Record<string, unknown>) => void
- ) => unknown;
+ bind: (event: string, callback: (data: Record<string, unknown>) => void) => unknown;
+ connection: {
+ bind: (event: string, callback: (error: Error) => void) => void;
+ };
};
type TChunkedTriggerData = {
@@ -51,25 +49,38 @@ export type TriggerData = {
export class PusherUtils {
static pusherClient: PusherClient;
- static getPusherClient(baseURL: string, apiKey: string): PusherClient {
- if (!PusherUtils.pusherClient) {
- // Dynamic import not available, using require for now
- // TODO: Update to use dynamic import when available
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const PusherClient = require("pusher-js");
- PusherUtils.pusherClient = new PusherClient(PUSHER_KEY, {
- cluster: PUSHER_CLUSTER,
- channelAuthorization: {
- endpoint: `${baseURL}/api/v1/client/auth/pusher_auth`,
- headers: {
- "x-api-key": apiKey,
+ static async getPusherClient(baseURL: string, apiKey: string): Promise<PusherClient> {
+ try {
+ if (!PusherUtils.pusherClient) {
+ // Dynamic import not available, using require for now
+ // TODO: Update to use dynamic import when available
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const PusherClient = require('pusher-js');
+ PusherUtils.pusherClient = new PusherClient(PUSHER_KEY, {
+ cluster: PUSHER_CLUSTER,
+ channelAuthorization: {
+ endpoint: `${baseURL}/api/v1/client/auth/pusher_auth`,
+ headers: {
+ 'x-api-key': apiKey,
+ },
+ transport: 'ajax',
},
- transport: "ajax",
- },
- });
+ });
+
+ // Add connection error handling
+ PusherUtils.pusherClient.connection.bind('error', (err: Error) => {
+ logger.error('Pusher connection error:', err);
+ throw new Error(`Pusher connection error: ${err.message}`);
+ });
+ }
+ return PusherUtils.pusherClient;
+ } catch (error: unknown) {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ logger.error('Failed to initialize Pusher client:', error);
+ throw new Error(`Failed to initialize Pusher client: ${errorMessage}`);
}
- return PusherUtils.pusherClient;
}
+
/**
* Subscribes to a Pusher channel and binds an event to a callback function.
* @param {string} channelName - The name of the channel to subscribe to.
@@ -85,9 +96,7 @@ export class PusherUtils {
try {
await PusherUtils.pusherClient.subscribe(channelName).bind(event, fn);
} catch (error) {
- logger.error(
- `Error subscribing to ${channelName} with event ${event}: ${error}`
- );
+ logger.error(`Error subscribing to ${channelName} with event ${event}: ${error}`);
}
}
@@ -111,54 +120,139 @@ export class PusherUtils {
event: string,
callback: (data: Record<string, unknown>) => void
): void {
- channel.bind(event, callback); // Allow normal unchunked events.
-
- // Now the chunked variation. Allows arbitrarily long messages.
- const events: {
- [key: string]: { chunks: string[]; receivedFinal: boolean };
- } = {};
- channel.bind("chunked-" + event, (data) => {
- const typedData = data as TChunkedTriggerData;
- if (!events.hasOwnProperty(typedData.id)) {
- events[typedData.id] = { chunks: [], receivedFinal: false };
- }
- const ev = events[typedData.id];
- ev.chunks[typedData.index] = typedData.chunk;
- if (typedData.final) ev.receivedFinal = true;
- if (
- ev.receivedFinal &&
- ev.chunks.length === Object.keys(ev.chunks).length
- ) {
- callback(JSON.parse(ev.chunks.join("")));
- delete events[typedData.id];
- }
- });
+ try {
+ // Wrap the callback to handle errors
+ const safeCallback = (data: Record<string, unknown>) => {
+ try {
+ callback(data);
+ } catch (error: unknown) {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ logger.error('Error in chunked event callback:', errorMessage);
+ // Don't throw here to prevent breaking the subscription
+ }
+ };
+
+ channel.bind(event, safeCallback);
+
+ // Now the chunked variation. Allows arbitrarily long messages.
+ const events: {
+ [key: string]: { chunks: string[]; receivedFinal: boolean };
+ } = {};
+
+ channel.bind('chunked-' + event, data => {
+ try {
+ const typedData = data as TChunkedTriggerData;
+
+ // Validate chunked data
+ if (
+ !typedData ||
+ typeof typedData.id !== 'string' ||
+ typeof typedData.index !== 'number'
+ ) {
+ throw new Error('Invalid chunked trigger data format');
+ }
+
+ if (!events.hasOwnProperty(typedData.id)) {
+ events[typedData.id] = { chunks: [], receivedFinal: false };
+ }
+
+ const ev = events[typedData.id];
+ ev.chunks[typedData.index] = typedData.chunk;
+
+ if (typedData.final) ev.receivedFinal = true;
+
+ if (ev.receivedFinal && ev.chunks.length === Object.keys(ev.chunks).length) {
+ try {
+ const parsedData = JSON.parse(ev.chunks.join(''));
+ safeCallback(parsedData);
+ } catch (parseError: unknown) {
+ const errorMessage =
+ parseError instanceof Error ? parseError.message : String(parseError);
+ logger.error('Failed to parse chunked data:', errorMessage);
+ } finally {
+ delete events[typedData.id];
+ }
+ }
+ } catch (error: unknown) {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ logger.error('Error processing chunked trigger data:', errorMessage);
+ // Clean up the event data to prevent memory leaks
+ if (data && typeof data === 'object' && 'id' in data) {
+ delete events[data.id as string];
+ }
+ }
+ });
+ } catch (error: unknown) {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ logger.error('Failed to bind chunked events:', error);
+ throw new Error(`Failed to bind chunked events: ${errorMessage}`);
+ }
}
/**
* Subscribes to a trigger channel for a client and handles chunked data.
* @param {string} clientId - The unique identifier for the client subscribing to the events.
* @param {(data: TriggerData) => void} fn - The callback function to execute when trigger data is received.
+ *
+ * @example
+ * ```ts
+ * composio.trigger.subscribe((data) => {
+ * console.log(data);
+ * });
+ * ```
*/
- static triggerSubscribe(
- clientId: string,
- fn: (data: TriggerData) => void
- ): void {
- const channel = PusherUtils.pusherClient.subscribe(
- `private-${clientId}_triggers`
- );
- PusherUtils.bindWithChunking(
- channel as PusherClient,
- "trigger_to_client",
- fn as (data: unknown) => void
- );
-
- logger.info(
- `Subscribed to triggers. You should start receiving events now.`
- );
+ static triggerSubscribe(clientId: string, fn: (data: TriggerData) => void): void {
+ try {
+ if (!PusherUtils.pusherClient) {
+ throw new Error('Pusher client not initialized');
+ }
+
+ const channel = PusherUtils.pusherClient.subscribe(`private-${clientId}_triggers`);
+
+ // Add subscription error handling
+ channel.bind('pusher:subscription_error', (data: Record<string, unknown>) => {
+ const error = data.error ? String(data.error) : 'Unknown subscription error';
+ throw new PusherSubscriptionError(`Trigger subscription error`, {
+ cause: error,
+ });
+ });
+
+ // Wrap the callback to handle errors
+ const safeCallback = (data: TriggerData) => {
+ try {
+ fn(data);
+ } catch (error: unknown) {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ logger.error('Error in trigger callback:', errorMessage);
+ // Don't throw here to prevent breaking the subscription
+ }
+ };
+
+ PusherUtils.bindWithChunking(
+ channel as PusherClient,
+ 'trigger_to_client',
+ safeCallback as (data: unknown) => void
+ );
+
+ logger.info(`Subscribed to triggers. You should start receiving events now.`);
+ } catch (error: unknown) {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ logger.error('Failed to subscribe to triggers:', error);
+ throw new Error(`Failed to subscribe to triggers: ${errorMessage}`);
+ }
}
static triggerUnsubscribe(clientId: string): void {
- PusherUtils.pusherClient.unsubscribe(`${clientId}_triggers`);
+ try {
+ if (!PusherUtils.pusherClient) {
+ throw new Error('Pusher client not initialized');
+ }
+ PusherUtils.pusherClient.unsubscribe(`${clientId}_triggers`);
+ logger.info('Successfully unsubscribed from triggers');
+ } catch (error: unknown) {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ logger.error('Failed to unsubscribe from triggers:', error);
+ throw new Error(`Failed to unsubscribe from triggers: ${errorMessage}`);
+ }
}
}
diff --git a/packages/core/test/models/triggers.test.ts b/packages/core/test/models/triggers.test.ts
index fef885931..36e94c747 100644
--- a/packages/core/test/models/triggers.test.ts
+++ b/packages/core/test/models/triggers.test.ts
@@ -6,6 +6,7 @@ import { PusherUtils, TriggerData } from '../../src/utils/pusher';
import logger from '../../src/utils/logger';
import { TriggerStatusEnum, TriggerSubscribeParams } from '../../src/types/triggers.types';
import { telemetry } from '../../src/telemetry/Telemetry';
+import { ValidationError } from '../../src/errors';
// Mock dependencies
vi.mock('../../src/models/Session');
@@ -46,36 +47,41 @@ const mockTriggerInstances = {
items: [
{
id: 'trigger-1',
- slug: 'github_webhook',
- status: 'active',
- connectedAccountId: 'conn-123',
- config: { webhook_url: 'https://example.com/webhook' },
- createdAt: '2024-01-01T00:00:00Z',
- updatedAt: '2024-01-01T00:00:00Z',
+ connected_account_id: 'conn-123',
+ disabled_at: null,
+ state: { lastRun: '2024-01-01T00:00:00Z' },
+ trigger_config: { webhook_url: 'https://example.com/webhook' },
+ trigger_name: 'github_webhook',
+ updated_at: '2024-01-01T00:00:00Z',
+ trigger_data: '{"event":"push"}',
+ uuid: 'uuid-123',
},
{
id: 'trigger-2',
- slug: 'slack_message',
- status: 'inactive',
- connectedAccountId: 'conn-456',
- config: { channel: '#general' },
- createdAt: '2024-01-02T00:00:00Z',
- updatedAt: '2024-01-02T00:00:00Z',
+ connected_account_id: 'conn-456',
+ disabled_at: '2024-01-02T00:00:00Z',
+ state: { lastRun: '2024-01-02T00:00:00Z' },
+ trigger_config: { channel: '#general' },
+ trigger_name: 'slack_message',
+ updated_at: '2024-01-02T00:00:00Z',
+ trigger_data: '{"event":"message"}',
+ uuid: 'uuid-456',
},
],
- totalPages: 1,
- page: 1,
- pageSize: 10,
+ next_cursor: null,
+ total_pages: 1,
};
-const mockTriggerInstance = {
- id: 'trigger-123',
- slug: 'test_trigger',
- status: 'active',
- connectedAccountId: 'conn-123',
- config: { param1: 'value1' },
- createdAt: '2024-01-01T00:00:00Z',
- updatedAt: '2024-01-01T00:00:00Z',
+const mockTriggerUpsertResponse = {
+ trigger_id: 'trigger-123',
+};
+
+const mockTriggerUpdateResponse = {
+ status: 'success',
+};
+
+const mockTriggerDeleteResponse = {
+ trigger_id: 'trigger-123',
};
const mockTriggerTypes = {
@@ -89,15 +95,6 @@ const mockTriggerTypes = {
optional: ['secret'],
},
},
- {
- slug: 'slack_message',
- name: 'Slack Message',
- description: 'Triggered when a Slack message is received',
- config: {
- required: ['channel'],
- optional: ['pattern'],
- },
- },
],
totalPages: 1,
page: 1,
@@ -111,10 +108,6 @@ const mockTriggerType = {
required: ['webhook_url'],
optional: ['secret'],
},
- toolkit: {
- slug: 'github',
- name: 'GitHub',
- },
};
const mockTriggerEnum = {
@@ -147,13 +140,32 @@ const mockTriggerData: TriggerData = {
id: 'conn-123',
integrationId: 'github',
clientUniqueUserId: 'user-456',
- status: 'active',
+ status: 'enable',
},
},
};
-const mockTriggerUpdateResponse = {
- status: 'success',
+const mockIncomingTriggerPayload = {
+ id: 'trigger-123',
+ clientId: '123',
+ triggerSlug: 'github_webhook',
+ toolkitSlug: 'github',
+ payload: { action: 'push', repository: 'test-repo' },
+ originalPayload: { action: 'push', repository: 'test-repo' },
+ metadata: {
+ id: 'trigger-123',
+ connectedAccountId: 'conn-123',
+ triggerSlug: 'github_webhook',
+ triggerName: 'github_webhook',
+ triggerData: '{"action":"push"}',
+ triggerConfig: { webhook_url: 'https://example.com/webhook' },
+ connection: {
+ id: 'conn-123',
+ integrationId: 'github',
+ clientUniqueUserId: 'user-456',
+ status: 'enable',
+ },
+ },
};
describe('Triggers', () => {
@@ -198,21 +210,58 @@ describe('Triggers', () => {
it('should list active trigger instances', async () => {
mockClient.triggerInstances.listActive.mockResolvedValue(mockTriggerInstances);
- const result = await triggers.list();
+ const result = await triggers.listActive();
+
+ expect(mockClient.triggerInstances.listActive).toHaveBeenCalledWith(undefined);
+ expect(result).toEqual({
+ items: mockTriggerInstances.items.map(item => ({
+ id: item.id,
+ connectedAccountId: item.connected_account_id,
+ disabledAt: item.disabled_at,
+ state: item.state,
+ triggerConfig: item.trigger_config,
+ triggerName: item.trigger_name,
+ updatedAt: item.updated_at,
+ triggerData: item.trigger_data,
+ uuid: item.uuid,
+ })),
+ nextCursor: null,
+ totalPages: 1,
+ });
+ });
+
+ it('should throw validation error for invalid response', async () => {
+ mockClient.triggerInstances.listActive.mockResolvedValue({
+ items: [{ invalid: 'data' }],
+ });
- expect(mockClient.triggerInstances.listActive).toHaveBeenCalledWith(undefined, undefined);
- expect(result).toEqual(mockTriggerInstances);
+ await expect(triggers.listActive()).rejects.toThrow(ValidationError);
});
it('should list active trigger instances with query parameters', async () => {
- const query = { limit: 5, page: 2 };
- const options = { timeout: 5000 };
+ const query = {
+ authConfigIds: ['auth-1'],
+ connectedAccountIds: ['conn-1'],
+ limit: 5,
+ page: 2,
+ showDisabled: true,
+ triggerIds: ['trigger-1'],
+ triggerNames: ['github_webhook'],
+ };
+
mockClient.triggerInstances.listActive.mockResolvedValue(mockTriggerInstances);
- const result = await triggers.list(query, options);
+ await triggers.listActive(query);
- expect(mockClient.triggerInstances.listActive).toHaveBeenCalledWith(query, options);
- expect(result).toEqual(mockTriggerInstances);
+ expect(mockClient.triggerInstances.listActive).toHaveBeenCalledWith({
+ auth_config_ids: query.authConfigIds,
+ connected_account_ids: query.connectedAccountIds,
+ limit: query.limit,
+ page: query.page,
+ show_disabled: query.showDisabled,
+ trigger_ids: query.triggerIds,
+ trigger_names: query.triggerNames,
+ });
});
});
@@ -221,83 +270,56 @@ describe('Triggers', () => {
const slug = 'github_webhook';
const body = {
connectedAccountId: 'conn-123',
- config: { webhook_url: 'https://example.com/webhook' },
- } as any;
- mockClient.triggerInstances.upsert.mockResolvedValue(mockTriggerInstance);
+ triggerConfig: { webhook_url: 'https://example.com/webhook' },
+ };
+ mockClient.triggerInstances.upsert.mockResolvedValue(mockTriggerUpsertResponse);
const result = await triggers.create(slug, body);
- expect(mockClient.triggerInstances.upsert).toHaveBeenCalledWith(slug, body, undefined);
- expect(result).toEqual(mockTriggerInstance);
- });
-
- it('should create a new trigger instance with options', async () => {
- const slug = 'github_webhook';
- const body = {
- connectedAccountId: 'conn-123',
- config: { webhook_url: 'https://example.com/webhook' },
- } as any;
- const options = { timeout: 5000 };
- mockClient.triggerInstances.upsert.mockResolvedValue(mockTriggerInstance);
-
- const result = await triggers.create(slug, body, options);
-
- expect(mockClient.triggerInstances.upsert).toHaveBeenCalledWith(slug, body, options);
- expect(result).toEqual(mockTriggerInstance);
+ expect(mockClient.triggerInstances.upsert).toHaveBeenCalledWith(slug, {
+ connected_account_id: body.connectedAccountId,
+ trigger_config: body.triggerConfig,
+ });
+ expect(result).toEqual({ triggerId: mockTriggerUpsertResponse.trigger_id });
});
});
describe('update', () => {
- it('should update an existing trigger instance', async () => {
- const slug = 'github_webhook';
- const body = {
- connectedAccountId: 'conn-123',
- config: { webhook_url: 'https://updated.example.com/webhook' },
- } as any;
- mockClient.triggerInstances.upsert.mockResolvedValue(mockTriggerInstance);
+ it('should update a trigger instance status', async () => {
+ const triggerId = 'trigger-123';
+ const body = { status: 'enable' as const };
+ mockClient.triggerInstances.manage.update.mockResolvedValue(mockTriggerUpdateResponse);
- const result = await triggers.update(slug, body);
+ const result = await triggers.update(triggerId, body);
- expect(mockClient.triggerInstances.upsert).toHaveBeenCalledWith(slug, body);
- expect(result).toEqual(mockTriggerInstance);
+ expect(mockClient.triggerInstances.manage.update).toHaveBeenCalledWith(triggerId, body);
+ expect(result).toEqual(mockTriggerUpdateResponse);
});
});
describe('delete', () => {
it('should delete a trigger instance', async () => {
const triggerId = 'trigger-123';
- const deleteResponse = { success: true, message: 'Trigger deleted successfully' };
- mockClient.triggerInstances.manage.delete.mockResolvedValue(deleteResponse as any);
+ mockClient.triggerInstances.manage.delete.mockResolvedValue(mockTriggerDeleteResponse);
const result = await triggers.delete(triggerId);
expect(mockClient.triggerInstances.manage.delete).toHaveBeenCalledWith(triggerId);
- expect(result).toEqual(deleteResponse);
+ expect(result).toEqual({ triggerId: mockTriggerDeleteResponse.trigger_id });
});
- });
-
- describe('updateStatus', () => {
- it('should update the status of a trigger', async () => {
- const status: TriggerStatusEnum = 'enable';
- const params = { triggerId: 'trigger-123', status: status };
- const options = { timeout: 5000 };
- mockClient.triggerInstances.manage.update.mockResolvedValue(mockTriggerUpdateResponse as any);
- const result = await triggers.updateStatus(status, params, options);
+ it('should throw validation error for invalid response', async () => {
+ const triggerId = 'trigger-123';
+ mockClient.triggerInstances.manage.delete.mockResolvedValue({ invalid: 'response' });
- expect(mockClient.triggerInstances.manage.update).toHaveBeenCalledWith(
- status,
- params,
- options
- );
- expect(result).toEqual(mockTriggerUpdateResponse);
+ await expect(triggers.delete(triggerId)).rejects.toThrow(ValidationError);
});
});
describe('disable', () => {
it('should disable a trigger instance', async () => {
const triggerId = 'trigger-123';
- mockClient.triggerInstances.manage.update.mockResolvedValue(mockTriggerUpdateResponse as any);
+ mockClient.triggerInstances.manage.update.mockResolvedValue(mockTriggerUpdateResponse);
const result = await triggers.disable(triggerId);
@@ -328,18 +350,17 @@ describe('Triggers', () => {
const result = await triggers.listTypes();
- expect(mockClient.triggersTypes.list).toHaveBeenCalledWith(undefined, undefined);
+ expect(mockClient.triggersTypes.list).toHaveBeenCalledWith(undefined);
expect(result).toEqual(mockTriggerTypes);
});
it('should list trigger types with query parameters', async () => {
const query = { limit: 10, toolkit: 'github' };
- const options = { timeout: 5000 };
mockClient.triggersTypes.list.mockResolvedValue(mockTriggerTypes);
- const result = await triggers.listTypes(query, options);
+ const result = await triggers.listTypes(query);
- expect(mockClient.triggersTypes.list).toHaveBeenCalledWith(query, options);
+ expect(mockClient.triggersTypes.list).toHaveBeenCalledWith(query);
expect(result).toEqual(mockTriggerTypes);
});
});
@@ -351,18 +372,7 @@ describe('Triggers', () => {
const result = await triggers.getType(slug);
- expect(mockClient.triggersTypes.retrieve).toHaveBeenCalledWith(slug, undefined);
- expect(result).toEqual(mockTriggerType);
- });
-
- it('should retrieve a trigger type with options', async () => {
- const slug = 'github_webhook';
- const options = { timeout: 5000 };
- mockClient.triggersTypes.retrieve.mockResolvedValue(mockTriggerType);
-
- const result = await triggers.getType(slug, options);
-
- expect(mockClient.triggersTypes.retrieve).toHaveBeenCalledWith(slug, options);
+ expect(mockClient.triggersTypes.retrieve).toHaveBeenCalledWith(slug);
expect(result).toEqual(mockTriggerType);
});
});
@@ -373,17 +383,7 @@ describe('Triggers', () => {
const result = await triggers.listEnum();
- expect(mockClient.triggersTypes.retrieveEnum).toHaveBeenCalledWith(undefined);
- expect(result).toEqual(mockTriggerEnum);
- });
-
- it('should fetch trigger enums with options', async () => {
- const options = { timeout: 5000 };
- mockClient.triggersTypes.retrieveEnum.mockResolvedValue(mockTriggerEnum);
-
- const result = await triggers.listEnum(options);
-
- expect(mockClient.triggersTypes.retrieveEnum).toHaveBeenCalledWith(options);
+ expect(mockClient.triggersTypes.retrieveEnum).toHaveBeenCalled();
expect(result).toEqual(mockTriggerEnum);
});
});
@@ -393,6 +393,7 @@ describe('Triggers', () => {
beforeEach(() => {
mockCallback.mockClear();
+ vi.mocked(logger.debug).mockClear();
});
it('should throw error if function is not provided', async () => {
@@ -422,14 +423,17 @@ describe('Triggers', () => {
mockClient.apiKey
);
expect(PusherUtils.triggerSubscribe).toHaveBeenCalled();
- expect(logger.debug).toHaveBeenCalledWith('Subscribing to triggers', {});
+ expect(logger.debug).toHaveBeenCalledWith('Subscribing to triggers', `{}`);
});
it('should subscribe to triggers with filters', async () => {
const filters: TriggerSubscribeParams = {
- appName: 'github',
+ toolkits: ['github'],
triggerId: 'trigger-123',
- connectionId: 'conn-123',
+ connectedAccountId: 'conn-123',
+ triggerName: 'github_webhook',
+ triggerData: '{"action":"push"}',
+ userId: 'user-456',
};
await triggers.subscribe(mockCallback, filters);
@@ -440,197 +444,155 @@ describe('Triggers', () => {
mockClient.apiKey
);
expect(PusherUtils.triggerSubscribe).toHaveBeenCalled();
- expect(logger.debug).toHaveBeenCalledWith('Subscribing to triggers', filters);
});
- it('should filter triggers based on appName', async () => {
- const filters: TriggerSubscribeParams = { appName: 'github' };
+ it('should filter triggers based on toolkits case-insensitively', async () => {
+ const filters: TriggerSubscribeParams = { toolkits: ['GITHUB'] };
await triggers.subscribe(mockCallback, filters);
- // Get the filter function that was passed to PusherUtils.triggerSubscribe
const triggerSubscribeCall = vi.mocked(PusherUtils.triggerSubscribe).mock.calls[0];
const filterCallback = triggerSubscribeCall[1];
- // Test data that should match the filter
- const matchingData = { ...mockTriggerData, appName: 'github' };
- const nonMatchingData = { ...mockTriggerData, appName: 'slack' };
+ filterCallback(mockTriggerData);
- filterCallback(matchingData);
- filterCallback(nonMatchingData);
-
- expect(mockCallback).toHaveBeenCalledWith(matchingData);
+ expect(mockCallback).toHaveBeenCalledWith(mockIncomingTriggerPayload);
expect(mockCallback).toHaveBeenCalledTimes(1);
});
- it('should filter triggers based on triggerId', async () => {
- const filters: TriggerSubscribeParams = { triggerId: 'trigger-123' };
+ it('should log debug message when toolkit filter does not match', async () => {
+ const filters: TriggerSubscribeParams = { toolkits: ['slack'] };
await triggers.subscribe(mockCallback, filters);
const triggerSubscribeCall = vi.mocked(PusherUtils.triggerSubscribe).mock.calls[0];
const filterCallback = triggerSubscribeCall[1];
- const matchingData = { ...mockTriggerData };
- const nonMatchingData = {
- ...mockTriggerData,
- metadata: { ...mockTriggerData.metadata, id: 'trigger-456' },
- };
-
- filterCallback(matchingData);
- filterCallback(nonMatchingData);
+ filterCallback(mockTriggerData);
- expect(mockCallback).toHaveBeenCalledWith(matchingData);
- expect(mockCallback).toHaveBeenCalledTimes(1);
+ expect(mockCallback).not.toHaveBeenCalled();
+ expect(logger.debug).toHaveBeenCalledWith(
+ 'Trigger does not match toolkits filter',
+ expect.any(String)
+ );
});
- it('should filter triggers based on connectionId', async () => {
- const filters: TriggerSubscribeParams = { connectionId: 'conn-123' };
+ it('should log debug message when triggerId filter does not match', async () => {
+ const filters: TriggerSubscribeParams = { triggerId: 'trigger-456' };
await triggers.subscribe(mockCallback, filters);
const triggerSubscribeCall = vi.mocked(PusherUtils.triggerSubscribe).mock.calls[0];
const filterCallback = triggerSubscribeCall[1];
- const matchingData = { ...mockTriggerData };
- const nonMatchingData = {
- ...mockTriggerData,
- metadata: { ...mockTriggerData.metadata, connectionId: 'conn-456' },
- };
-
- filterCallback(matchingData);
- filterCallback(nonMatchingData);
+ filterCallback(mockTriggerData);
- expect(mockCallback).toHaveBeenCalledWith(matchingData);
- expect(mockCallback).toHaveBeenCalledTimes(1);
+ expect(mockCallback).not.toHaveBeenCalled();
+ expect(logger.debug).toHaveBeenCalledWith(
+ 'Trigger does not match triggerId filter',
+ expect.any(String)
+ );
});
- it('should filter triggers based on triggerName', async () => {
- const filters: TriggerSubscribeParams = { triggerName: 'github_webhook' };
+ it('should log debug message when connectedAccountId filter does not match', async () => {
+ const filters: TriggerSubscribeParams = { connectedAccountId: 'conn-456' };
await triggers.subscribe(mockCallback, filters);
const triggerSubscribeCall = vi.mocked(PusherUtils.triggerSubscribe).mock.calls[0];
const filterCallback = triggerSubscribeCall[1];
- const matchingData = { ...mockTriggerData };
- const nonMatchingData = {
- ...mockTriggerData,
- metadata: { ...mockTriggerData.metadata, triggerName: 'slack_message' },
- };
-
- filterCallback(matchingData);
- filterCallback(nonMatchingData);
+ filterCallback(mockTriggerData);
- expect(mockCallback).toHaveBeenCalledWith(matchingData);
- expect(mockCallback).toHaveBeenCalledTimes(1);
+ expect(mockCallback).not.toHaveBeenCalled();
+ expect(logger.debug).toHaveBeenCalledWith(
+ 'Trigger does not match connectedAccountId filter',
+ expect.any(String)
+ );
});
- it('should filter triggers based on entityId', async () => {
- const filters: TriggerSubscribeParams = { entityId: 'user-456' };
+ it('should log debug message when triggerName filter does not match', async () => {
+ const filters: TriggerSubscribeParams = { triggerName: 'slack_message' };
await triggers.subscribe(mockCallback, filters);
const triggerSubscribeCall = vi.mocked(PusherUtils.triggerSubscribe).mock.calls[0];
const filterCallback = triggerSubscribeCall[1];
- const matchingData = { ...mockTriggerData };
- const nonMatchingData = {
- ...mockTriggerData,
- metadata: {
- ...mockTriggerData.metadata,
- connection: {
- ...mockTriggerData.metadata.connection,
- clientUniqueUserId: 'user-789',
- },
- },
- };
+ filterCallback(mockTriggerData);
- filterCallback(matchingData);
- filterCallback(nonMatchingData);
-
- expect(mockCallback).toHaveBeenCalledWith(matchingData);
- expect(mockCallback).toHaveBeenCalledTimes(1);
+ expect(mockCallback).not.toHaveBeenCalled();
+ expect(logger.debug).toHaveBeenCalledWith(
+ 'Trigger does not match triggerName filter',
+ expect.any(String)
+ );
});
- it('should filter triggers based on integrationId', async () => {
- const filters: TriggerSubscribeParams = { integrationId: 'github' };
+ it('should log debug message when triggerData filter does not match', async () => {
+ const filters: TriggerSubscribeParams = { triggerData: '{"action":"comment"}' };
await triggers.subscribe(mockCallback, filters);
const triggerSubscribeCall = vi.mocked(PusherUtils.triggerSubscribe).mock.calls[0];
const filterCallback = triggerSubscribeCall[1];
- const matchingData = { ...mockTriggerData };
- const nonMatchingData = {
- ...mockTriggerData,
- metadata: {
- ...mockTriggerData.metadata,
- connection: {
- ...mockTriggerData.metadata.connection,
- integrationId: 'slack',
- },
- },
- };
+ filterCallback(mockTriggerData);
- filterCallback(matchingData);
- filterCallback(nonMatchingData);
-
- expect(mockCallback).toHaveBeenCalledWith(matchingData);
- expect(mockCallback).toHaveBeenCalledTimes(1);
+ expect(mockCallback).not.toHaveBeenCalled();
+ expect(logger.debug).toHaveBeenCalledWith(
+ 'Trigger does not match triggerData filter',
+ expect.any(String)
+ );
});
- it('should apply multiple filters correctly', async () => {
- const filters: TriggerSubscribeParams = {
- appName: 'github',
- triggerId: 'trigger-123',
- connectionId: 'conn-123',
- };
+ it('should log debug message when userId filter does not match', async () => {
+ const filters: TriggerSubscribeParams = { userId: 'user-789' };
await triggers.subscribe(mockCallback, filters);
const triggerSubscribeCall = vi.mocked(PusherUtils.triggerSubscribe).mock.calls[0];
const filterCallback = triggerSubscribeCall[1];
- const matchingData = { ...mockTriggerData, appName: 'github' };
- const nonMatchingDataApp = { ...mockTriggerData, appName: 'slack' };
- const nonMatchingDataTrigger = {
- ...mockTriggerData,
- appName: 'github',
- metadata: { ...mockTriggerData.metadata, id: 'trigger-456' },
- };
+ filterCallback(mockTriggerData);
- filterCallback(matchingData);
- filterCallback(nonMatchingDataApp);
- filterCallback(nonMatchingDataTrigger);
-
- expect(mockCallback).toHaveBeenCalledWith(matchingData);
- expect(mockCallback).toHaveBeenCalledTimes(1);
+ expect(mockCallback).not.toHaveBeenCalled();
+ expect(logger.debug).toHaveBeenCalledWith(
+ 'Trigger does not match userId filter',
+ expect.any(String)
+ );
});
- it('should pass all triggers when no filters are provided', async () => {
- await triggers.subscribe(mockCallback);
+ it('should log debug message when trigger matches all filters', async () => {
+ const filters: TriggerSubscribeParams = {
+ toolkits: ['github'],
+ triggerId: 'trigger-123',
+ connectedAccountId: 'conn-123',
+ triggerName: 'github_webhook',
+ triggerData: '{"action":"push"}',
+ userId: 'user-456',
+ };
+ await triggers.subscribe(mockCallback, filters);
const triggerSubscribeCall = vi.mocked(PusherUtils.triggerSubscribe).mock.calls[0];
const filterCallback = triggerSubscribeCall[1];
- const testData1 = { ...mockTriggerData, appName: 'github' };
- const testData2 = { ...mockTriggerData, appName: 'slack' };
-
- filterCallback(testData1);
- filterCallback(testData2);
+ filterCallback(mockTriggerData);
- expect(mockCallback).toHaveBeenCalledWith(testData1);
- expect(mockCallback).toHaveBeenCalledWith(testData2);
- expect(mockCallback).toHaveBeenCalledTimes(2);
+ expect(mockCallback).toHaveBeenCalledWith(mockIncomingTriggerPayload);
+ expect(mockCallback).toHaveBeenCalledTimes(1);
+ expect(logger.debug).toHaveBeenCalledWith('Trigger matches all filters', expect.any(String));
});
- it('should be case insensitive for filters', async () => {
- const filters: TriggerSubscribeParams = { appName: 'GITHUB' };
+ it('should log debug message when trigger does not match any filters', async () => {
+ const filters: TriggerSubscribeParams = {
+ toolkits: ['slack'],
+ triggerId: 'trigger-456',
+ };
await triggers.subscribe(mockCallback, filters);
const triggerSubscribeCall = vi.mocked(PusherUtils.triggerSubscribe).mock.calls[0];
const filterCallback = triggerSubscribeCall[1];
- const matchingData = { ...mockTriggerData, appName: 'github' };
-
- filterCallback(matchingData);
+ filterCallback(mockTriggerData);
- expect(mockCallback).toHaveBeenCalledWith(matchingData);
- expect(mockCallback).toHaveBeenCalledTimes(1);
+ expect(mockCallback).not.toHaveBeenCalled();
+ expect(logger.debug).toHaveBeenCalledWith(
+ 'Trigger does not match filters',
+ expect.any(String)
+ );
});
});
@@ -642,7 +604,7 @@ describe('Triggers', () => {
expect(PusherUtils.triggerUnsubscribe).toHaveBeenCalledWith('client-123');
});
- it('should throw error if client ID is not found during unsubscribe', async () => {
+ it('should throw error if client ID is not found', async () => {
mockSession.getInfo = vi.fn().mockResolvedValue({ project: null });
await expect(triggers.unsubscribe()).rejects.toThrow('Client ID not found');
@@ -654,7 +616,7 @@ describe('Triggers', () => {
const apiError = new Error('API request failed');
mockClient.triggerInstances.listActive.mockRejectedValue(apiError);
- await expect(triggers.list()).rejects.toThrow('API request failed');
+ await expect(triggers.listActive()).rejects.toThrow('API request failed');
});
it('should handle session retrieval errors', async () => {