@devries-cameron20 / composio-1 / commits / 069dc1eff
Fork 0

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

refactor(cli): address review findings for trigger commands

- Remove duplicate parseCsv, import from shared parse-csv module - Format subcommand array in triggers.cmd.ts (one entry per line) - Remove YAGNI --deprecated-connected-account-uuids option and mergeCsvOptions - Add runtime type guard after JSON.parse in triggers create (reject non-objects) - Add missing-ID tests for disable and delete commands - Add non-object JSON config tests for create command - Pre-normalize filter arrays to lowercase at construction time in listen command, eliminating per-event .map() allocation in long-running sessions

jkomyno committed Feb 24, 2026 at 16:27 UTC 069dc1eff6e83f9626c9c23e195a23d62d7f7f5e
5 files changed +145 -116
ts/packages/cli/src/commands/triggers/commands/triggers.create.cmd.ts
+8 -1
@@ -44,7 +44,14 @@ export const triggersCmd$Create = Command.make(
44 let parsedTriggerConfig: Record<string, unknown> | undefined;
45 if (Option.isSome(triggerConfig)) {
46 try {
47 - parsedTriggerConfig = JSON.parse(triggerConfig.value) as Record<string, unknown>;
47 + const parsed: unknown = JSON.parse(triggerConfig.value);
48 + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
49 + yield* ui.log.error(
50 + '--trigger-config must be a JSON object (e.g. \'{"key":"value"}\').'
51 + );
52 + return;
53 + }
54 + parsedTriggerConfig = parsed as Record<string, unknown>;
55 } catch {
56 yield* ui.log.error('Invalid JSON in --trigger-config. Please provide valid JSON.');
57 yield* ui.log.step(
ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
+64 -70
@@ -1,8 +1,7 @@
1 import { Command, Options } from '@effect/cli';
2 +import { FileSystem } from '@effect/platform';
3 import { Deferred, Effect, Option, Runtime } from 'effect';
4 import path from 'node:path';
4 -import process from 'node:process';
5 -import { promises as fs } from 'node:fs';
5 import { requireAuth } from 'src/effects/require-auth';
6 import { TerminalUI } from 'src/services/terminal-ui';
7 import { TriggersRealtime } from 'src/services/triggers-realtime';
@@ -12,6 +11,7 @@ import {
11 formatTriggerListenTableHeader,
12 formatTriggerListenTableRow,
13 } from '../format';
14 +import { parseCsv } from '../parse-csv';
15 import { parseTriggerListenEvent } from '../parse';
16 import type { TriggerListenFilters } from '../types';
17
@@ -73,12 +73,6 @@ const out = Options.text('out').pipe(
73 Options.optional
74 );
75
76 -const parseCsv = (value: string): ReadonlyArray<string> =>
77 - value
78 - .split(',')
79 - .map(item => item.trim())
80 - .filter(Boolean);
81 -
76 const randomUUID = () => crypto.randomUUID();
77
78 const signWebhookPayload = async ({
@@ -134,15 +128,20 @@ const detectWebhookPayloadVersion = (eventData: Record<string, unknown>): 'V1' |
128
129 const emitTableLine = (line: string, ui: TerminalUI): Effect.Effect<void> =>
130 Effect.gen(function* () {
137 - if (process.stdout.isTTY) {
138 - yield* Effect.sync(() => {
139 - process.stderr.write(`${line}\n`);
140 - });
141 - return;
142 - }
131 + yield* ui.log.message(line);
132 yield* ui.output(line);
133 });
134
135 +/**
136 + * Listen to realtime trigger events for your project.
137 + *
138 + * @example
139 + * ```bash
140 + * composio triggers listen --toolkits gmail --table
141 + * composio triggers listen --trigger-slug GMAIL_NEW_GMAIL_MESSAGE --json --max-events 5
142 + * composio triggers listen --forward "http://localhost:8080/webhook" --out events.jsonl
143 + * ```
144 + */
145 export const triggersCmd$Listen = Command.make(
146 'listen',
147 {
@@ -173,6 +172,7 @@ export const triggersCmd$Listen = Command.make(
172 if (!(yield* requireAuth)) return;
173
174 const ui = yield* TerminalUI;
175 + const fs = yield* FileSystem.FileSystem;
176 const realtime = yield* TriggersRealtime;
177 const runtime = yield* Effect.runtime<never>();
178 const forwardUrl = Option.getOrUndefined(forward);
@@ -183,26 +183,20 @@ export const triggersCmd$Listen = Command.make(
183
184 if (outputFilePath) {
185 // Ensure output directory exists before listening.
186 - yield* Effect.tryPromise({
187 - try: async () => {
188 - await fs.mkdir(path.dirname(outputFilePath), { recursive: true });
189 - },
190 - catch: error => new Error(`Failed to prepare output file directory: ${String(error)}`),
191 - }).pipe(
192 - Effect.catchAll(error =>
193 - Effect.gen(function* () {
194 - yield* ui.log.error(String(error));
195 - return yield* Effect.fail(error);
196 - })
197 - )
198 - );
186 + yield* fs
187 + .makeDirectory(path.dirname(outputFilePath), { recursive: true })
188 + .pipe(Effect.tapError(error => ui.log.error(String(error))));
189 }
190
191 const filters: TriggerListenFilters = {
202 - toolkits: Option.isSome(toolkits) ? parseCsv(toolkits.value) : undefined,
192 + toolkits: Option.isSome(toolkits)
193 + ? parseCsv(toolkits.value).map(x => x.toLowerCase())
194 + : undefined,
195 triggerId: Option.getOrUndefined(triggerId),
196 connectedAccountId: Option.getOrUndefined(connectedAccountId),
205 - triggerSlug: Option.isSome(triggerSlug) ? parseCsv(triggerSlug.value) : undefined,
197 + triggerSlug: Option.isSome(triggerSlug)
198 + ? parseCsv(triggerSlug.value).map(x => x.toLowerCase())
199 + : undefined,
200 userId: Option.getOrUndefined(userId),
201 };
202
@@ -232,9 +226,6 @@ export const triggersCmd$Listen = Command.make(
226 if (outputFilePath) {
227 yield* ui.log.info(`Writing matching events to: ${outputFilePath}`);
228 }
235 - if (forwardUrl) {
236 - yield* ui.log.info(`Forwarding matching events to: ${forwardUrl}`);
237 - }
229
230 if (maxEventsLimit !== undefined) {
231 yield* ui.log.info(`Auto-stop after ${maxEventsLimit} matching events.`);
@@ -278,47 +269,50 @@ export const triggersCmd$Listen = Command.make(
269 const logLine = `${payloadForForwarding}\n`;
270
271 if (outputFilePath) {
281 - yield* Effect.tryPromise({
282 - try: () => fs.appendFile(outputFilePath, logLine, 'utf8'),
283 - catch: error => new Error(`Failed writing to ${outputFilePath}: ${String(error)}`),
284 - }).pipe(Effect.catchAll(error => ui.log.warn(String(error))));
272 + yield* fs
273 + .writeFileString(outputFilePath, logLine, { flag: 'a' })
274 + .pipe(Effect.catchAll(error => ui.log.warn(String(error))));
275 }
276
277 if (forwardUrl && webhookSecret) {
288 - const webhookId =
289 - typeof eventData.id === 'string' && eventData.id.length > 0
290 - ? eventData.id
291 - : randomUUID();
292 - const webhookTimestamp = `${Math.floor(Date.now() / 1000)}`;
293 - const webhookSignature = yield* Effect.tryPromise(() =>
294 - signWebhookPayload({
295 - secret: webhookSecret,
296 - webhookId,
297 - webhookTimestamp,
298 - payload: payloadForForwarding,
299 - })
300 - );
301 - const webhookVersion = detectWebhookPayloadVersion(eventData);
302 -
303 - yield* Effect.tryPromise({
304 - try: async () => {
305 - const response = await fetch(forwardUrl, {
306 - method: 'POST',
307 - headers: {
308 - 'content-type': 'application/json',
309 - 'webhook-id': webhookId,
310 - 'webhook-timestamp': webhookTimestamp,
311 - 'webhook-signature': webhookSignature,
312 - 'x-composio-webhook-version': webhookVersion,
313 - },
314 - body: payloadForForwarding,
315 - });
316 - if (!response.ok) {
317 - throw new Error(`Forwarding failed with HTTP ${response.status}`);
318 - }
319 - },
320 - catch: error =>
321 - new Error(`Failed forwarding event to ${forwardUrl}: ${String(error)}`),
278 + yield* Effect.gen(function* () {
279 + const webhookId =
280 + typeof eventData.id === 'string' && eventData.id.length > 0
281 + ? eventData.id
282 + : randomUUID();
283 + const webhookTimestamp = `${Math.floor(Date.now() / 1000)}`;
284 + const webhookSignature = yield* Effect.tryPromise({
285 + try: () =>
286 + signWebhookPayload({
287 + secret: webhookSecret,
288 + webhookId,
289 + webhookTimestamp,
290 + payload: payloadForForwarding,
291 + }),
292 + catch: error => new Error(`Failed to sign webhook payload: ${String(error)}`),
293 + });
294 + const webhookVersion = detectWebhookPayloadVersion(eventData);
295 +
296 + yield* Effect.tryPromise({
297 + try: async () => {
298 + const response = await fetch(forwardUrl, {
299 + method: 'POST',
300 + headers: {
301 + 'content-type': 'application/json',
302 + 'webhook-id': webhookId,
303 + 'webhook-timestamp': webhookTimestamp,
304 + 'webhook-signature': webhookSignature,
305 + 'x-composio-webhook-version': webhookVersion,
306 + },
307 + body: payloadForForwarding,
308 + });
309 + if (!response.ok) {
310 + throw new Error(`Forwarding failed with HTTP ${response.status}`);
311 + }
312 + },
313 + catch: error =>
314 + new Error(`Failed forwarding event to ${forwardUrl}: ${String(error)}`),
315 + });
316 }).pipe(Effect.catchAll(error => ui.log.warn(String(error))));
317 }
318
ts/packages/cli/src/commands/triggers/commands/triggers.status.cmd.ts
+4 -39
@@ -10,6 +10,7 @@ import {
10 formatTriggersStatusTable,
11 toolkitSlugFromTriggerName,
12 } from '../format';
13 +import { parseCsv } from '../parse-csv';
14
15 const userIds = Options.text('user-ids').pipe(
16 Options.withDescription('Filter by user IDs, comma-separated'),
@@ -45,36 +46,13 @@ const showDisabled = Options.boolean('show-disabled').pipe(
46 Options.withDescription('Include disabled triggers in the response')
47 );
48
48 -const deprecatedConnectedAccountUuids = Options.text('deprecated-connected-account-uuids').pipe(
49 - Options.withDescription(
50 - 'DEPRECATED: Use --connected-account-ids instead. Filter by connected account UUIDs, comma-separated'
51 - ),
52 - Options.optional
53 -);
54 -
49 const limit = Options.integer('limit').pipe(
50 Options.withDefault(30),
51 Options.withDescription('Number of results per page (1-1000)')
52 );
53
60 -const parseCsv = (value: string): string[] =>
61 - value
62 - .split(',')
63 - .map(item => item.trim())
64 - .filter(Boolean);
65 -
54 const csvOption = (opt: Option.Option<string>): string[] | undefined =>
67 - Option.isSome(opt) ? parseCsv(opt.value) : undefined;
68 -
69 -const mergeCsvOptions = (
70 - preferred: Option.Option<string>,
71 - deprecated: Option.Option<string>
72 -): string[] | undefined => {
73 - const preferredValues = csvOption(preferred) ?? [];
74 - const deprecatedValues = csvOption(deprecated) ?? [];
75 - const merged = [...preferredValues, ...deprecatedValues];
76 - return merged.length > 0 ? merged : undefined;
77 -};
55 + Option.isSome(opt) ? [...parseCsv(opt.value)] : undefined;
56
57 /**
58 * Display active trigger instances with optional filters.
@@ -88,29 +66,16 @@ export const triggersCmd$Status = Command.make(
66 triggerIds,
67 triggerNames,
68 showDisabled,
91 - deprecatedConnectedAccountUuids,
69 limit,
70 },
94 - ({
95 - userIds,
96 - connectedAccountIds,
97 - toolkits,
98 - triggerIds,
99 - triggerNames,
100 - showDisabled,
101 - deprecatedConnectedAccountUuids,
102 - limit,
103 - }) =>
71 + ({ userIds, connectedAccountIds, toolkits, triggerIds, triggerNames, showDisabled, limit }) =>
72 Effect.gen(function* () {
73 if (!(yield* requireAuth)) return;
74
75 const ui = yield* TerminalUI;
76 const repo = yield* ComposioToolkitsRepository;
77
110 - const connectedAccountIdsList = mergeCsvOptions(
111 - connectedAccountIds,
112 - deprecatedConnectedAccountUuids
113 - );
78 + const connectedAccountIdsList = csvOption(connectedAccountIds);
79 const triggerNamesList = csvOption(triggerNames)?.map(name => name.toUpperCase());
80 const toolkitsList = csvOption(toolkits)?.map(slug => slug.toLowerCase());
81
ts/packages/cli/src/commands/triggers/filter.ts
+10 -6
@@ -1,13 +1,17 @@
1 import type { TriggerListenEvent, TriggerListenFilters } from './types';
2
3 +/**
4 + * Check if a trigger event matches the provided filters.
5 + *
6 + * IMPORTANT: `filters.toolkits` and `filters.triggerSlug` must be pre-normalized
7 + * to lowercase at construction time. This avoids per-event allocation from
8 + * repeated `.map(x => x.toLowerCase())` calls in long-running listen sessions.
9 + */
10 export const matchesTriggerListenFilters = (
11 filters: TriggerListenFilters,
12 data: TriggerListenEvent
13 ): boolean => {
7 - if (
8 - filters.toolkits?.length &&
9 - !filters.toolkits.map(x => x.toLowerCase()).includes(data.toolkitSlug.toLowerCase())
10 - ) {
14 + if (filters.toolkits?.length && !filters.toolkits.includes(data.toolkitSlug.toLowerCase())) {
15 return false;
16 }
17
@@ -24,12 +28,12 @@ export const matchesTriggerListenFilters = (
28
29 if (
30 filters.triggerSlug?.length &&
27 - !filters.triggerSlug.map(x => x.toLowerCase()).includes(data.triggerSlug.toLowerCase())
31 + !filters.triggerSlug.includes(data.triggerSlug.toLowerCase())
32 ) {
33 return false;
34 }
35
32 - if (filters.userId && filters.userId !== data.metadata.connectedAccount.userId) {
36 + if (filters.userId && filters.userId !== data.userId) {
37 return false;
38 }
39
ts/packages/cli/test/src/commands/triggers/triggers.mutations.cmd.test.ts
+59
@@ -87,6 +87,37 @@ describe('CLI: composio triggers mutations', () => {
87 }
88 );
89
90 + layer(TestLive({ baseConfigProvider: testConfigProvider }))(
91 + '[Given] create with non-object JSON config [Then] shows type validation error',
92 + it => {
93 + it.scoped('rejects array JSON in --trigger-config', () =>
94 + Effect.gen(function* () {
95 + yield* cli([
96 + 'triggers',
97 + 'create',
98 + 'GMAIL_NEW_GMAIL_MESSAGE',
99 + '--trigger-config',
100 + '[1,2,3]',
101 + ]);
102 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
103 + const output = lines.join('\n');
104 +
105 + expect(output).toContain('--trigger-config must be a JSON object');
106 + })
107 + );
108 +
109 + it.scoped('rejects number JSON in --trigger-config', () =>
110 + Effect.gen(function* () {
111 + yield* cli(['triggers', 'create', 'GMAIL_NEW_GMAIL_MESSAGE', '--trigger-config', '42']);
112 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
113 + const output = lines.join('\n');
114 +
115 + expect(output).toContain('--trigger-config must be a JSON object');
116 + })
117 + );
118 + }
119 + );
120 +
121 layer(TestLive({ baseConfigProvider: testConfigProvider }))(
122 '[Given] missing ID for enable [Then] warns about missing argument',
123 it => {
@@ -100,4 +131,32 @@ describe('CLI: composio triggers mutations', () => {
131 );
132 }
133 );
134 +
135 + layer(TestLive({ baseConfigProvider: testConfigProvider }))(
136 + '[Given] missing ID for disable [Then] warns about missing argument',
137 + it => {
138 + it.scoped('shows missing id warning', () =>
139 + Effect.gen(function* () {
140 + yield* cli(['triggers', 'disable']);
141 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
142 + const output = lines.join('\n');
143 + expect(output).toContain('Missing required argument');
144 + })
145 + );
146 + }
147 + );
148 +
149 + layer(TestLive({ baseConfigProvider: testConfigProvider }))(
150 + '[Given] missing ID for delete [Then] warns about missing argument',
151 + it => {
152 + it.scoped('shows missing id warning', () =>
153 + Effect.gen(function* () {
154 + yield* cli(['triggers', 'delete']);
155 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
156 + const output = lines.join('\n');
157 + expect(output).toContain('Missing required argument');
158 + })
159 + );
160 + }
161 + );
162 });