Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | import { PusherSubscriptionError } from '../errors/PusherErrors'; |
| 2 | import { CLIENT_PUSHER_KEY } from './constants'; |
| 3 | import logger from './logger'; |
| 4 | |
| 5 | const PUSHER_KEY = CLIENT_PUSHER_KEY || 'ff9f18c208855d77a152'; |
| 6 | const PUSHER_CLUSTER = 'mt1'; |
| 7 | |
| 8 | type Channel = { |
| 9 | subscribe: (channelName: string) => unknown; |
| 10 | unsubscribe: (channelName: string) => unknown; |
| 11 | bind: (event: string, callback: (data: Record<string, unknown>) => void) => unknown; |
| 12 | }; |
| 13 | |
| 14 | type PusherClient = { |
| 15 | subscribe: (channelName: string) => Channel; |
| 16 | unsubscribe: (channelName: string) => unknown; |
| 17 | bind: (event: string, callback: (data: Record<string, unknown>) => void) => unknown; |
| 18 | connection: { |
| 19 | bind: (event: string, callback: (error: Error) => void) => void; |
| 20 | socket_id?: string; |
| 21 | }; |
| 22 | }; |
| 23 | |
| 24 | type TChunkedTriggerData = { |
| 25 | id: string; |
| 26 | index: number; |
| 27 | chunk: string; |
| 28 | final: boolean; |
| 29 | }; |
| 30 | |
| 31 | export type TriggerData = { |
| 32 | appName: string; |
| 33 | clientId: number; |
| 34 | payload: Record<string, unknown>; |
| 35 | originalPayload: Record<string, unknown>; |
| 36 | metadata: { |
| 37 | id: string; |
| 38 | connectionId: string; |
| 39 | triggerName: string; |
| 40 | triggerData: string; |
| 41 | triggerConfig: Record<string, unknown>; |
| 42 | connection: { |
| 43 | id: string; |
| 44 | integrationId: string; |
| 45 | clientUniqueUserId: string; |
| 46 | status: string; |
| 47 | connectedAccountNanoId: string; |
| 48 | authConfigNanoId: string; |
| 49 | }; |
| 50 | }; |
| 51 | }; |
| 52 | |
| 53 | export class PusherUtils { |
| 54 | static pusherClient: PusherClient; |
| 55 | |
| 56 | static async getPusherClient(baseURL: string, apiKey: string): Promise<PusherClient> { |
| 57 | try { |
| 58 | if (!PusherUtils.pusherClient) { |
| 59 | const { default: PusherClient } = await import('pusher-js'); |
| 60 | const authEndpoint = `${baseURL}/api/v3/internal/sdk/realtime/auth`; |
| 61 | PusherUtils.pusherClient = new PusherClient(PUSHER_KEY, { |
| 62 | cluster: PUSHER_CLUSTER, |
| 63 | channelAuthorization: { |
| 64 | // `transport` and `endpoint` are required by pusher-js's types but are |
| 65 | // unused at runtime: `customHandler` fully owns the auth request below. |
| 66 | transport: 'ajax', |
| 67 | endpoint: authEndpoint, |
| 68 | customHandler: (params, callback) => { |
| 69 | fetch(authEndpoint, { |
| 70 | method: 'POST', |
| 71 | headers: { |
| 72 | 'x-api-key': apiKey, |
| 73 | 'Content-Type': 'application/json', |
| 74 | }, |
| 75 | body: JSON.stringify({ |
| 76 | socket_id: params.socketId, |
| 77 | channel_name: params.channelName, |
| 78 | }), |
| 79 | }) |
| 80 | .then(async response => { |
| 81 | const data = await response.text(); |
| 82 | logger.debug('Pusher auth response:', data); |
| 83 | try { |
| 84 | callback(null, JSON.parse(data)); |
| 85 | } catch (e) { |
| 86 | logger.error('Failed to parse auth response:', e); |
| 87 | callback(new Error('Invalid auth response format'), null); |
| 88 | } |
| 89 | }) |
| 90 | .catch((error: unknown) => { |
| 91 | logger.error('Pusher auth request failed:', error); |
| 92 | callback(error instanceof Error ? error : new Error(String(error)), null); |
| 93 | }); |
| 94 | }, |
| 95 | }, |
| 96 | }); |
| 97 | |
| 98 | // Add connection error handling |
| 99 | PusherUtils.pusherClient.connection.bind('error', (err: Error) => { |
| 100 | logger.error('Pusher connection error:', err); |
| 101 | throw new Error(`Pusher connection error: ${err.message}`); |
| 102 | }); |
| 103 | } |
| 104 | return PusherUtils.pusherClient; |
| 105 | } catch (error: unknown) { |
| 106 | const errorMessage = error instanceof Error ? error.message : String(error); |
| 107 | logger.error('Failed to initialize Pusher client:', error); |
| 108 | throw new Error(`Failed to initialize Pusher client: ${errorMessage}`); |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | /** |
| 113 | * Subscribes to a Pusher channel and binds an event to a callback function. |
| 114 | * @param {string} channelName - The name of the channel to subscribe to. |
| 115 | * @param {string} event - The event to bind to the channel. |
| 116 | * @param {(data: Record<string, unknown>) => void} fn - The callback function to execute when the event is triggered. |
| 117 | * @returns {PusherClient} The Pusher client instance. |
| 118 | */ |
| 119 | static async subscribe( |
| 120 | channelName: string, |
| 121 | event: string, |
| 122 | fn: (data: Record<string, unknown>) => void |
| 123 | ): Promise<void> { |
| 124 | try { |
| 125 | await PusherUtils.pusherClient.subscribe(channelName).bind(event, fn); |
| 126 | } catch (error) { |
| 127 | logger.error(`Error subscribing to ${channelName} with event ${event}: ${error}`); |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | /** |
| 132 | * Unsubscribes from a Pusher channel. |
| 133 | * @param {string} channelName - The name of the channel to unsubscribe from. |
| 134 | * @returns {void} |
| 135 | */ |
| 136 | static async unsubscribe(channelName: string): Promise<void> { |
| 137 | PusherUtils.pusherClient.unsubscribe(channelName); |
| 138 | } |
| 139 | |
| 140 | /** |
| 141 | * Binds an event to a channel with support for chunked messages. |
| 142 | * @param {PusherClient} channel - The Pusher channel to bind the event to. |
| 143 | * @param {string} event - The event to bind to the channel. |
| 144 | * @param {(data: unknown) => void} callback - The callback function to execute when the event is triggered. |
| 145 | */ |
| 146 | private static bindWithChunking( |
| 147 | channel: PusherClient, |
| 148 | event: string, |
| 149 | callback: (data: Record<string, unknown>) => void |
| 150 | ): void { |
| 151 | try { |
| 152 | // Wrap the callback to handle errors |
| 153 | const safeCallback = (data: Record<string, unknown>) => { |
| 154 | try { |
| 155 | callback(data); |
| 156 | } catch (error: unknown) { |
| 157 | const errorMessage = error instanceof Error ? error.message : String(error); |
| 158 | logger.error('Error in chunked event callback:', errorMessage); |
| 159 | // Don't throw here to prevent breaking the subscription |
| 160 | } |
| 161 | }; |
| 162 | |
| 163 | channel.bind(event, safeCallback); |
| 164 | |
| 165 | // Now the chunked variation. Allows arbitrarily long messages. |
| 166 | const events: { |
| 167 | [key: string]: { chunks: string[]; receivedFinal: boolean }; |
| 168 | } = {}; |
| 169 | |
| 170 | channel.bind('chunked-' + event, data => { |
| 171 | try { |
| 172 | const typedData = data as TChunkedTriggerData; |
| 173 | |
| 174 | // Validate chunked data |
| 175 | if ( |
| 176 | !typedData || |
| 177 | typeof typedData.id !== 'string' || |
| 178 | typeof typedData.index !== 'number' |
| 179 | ) { |
| 180 | throw new Error('Invalid chunked trigger data format'); |
| 181 | } |
| 182 | |
| 183 | if (!events.hasOwnProperty(typedData.id)) { |
| 184 | events[typedData.id] = { chunks: [], receivedFinal: false }; |
| 185 | } |
| 186 | |
| 187 | const ev = events[typedData.id]; |
| 188 | ev.chunks[typedData.index] = typedData.chunk; |
| 189 | |
| 190 | if (typedData.final) ev.receivedFinal = true; |
| 191 | |
| 192 | if (ev.receivedFinal && ev.chunks.length === Object.keys(ev.chunks).length) { |
| 193 | try { |
| 194 | const parsedData = JSON.parse(ev.chunks.join('')); |
| 195 | safeCallback(parsedData); |
| 196 | } catch (parseError: unknown) { |
| 197 | const errorMessage = |
| 198 | parseError instanceof Error ? parseError.message : String(parseError); |
| 199 | logger.error('Failed to parse chunked data:', errorMessage); |
| 200 | } finally { |
| 201 | delete events[typedData.id]; |
| 202 | } |
| 203 | } |
| 204 | } catch (error: unknown) { |
| 205 | const errorMessage = error instanceof Error ? error.message : String(error); |
| 206 | logger.error('Error processing chunked trigger data:', errorMessage); |
| 207 | // Clean up the event data to prevent memory leaks |
| 208 | if (data && typeof data === 'object' && 'id' in data) { |
| 209 | delete events[data.id as string]; |
| 210 | } |
| 211 | } |
| 212 | }); |
| 213 | } catch (error: unknown) { |
| 214 | const errorMessage = error instanceof Error ? error.message : String(error); |
| 215 | logger.error('Failed to bind chunked events:', error); |
| 216 | throw new Error(`Failed to bind chunked events: ${errorMessage}`); |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | /** |
| 221 | * Subscribes to a trigger channel for a client and handles chunked data. |
| 222 | * @param {string} clientId - The unique identifier for the client subscribing to the events. |
| 223 | * @param {(data: TriggerData) => void} fn - The callback function to execute when trigger data is received. |
| 224 | * |
| 225 | * @example |
| 226 | * ```ts |
| 227 | * composio.trigger.subscribe((data) => { |
| 228 | * console.log(data); |
| 229 | * }); |
| 230 | * ``` |
| 231 | */ |
| 232 | static triggerSubscribe(clientId: string, fn: (data: TriggerData) => void): void { |
| 233 | try { |
| 234 | if (!PusherUtils.pusherClient) { |
| 235 | throw new Error('Pusher client not initialized'); |
| 236 | } |
| 237 | |
| 238 | const channel = PusherUtils.pusherClient.subscribe(`private-${clientId}_triggers`); |
| 239 | |
| 240 | // Add subscription error handling |
| 241 | channel.bind('pusher:subscription_error', (data: Record<string, unknown>) => { |
| 242 | const error = data.error ? String(data.error) : 'Unknown subscription error'; |
| 243 | throw new PusherSubscriptionError(`Trigger subscription error`, { |
| 244 | cause: error, |
| 245 | }); |
| 246 | }); |
| 247 | |
| 248 | // Wrap the callback to handle errors |
| 249 | const safeCallback = (data: TriggerData) => { |
| 250 | try { |
| 251 | fn(data); |
| 252 | } catch (error: unknown) { |
| 253 | const errorMessage = error instanceof Error ? error.message : String(error); |
| 254 | logger.error('Error in trigger callback:', errorMessage); |
| 255 | // Don't throw here to prevent breaking the subscription |
| 256 | } |
| 257 | }; |
| 258 | |
| 259 | PusherUtils.bindWithChunking( |
| 260 | channel as PusherClient, |
| 261 | 'trigger_to_client', |
| 262 | safeCallback as (data: unknown) => void |
| 263 | ); |
| 264 | |
| 265 | logger.info(`Subscribed to triggers. You should start receiving events now.`); |
| 266 | } catch (error: unknown) { |
| 267 | const errorMessage = error instanceof Error ? error.message : String(error); |
| 268 | logger.error('Failed to subscribe to triggers:', error); |
| 269 | throw new Error(`Failed to subscribe to triggers: ${errorMessage}`); |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | static triggerUnsubscribe(clientId: string): void { |
| 274 | try { |
| 275 | if (!PusherUtils.pusherClient) { |
| 276 | throw new Error('Pusher client not initialized'); |
| 277 | } |
| 278 | PusherUtils.pusherClient.unsubscribe(`private-${clientId}_triggers`); |
| 279 | logger.info('Successfully unsubscribed from triggers'); |
| 280 | } catch (error: unknown) { |
| 281 | const errorMessage = error instanceof Error ? error.message : String(error); |
| 282 | logger.error('Failed to unsubscribe from triggers:', error); |
| 283 | throw new Error(`Failed to unsubscribe from triggers: ${errorMessage}`); |
| 284 | } |
| 285 | } |
| 286 | } |