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

next
ts 238 lines 9.23 KB
Raw
1 import { APIConnectionError, type RequestOptions } from '@composio/client/effect';
2 import type { SessionRetrieveInfoResponse } from '@composio/client/resources/auth';
3 import type { PermissionsResolveResponse } from '@composio/client/resources/_internal/consumer';
4 import type { ConsumerRetrieveConfigResponse } from '@composio/client/resources/_internal/org/consumer';
5 import { Effect, Option } from 'effect';
6 import type { OrganizationSummary, OrgProject } from 'src/services/composio-account';
7 import { TIMESTAMP } from '../models/account';
8
9 /**
10 * The credentials and scope one mock-client request carries: the parameters
11 * the client was obtained with, and the org or project an unscoped client
12 * names on the request itself.
13 */
14 export interface MockRequestScope {
15 readonly userApiKey?: string;
16 /** The project key the client authenticates with, in place of a user key. */
17 readonly apiKey?: string;
18 readonly orgId?: string;
19 readonly projectId?: string;
20 }
21
22 /**
23 * One call to an account, session-info, or consumer endpoint of the mock client.
24 */
25 export interface MockAccountRequest {
26 readonly operation:
27 | 'org.list'
28 | 'org.project.list'
29 | 'org.consumer.project.resolve'
30 | 'org.consumer.listConnectedToolkits'
31 | 'auth.session.retrieveInfo'
32 | 'tools.getLatestVersion'
33 | 'org.project.createApiKey'
34 | 'org.consumer.config'
35 | 'consumer.permissions.resolve';
36 readonly scope: MockRequestScope;
37 readonly params?: unknown;
38 readonly options?: RequestOptions;
39 }
40
41 /**
42 * Account, session-info, and consumer data served by the mock client's
43 * `org.*` and `auth.session.retrieveInfo` resources and its `get`/`post`
44 * escape hatch. An endpoint without data rejects with a connection error,
45 * as an unreachable backend would; consumer project resolution always
46 * answers, echoing the requested org.
47 */
48 export interface AccountTestData {
49 /** A function answers per scope; whatever it throws becomes the call's failure. */
50 sessionInfo?:
51 SessionRetrieveInfoResponse | ((scope: MockRequestScope) => SessionRetrieveInfoResponse);
52 organizations?: ReadonlyArray<OrganizationSummary>;
53 projects?: ReadonlyArray<OrgProject>;
54 /**
55 * The `consumer_user_id` the consumer project resolve endpoint answers with. Omitted (the
56 * default) serves `consumer-user-<orgId>`; `''` serves an empty id (the backend's
57 * "logged in, but no consumer user" shape); `null` serves no field at all, which only a
58 * mock can answer — the real response schema requires the string.
59 */
60 consumerUserId?: string | null;
61 connectedToolkits?: ReadonlyArray<string>;
62 latestToolVersion?: { readonly tool_slug: string; readonly version: string };
63 projectApiKey?: string;
64 consumerConfig?: ConsumerRetrieveConfigResponse;
65 consumerPermissions?: PermissionsResolveResponse;
66 onRequest?: (request: MockAccountRequest) => void;
67 }
68
69 const noTestData = (operation: MockAccountRequest['operation']) =>
70 new APIConnectionError({
71 message: `No test data for ${operation}`,
72 method: 'GET',
73 url: 'https://mock.invalid',
74 reason: 'TransportError',
75 description: `No test data for ${operation}`,
76 });
77
78 /**
79 * `value`, or the connection error an endpoint without test data rejects with.
80 */
81 const withTestData = <A>(value: A | undefined, operation: MockAccountRequest['operation']) =>
82 Effect.fromOption(Option.fromUndefinedOr(value), () => noTestData(operation));
83
84 const LATEST_TOOL_VERSION_PATH = /^\/api\/v3\/tools\/[^/]+\/get_latest_version$/;
85 const CREATE_PROJECT_API_KEY_PATH = /^\/api\/v3\/org\/project\/[^/]+\/api_keys\/create$/;
86
87 // The credential is the client's own; an unscoped client may still name the
88 // org or project on one request.
89 const scopeOf = (base: MockRequestScope, options?: RequestOptions): MockRequestScope => {
90 // The CLI only ever passes plain header records.
91 const headers = (options?.headers ?? {}) as Record<string, string | null | undefined>;
92 return {
93 userApiKey: base.userApiKey,
94 apiKey: base.apiKey,
95 orgId: headers['x-org-id'] ?? base.orgId,
96 projectId: headers['x-project-id'] ?? base.projectId,
97 };
98 };
99
100 /**
101 * The account, session-info, and consumer resources of a mock client obtained
102 * with `base`, answering from `accountData` and recording each call through
103 * `accountData.onRequest`. Served per client scope, so a handler sees the
104 * credentials and org or project the real client would have placed in its
105 * default headers.
106 */
107 export const mockAccountResources = (accountData: AccountTestData, base: MockRequestScope) => {
108 const record = (
109 operation: MockAccountRequest['operation'],
110 options: RequestOptions | undefined,
111 params?: unknown
112 ): MockRequestScope => {
113 const scope = scopeOf(base, options);
114 accountData.onRequest?.({ operation, scope, params, options });
115 return scope;
116 };
117 const timestamps = {
118 created_at: TIMESTAMP,
119 updated_at: TIMESTAMP,
120 };
121
122 return {
123 org: {
124 list: (query?: { limit?: number } | null, options?: RequestOptions) => {
125 record('org.list', options, query);
126 return withTestData(accountData.organizations, 'org.list').pipe(
127 Effect.map(organizations => organizations.map(org => ({ ...org, ...timestamps }))),
128 Effect.map(organizations => ({
129 organizations,
130 next_cursor: null,
131 total_pages: 1,
132 current_page: 1,
133 total_items: organizations.length,
134 }))
135 );
136 },
137 project: {
138 list: (
139 query?: { limit?: number; list_all_org_projects?: boolean | null } | null,
140 options?: RequestOptions
141 ) => {
142 record('org.project.list', options, query);
143 return withTestData(accountData.projects, 'org.project.list').pipe(
144 Effect.map(projects => ({
145 data: [...projects],
146 next_cursor: null,
147 total_pages: 1,
148 current_page: 1,
149 total_items: projects.length,
150 }))
151 );
152 },
153 },
154 },
155 _internal: {
156 org: {
157 consumer: {
158 project: {
159 resolve: (
160 params: { 'x-user-api-key': string; 'x-org-id': string },
161 options?: RequestOptions
162 ) => {
163 record('org.consumer.project.resolve', options, params);
164 const orgId = params['x-org-id'];
165 return Effect.succeed({
166 project_id: 'consumer_project_id_test',
167 project_nano_id: 'consumer_project_test',
168 project_name: 'Consumer Project',
169 org_id: orgId,
170 project_type: 'CONSUMER' as const,
171 config: { consumer_experience_enabled: true, enhanced_controls: false },
172 consumer_user_id:
173 accountData.consumerUserId === null
174 ? undefined
175 : (accountData.consumerUserId ?? `consumer-user-${orgId}`),
176 });
177 },
178 },
179 listConnectedToolkits: (
180 params: { user_id: string; 'x-user-api-key': string; 'x-org-id': string },
181 options?: RequestOptions
182 ) => {
183 record('org.consumer.listConnectedToolkits', options, params);
184 return withTestData(
185 accountData.connectedToolkits,
186 'org.consumer.listConnectedToolkits'
187 ).pipe(Effect.map(toolkits => ({ toolkits: [...toolkits] })));
188 },
189 retrieveConfig: (options?: RequestOptions) => {
190 record('org.consumer.config', options);
191 return withTestData(accountData.consumerConfig, 'org.consumer.config');
192 },
193 },
194 },
195 consumer: {
196 permissions: {
197 resolve: (body?: unknown, options?: RequestOptions) => {
198 record('consumer.permissions.resolve', options, body);
199 return withTestData(accountData.consumerPermissions, 'consumer.permissions.resolve');
200 },
201 },
202 },
203 },
204 auth: {
205 session: {
206 retrieveInfo: (options?: RequestOptions) => {
207 const scope = record('auth.session.retrieveInfo', options);
208 return withTestData(accountData.sessionInfo, 'auth.session.retrieveInfo').pipe(
209 // A test fails the call by throwing from its callback.
210 Effect.flatMap(sessionInfo =>
211 Effect.try({
212 try: () => (typeof sessionInfo === 'function' ? sessionInfo(scope) : sessionInfo),
213 catch: cause => cause,
214 })
215 )
216 );
217 },
218 },
219 },
220 get: (path: string, options?: RequestOptions) => {
221 if (!LATEST_TOOL_VERSION_PATH.test(path)) {
222 return Effect.fail(new Error(`Unhandled GET path "${path}"`));
223 }
224 record('tools.getLatestVersion', options, { path });
225 return withTestData(accountData.latestToolVersion, 'tools.getLatestVersion');
226 },
227 post: (path: string, options?: RequestOptions & { body?: unknown }) => {
228 if (!CREATE_PROJECT_API_KEY_PATH.test(path)) {
229 return Effect.fail(new Error(`Unhandled POST path "${path}"`));
230 }
231 record('org.project.createApiKey', options, { path, body: options?.body });
232 // An empty key counts as missing, as it always has.
233 return withTestData(accountData.projectApiKey || undefined, 'org.project.createApiKey').pipe(
234 Effect.map(apiKey => ({ api_key: apiKey }))
235 );
236 },
237 };
238 };