@composio/core 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/dist/BaseProvider-Brb3o86-.d.mts +29425 -0
  2. package/dist/{CustomTool-DEB4BQPl.mjs → CustomTool-D9qwyMrv.mjs} +1 -1
  3. package/dist/{CustomTool-DH18rVQu.d.mts → CustomTool-Dmi6ti3I.d.mts} +1 -1
  4. package/dist/CustomTool-DrJpOhY2.d.mts +74 -0
  5. package/dist/{composio-CHnEggnv.d.mts → composio-DHIKRdeG.d.mts} +253 -37
  6. package/dist/composio-vMwhASRc.d.mts +5698 -0
  7. package/dist/{customTool.types-DpIdOJjL.d.mts → customTool.types-CKH2R2ia.d.mts} +344 -25
  8. package/dist/customTool.types-DXin7Cfc.d.mts +2773 -0
  9. package/dist/docs/error-consistency.md +97 -0
  10. package/dist/docs/reference/sdk-reference/typescript/auth-configs.mdx +306 -0
  11. package/dist/docs/reference/sdk-reference/typescript/composio.mdx +205 -0
  12. package/dist/docs/reference/sdk-reference/typescript/connected-accounts.mdx +488 -0
  13. package/dist/docs/reference/sdk-reference/typescript/experimental.mdx +94 -0
  14. package/dist/docs/reference/sdk-reference/typescript/index.mdx +67 -0
  15. package/dist/docs/reference/sdk-reference/typescript/mcp.mdx +304 -0
  16. package/dist/docs/reference/sdk-reference/typescript/meta.json +17 -0
  17. package/dist/docs/reference/sdk-reference/typescript/remote-file.mdx +107 -0
  18. package/dist/docs/reference/sdk-reference/typescript/session-files.mdx +163 -0
  19. package/dist/docs/reference/sdk-reference/typescript/session.mdx +229 -0
  20. package/dist/docs/reference/sdk-reference/typescript/sessions.mdx +131 -0
  21. package/dist/docs/reference/sdk-reference/typescript/toolkits.mdx +169 -0
  22. package/dist/docs/reference/sdk-reference/typescript/tools.mdx +453 -0
  23. package/dist/docs/reference/sdk-reference/typescript/triggers.mdx +434 -0
  24. package/dist/{errors-D5f4pfvI.mjs → errors-DSIlYfl5.mjs} +2 -2
  25. package/dist/experimental/index.d.mts +2 -2
  26. package/dist/experimental/index.mjs +1 -1
  27. package/dist/index.d.mts +27 -4
  28. package/dist/index.mjs +423 -123
  29. package/dist/{jsonSchema-daqF3S3d.mjs → jsonSchema-CFKdONpP.mjs} +1 -1
  30. package/dist/{types-CaI5Z4PA.d.mts → types-D4Id3wXA.d.mts} +1 -1
  31. package/dist/types-qTbYYBJw.d.mts +12 -0
  32. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
  33. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
  34. package/dist/utils/modifiers/FileToolModifier.node.mjs +2 -2
  35. package/docs/error-consistency.md +97 -0
  36. package/package.json +4 -3
  37. package/src/composio.ts +509 -0
  38. package/src/errors/AuthConfigErrors.ts +23 -0
  39. package/src/errors/ComposioError.ts +408 -0
  40. package/src/errors/ConnectedAccountsErrors.ts +158 -0
  41. package/src/errors/ConnectionRequestErrors.ts +32 -0
  42. package/src/errors/FileModifierErrors.ts +100 -0
  43. package/src/errors/PusherErrors.ts +28 -0
  44. package/src/errors/RemoteFileErrors.ts +62 -0
  45. package/src/errors/SDKErrors.ts +92 -0
  46. package/src/errors/ToolErrors.ts +244 -0
  47. package/src/errors/ToolkitErrors.ts +39 -0
  48. package/src/errors/TriggerErrors.ts +120 -0
  49. package/src/errors/ValidationErrors.ts +99 -0
  50. package/src/errors/index.ts +41 -0
  51. package/src/experimental/index.ts +28 -0
  52. package/src/index.ts +64 -0
  53. package/src/lib/toolRouterConstants.ts +1 -0
  54. package/src/lib/toolRouterParams.ts +306 -0
  55. package/src/models/AuthConfigs.ts +398 -0
  56. package/src/models/AuthScheme.ts +206 -0
  57. package/src/models/ConnectedAccounts.ts +735 -0
  58. package/src/models/ConnectionRequest.ts +150 -0
  59. package/src/models/CustomTool.ts +676 -0
  60. package/src/models/Experimental.ts +202 -0
  61. package/src/models/Files.node.ts +93 -0
  62. package/src/models/Files.workerd.ts +49 -0
  63. package/src/models/MCP.ts +478 -0
  64. package/src/models/RemoteFile.ts +172 -0
  65. package/src/models/SessionContext.ts +147 -0
  66. package/src/models/Sessions.ts +21 -0
  67. package/src/models/ToolRouter.ts +391 -0
  68. package/src/models/ToolRouterSession.ts +827 -0
  69. package/src/models/ToolRouterSessionFileMount.ts +389 -0
  70. package/src/models/Toolkits.ts +412 -0
  71. package/src/models/Tools.ts +1260 -0
  72. package/src/models/Triggers.ts +1381 -0
  73. package/src/models/customToolExecution.ts +118 -0
  74. package/src/models/inlineCustomToolsPayload.ts +17 -0
  75. package/src/models/proxyParamsTransform.ts +26 -0
  76. package/src/provider/BaseProvider.ts +138 -0
  77. package/src/provider/ComposioProvider.ts +29 -0
  78. package/src/provider/OpenAIProvider.ts +547 -0
  79. package/src/services/internal/InternalService.ts +50 -0
  80. package/src/services/internal/InternalService.types.ts +14 -0
  81. package/src/services/pusher/Pusher.ts +230 -0
  82. package/src/services/telemetry/TelemetryService.ts +48 -0
  83. package/src/services/telemetry/TelemetryService.types.ts +67 -0
  84. package/src/telemetry/BatchProcessor.ts +77 -0
  85. package/src/telemetry/README.md +123 -0
  86. package/src/telemetry/Telemetry.ts +356 -0
  87. package/src/types/ToolRouterSessionFilesMount.types.ts +96 -0
  88. package/src/types/authConfigs.types.ts +174 -0
  89. package/src/types/composio.types.ts +1 -0
  90. package/src/types/connectedAccountAuthStates.types.ts +852 -0
  91. package/src/types/connectedAccounts.types.ts +395 -0
  92. package/src/types/connectionRequest.types.ts +16 -0
  93. package/src/types/customTool.types.ts +261 -0
  94. package/src/types/files.types.ts +15 -0
  95. package/src/types/mcp.experimental.types.ts +163 -0
  96. package/src/types/mcp.types.ts +362 -0
  97. package/src/types/modifiers.types.ts +663 -0
  98. package/src/types/org.types.ts +0 -0
  99. package/src/types/provider.types.ts +41 -0
  100. package/src/types/pusher.types.ts +18 -0
  101. package/src/types/requestOptions.types.ts +62 -0
  102. package/src/types/telemetry.types.ts +89 -0
  103. package/src/types/tool.types.ts +408 -0
  104. package/src/types/toolRouter.types.ts +761 -0
  105. package/src/types/toolkit.types.ts +130 -0
  106. package/src/types/triggers.types.ts +401 -0
  107. package/src/types/webhookEvents.types.ts +219 -0
  108. package/src/utils/buffer.ts +30 -0
  109. package/src/utils/cancellation.ts +22 -0
  110. package/src/utils/config-defaults/ConfigDefaults.node.ts +7 -0
  111. package/src/utils/config-defaults/ConfigDefaults.workerd.ts +10 -0
  112. package/src/utils/config-defaults/index.ts +1 -0
  113. package/src/utils/config-defaults/types.ts +14 -0
  114. package/src/utils/constants.ts +22 -0
  115. package/src/utils/crypto.ts +34 -0
  116. package/src/utils/env.ts +34 -0
  117. package/src/utils/fileDirs.ts +81 -0
  118. package/src/utils/fileUtils.node.ts +458 -0
  119. package/src/utils/json-schema.ts +1 -0
  120. package/src/utils/jsonSchema.ts +355 -0
  121. package/src/utils/logger.ts +99 -0
  122. package/src/utils/mime.ts +75 -0
  123. package/src/utils/modifiers/FileToolModifier.node.ts +477 -0
  124. package/src/utils/modifiers/FileToolModifier.utils.neutral.ts +132 -0
  125. package/src/utils/modifiers/FileToolModifier.workerd.ts +51 -0
  126. package/src/utils/pagination.ts +73 -0
  127. package/src/utils/pusher.ts +286 -0
  128. package/src/utils/schemaPropertyKeys.ts +433 -0
  129. package/src/utils/sdk.ts +110 -0
  130. package/src/utils/sensitiveFileUploadPaths.node.ts +105 -0
  131. package/src/utils/session.ts +114 -0
  132. package/src/utils/toolArguments.ts +73 -0
  133. package/src/utils/toolkitVersion.ts +26 -0
  134. package/src/utils/transform.ts +42 -0
  135. package/src/utils/transformers/authConfigs.ts +107 -0
  136. package/src/utils/transformers/connectedAccounts.ts +119 -0
  137. package/src/utils/transformers/mcp.ts +164 -0
  138. package/src/utils/transformers/toolRouterResponseTransform.ts +160 -0
  139. package/src/utils/transformers/toolkits.ts +100 -0
  140. package/src/utils/transformers/triggers.ts +118 -0
  141. package/src/utils/uploadDirAllowlist.node.ts +178 -0
  142. package/src/utils/uuid.ts +7 -0
  143. package/src/utils/version.ts +58 -0
  144. package/src/utils/zodSchema.ts +90 -0
@@ -0,0 +1,114 @@
1
+ import type { BaseComposioProvider } from '../provider/BaseProvider';
2
+ import { version } from '../../package.json';
3
+ import type { ComposioRequestHeaders } from '../types/composio.types';
4
+
5
+ /**
6
+ * Extended globalThis interface for runtime detection
7
+ */
8
+ interface ExtendedGlobalThis {
9
+ Bun?: unknown;
10
+ Deno?: unknown;
11
+ caches?: unknown;
12
+ WebSocketPair?: unknown;
13
+ EdgeRuntime?: unknown;
14
+ ServiceWorkerGlobalScope?: new () => unknown;
15
+ WorkerGlobalScope?: new () => unknown;
16
+ importScripts?: (url: string) => void;
17
+ }
18
+
19
+ /**
20
+ * Detect the JavaScript runtime environment without importing any external modules.
21
+ * Uses only built-in globals to avoid breaking in different environments.
22
+ */
23
+ function detectRuntime(): string {
24
+ const global = globalThis as ExtendedGlobalThis;
25
+
26
+ // Check for Bun
27
+ if ('Bun' in global && typeof global.Bun !== 'undefined') {
28
+ return 'BUN';
29
+ }
30
+
31
+ // Check for Deno
32
+ if ('Deno' in global && typeof global.Deno !== 'undefined') {
33
+ return 'DENO';
34
+ }
35
+
36
+ // Check for Node.js
37
+ if (typeof process !== 'undefined' && process.versions && process.versions.node) {
38
+ return 'NODEJS';
39
+ }
40
+
41
+ // Check for Cloudflare Workers
42
+ if (
43
+ 'caches' in global &&
44
+ typeof global.caches !== 'undefined' &&
45
+ 'WebSocketPair' in global &&
46
+ typeof global.WebSocketPair !== 'undefined'
47
+ ) {
48
+ return 'CLOUDFLARE_WORKERS';
49
+ }
50
+
51
+ // Check for Vercel Edge Runtime
52
+ if ('EdgeRuntime' in global && typeof global.EdgeRuntime !== 'undefined') {
53
+ return 'VERCEL_EDGE';
54
+ }
55
+
56
+ // Check for Service Worker
57
+ if (
58
+ 'ServiceWorkerGlobalScope' in global &&
59
+ typeof global.ServiceWorkerGlobalScope !== 'undefined'
60
+ ) {
61
+ const ServiceWorkerScope = global.ServiceWorkerGlobalScope;
62
+ if (ServiceWorkerScope && global instanceof ServiceWorkerScope) {
63
+ return 'SERVICE_WORKER';
64
+ }
65
+ }
66
+
67
+ // Check for Web Worker
68
+ if (
69
+ 'WorkerGlobalScope' in global &&
70
+ typeof global.WorkerGlobalScope !== 'undefined' &&
71
+ 'importScripts' in global &&
72
+ typeof global.importScripts === 'function'
73
+ ) {
74
+ return 'WEB_WORKER';
75
+ }
76
+
77
+ // Check for React Native
78
+ if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {
79
+ return 'REACT_NATIVE';
80
+ }
81
+
82
+ // Check for Browser
83
+ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
84
+ return 'BROWSER';
85
+ }
86
+
87
+ // Fallback
88
+ return 'UNKNOWN';
89
+ }
90
+
91
+ // Detect once at module initialization
92
+ const RUNTIME_ENV = detectRuntime();
93
+
94
+ export function getSessionHeaders(
95
+ provider: BaseComposioProvider<unknown, unknown, unknown> | undefined
96
+ ) {
97
+ return {
98
+ 'x-framework': provider?.name || 'unknown',
99
+ 'x-source': 'TYPESCRIPT_SDK',
100
+ 'x-runtime': RUNTIME_ENV,
101
+ 'x-sdk-version': version,
102
+ };
103
+ }
104
+
105
+ export const getDefaultHeaders = (
106
+ headers: ComposioRequestHeaders | undefined,
107
+ provider: BaseComposioProvider<unknown, unknown, unknown> | undefined
108
+ ) => {
109
+ const sessionHeaders = getSessionHeaders(provider);
110
+ return {
111
+ ...(headers || {}),
112
+ ...sessionHeaders,
113
+ };
114
+ };
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Tool-argument normalization.
3
+ *
4
+ * Models (and MCP transports) occasionally emit tool-call arguments as a JSON
5
+ * *string* instead of an object. `COMPOSIO_MULTI_EXECUTE_TOOL` and Vercel AI
6
+ * SDK streaming are common triggers. Forwarding that raw string to execution
7
+ * surfaces opaque downstream errors such as
8
+ * `tool_use.input: Input should be a valid dictionary`.
9
+ *
10
+ * `normalizeToolArguments` is the single coercion every provider routes through
11
+ * so the behaviour is identical everywhere instead of being re-implemented
12
+ * (inconsistently) per provider.
13
+ *
14
+ * @see https://github.com/ComposioHQ/composio/issues/2406
15
+ */
16
+ import { ComposioInvalidToolArgumentsError } from '../errors/ToolErrors';
17
+
18
+ /**
19
+ * Coerce model-supplied tool arguments into a plain object.
20
+ *
21
+ * Rules:
22
+ * - `null` / `undefined` → `{}` (some models send no arguments for no-arg tools).
23
+ * - A plain object is returned unchanged.
24
+ * - A string is JSON-parsed; an empty / whitespace-only string becomes `{}`.
25
+ * - Anything that does not resolve to a plain object (arrays, primitives,
26
+ * unparseable strings, JSON that parses to a non-object) throws a typed
27
+ * {@link ComposioInvalidToolArgumentsError} so callers get an actionable
28
+ * message instead of a raw `SyntaxError` or a silent malformed payload.
29
+ *
30
+ * @param input - Raw arguments as received from the model / framework.
31
+ * @param toolSlug - Optional tool slug, used to enrich the error message.
32
+ * @returns The normalized arguments as a `Record<string, unknown>`.
33
+ */
34
+ export function normalizeToolArguments(input: unknown, toolSlug?: string): Record<string, unknown> {
35
+ if (input === null || input === undefined) {
36
+ return {};
37
+ }
38
+
39
+ if (typeof input === 'string') {
40
+ const trimmed = input.trim();
41
+ if (trimmed === '') {
42
+ return {};
43
+ }
44
+
45
+ let parsed: unknown;
46
+ try {
47
+ parsed = JSON.parse(trimmed);
48
+ } catch (cause) {
49
+ throw new ComposioInvalidToolArgumentsError(
50
+ `${describeTool(toolSlug)} received arguments as a string that is not valid JSON`,
51
+ { cause: cause instanceof Error ? cause : undefined }
52
+ );
53
+ }
54
+ return assertPlainObject(parsed, toolSlug);
55
+ }
56
+
57
+ return assertPlainObject(input, toolSlug);
58
+ }
59
+
60
+ function assertPlainObject(value: unknown, toolSlug?: string): Record<string, unknown> {
61
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
62
+ return value as Record<string, unknown>;
63
+ }
64
+
65
+ const actual = Array.isArray(value) ? 'array' : typeof value;
66
+ throw new ComposioInvalidToolArgumentsError(
67
+ `${describeTool(toolSlug)} expected arguments to be an object, received ${actual}`
68
+ );
69
+ }
70
+
71
+ function describeTool(toolSlug?: string): string {
72
+ return toolSlug ? `Tool '${toolSlug}'` : 'Tool';
73
+ }
@@ -0,0 +1,26 @@
1
+ import { ToolkitVersion, ToolkitVersionParam } from '../types/tool.types';
2
+
3
+ /**
4
+ * Gets the version for a specific toolkit based on the provided toolkit versions configuration.
5
+ *
6
+ * @param toolkitSlug - The slug/name of the toolkit to get the version for
7
+ * @param toolkitVersions - Optional toolkit versions configuration (string for global version or object mapping toolkit slugs to versions)
8
+ * @returns The toolkit version to use - either the specific version from config, or 'latest' as fallback
9
+ */
10
+ export const getToolkitVersion = (
11
+ toolkitSlug: string,
12
+ toolkitVersions?: ToolkitVersionParam
13
+ ): ToolkitVersion => {
14
+ // If toolkitVersions is a string, use it as a global version for all toolkits
15
+ if (typeof toolkitVersions === 'string') {
16
+ return toolkitVersions;
17
+ }
18
+ // If toolkitVersions is an object mapping, look up the specific toolkit version
19
+ const hasToolkitVersion = toolkitVersions && Object.keys(toolkitVersions).length > 0;
20
+ if (hasToolkitVersion) {
21
+ return toolkitVersions[toolkitSlug] ?? 'latest';
22
+ }
23
+
24
+ // Else use 'latest'
25
+ return 'latest';
26
+ };
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Function to transform the response from the API to the expected format
3
+ * This takes in the zod schema to be transformed into and the response from the API
4
+ *
5
+ * Users need to manually map the fields to the expected format
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * transform(response)
10
+ * .with(ConnectedAccountRetrieveResponseSchema)
11
+ * .using((raw) => ({ ... }))
12
+ * ```
13
+ */
14
+ import { ZodTypeAny, z } from 'zod/v3';
15
+ import logger from './logger';
16
+
17
+ export function transform<RawInput>(raw: RawInput) {
18
+ return {
19
+ with<Schema extends ZodTypeAny>(schema: Schema) {
20
+ return {
21
+ using(
22
+ transformer: (input: RawInput) => z.infer<Schema>,
23
+ options?: { label?: string }
24
+ ): z.infer<Schema> {
25
+ const transformed = transformer(raw);
26
+ const result = schema.safeParse(transformed);
27
+
28
+ if (!result.success) {
29
+ const label = options?.label ? ` for ${options.label}` : '';
30
+ const issues = result.error.issues
31
+ .map(issue => ` - ${issue.path.join('.') || 'parameter'}: ${issue.message}`)
32
+ .join('\n');
33
+ logger.warn(`Transform validation failed${label}:\n${issues}`);
34
+ return transformed;
35
+ }
36
+
37
+ return result.data;
38
+ },
39
+ };
40
+ },
41
+ };
42
+ }
@@ -0,0 +1,107 @@
1
+ import { logger } from '../..';
2
+ import {
3
+ AuthConfigRetrieveResponse,
4
+ AuthConfigRetrieveResponseSchema,
5
+ AuthConfigListResponse,
6
+ AuthConfigListResponseSchema,
7
+ CreateAuthConfigResponse,
8
+ CreateAuthConfigResponseSchema,
9
+ } from '../../types/authConfigs.types';
10
+
11
+ import {
12
+ AuthConfigListResponse as RawAuthConfigListResponse,
13
+ AuthConfigRetrieveResponse as RawAuthConfigRetrieveResponse,
14
+ AuthConfigCreateResponse as RawCreateAuthConfigResponse,
15
+ } from '@composio/client/resources/auth-configs';
16
+ import { transform } from '../transform';
17
+
18
+ /**
19
+ * Transforms an auth config response from API format to SDK format.
20
+ *
21
+ * This method converts property names from snake_case to camelCase and reorganizes
22
+ * the data structure to match the SDK's standardized format for auth configurations.
23
+ *
24
+ * @param {RawAuthConfigRetrieveResponse} authConfig - The raw API response to transform
25
+ * @returns {AuthConfigRetrieveResponse} The transformed auth config data
26
+ *
27
+ * @private
28
+ */
29
+ export function transformAuthConfigRetrieveResponse(
30
+ authConfig: RawAuthConfigRetrieveResponse
31
+ ): AuthConfigRetrieveResponse {
32
+ return transform(authConfig)
33
+ .with(AuthConfigRetrieveResponseSchema)
34
+ .using(authConfig => ({
35
+ id: authConfig.id,
36
+ name: authConfig.name,
37
+ noOfConnections: authConfig.no_of_connections,
38
+ status: authConfig.status,
39
+ toolkit: {
40
+ logo: authConfig.toolkit.logo,
41
+ slug: authConfig.toolkit.slug,
42
+ },
43
+ isEnabledForToolRouter: authConfig.is_enabled_for_tool_router,
44
+ authScheme: authConfig.auth_scheme,
45
+ credentials: authConfig.credentials,
46
+ expectedInputFields: authConfig.expected_input_fields,
47
+ isComposioManaged: authConfig.is_composio_managed,
48
+ createdBy: authConfig.created_by,
49
+ createdAt: authConfig.created_at,
50
+ lastUpdatedAt: authConfig.last_updated_at,
51
+ restrictToFollowingTools: authConfig.tool_access_config?.tools_for_connected_account_creation,
52
+ toolAccessConfig: authConfig.tool_access_config
53
+ ? {
54
+ toolsAvailableForExecution: authConfig.tool_access_config.tools_available_for_execution,
55
+ toolsForConnectedAccountCreation:
56
+ authConfig.tool_access_config.tools_for_connected_account_creation,
57
+ }
58
+ : undefined,
59
+ }));
60
+ }
61
+
62
+ /**
63
+ * Transforms the raw auth config list response from the Composio API to the SDK format.
64
+ *
65
+ * This method converts property names from snake_case to camelCase and reorganizes
66
+ * the data structure to match the SDK's standardized format for auth configurations.
67
+ *
68
+ * @param {RawAuthConfigListResponse} response - The raw API response to transform
69
+ * @returns {AuthConfigListResponse} The transformed response
70
+ *
71
+ * @private
72
+ */
73
+ export function transformAuthConfigListResponse(
74
+ response: RawAuthConfigListResponse
75
+ ): AuthConfigListResponse {
76
+ return transform(response)
77
+ .with(AuthConfigListResponseSchema)
78
+ .using(response => ({
79
+ items: response.items.map(transformAuthConfigRetrieveResponse),
80
+ nextCursor: response.next_cursor ?? null,
81
+ totalPages: response.total_pages,
82
+ }));
83
+ }
84
+
85
+ /**
86
+ * Transforms the raw create auth config response from the Composio API to the SDK format.
87
+ *
88
+ * This method converts property names from snake_case to camelCase and reorganizes
89
+ * the data structure to match the SDK's standardized format for auth configurations.
90
+ *
91
+ * @param {RawCreateAuthConfigResponse} response - The raw API response to transform
92
+ * @returns {CreateAuthConfigResponse} The transformed response
93
+ *
94
+ * @private
95
+ */
96
+ export function transformCreateAuthConfigResponse(
97
+ response: RawCreateAuthConfigResponse
98
+ ): CreateAuthConfigResponse {
99
+ return transform(response)
100
+ .with(CreateAuthConfigResponseSchema)
101
+ .using(response => ({
102
+ id: response.auth_config.id,
103
+ authScheme: response.auth_config.auth_scheme,
104
+ isComposioManaged: response.auth_config.is_composio_managed,
105
+ toolkit: response.toolkit.slug,
106
+ }));
107
+ }
@@ -0,0 +1,119 @@
1
+ import {
2
+ ConnectedAccountListResponse as RawConnectedAccountListResponse,
3
+ ConnectedAccountRetrieveResponse as RawConnectedAccountRetrieveResponse,
4
+ } from '@composio/client/resources/connected-accounts';
5
+ import {
6
+ ConnectedAccountListResponse,
7
+ ConnectedAccountListResponseSchema,
8
+ ConnectedAccountRetrieveResponse,
9
+ ConnectedAccountRetrieveResponseSchema,
10
+ } from '../../types/connectedAccounts.types';
11
+ import { ConnectionDataSchema } from '../../types/connectedAccountAuthStates.types';
12
+ import logger from '../logger';
13
+ import { transform } from '../transform';
14
+
15
+ type RawConnectedAccountResponseWithLabels = (
16
+ | RawConnectedAccountRetrieveResponse
17
+ | RawConnectedAccountListResponse['items'][0]
18
+ ) & {
19
+ word_id?: string | null;
20
+ alias?: string | null;
21
+ };
22
+
23
+ /**
24
+ * Transforms the raw connected account response from the Composio API to the SDK format.
25
+ *
26
+ * This method converts property names from snake_case to camelCase and reorganizes
27
+ * the data structure to match the SDK's standardized format.
28
+ *
29
+ * @param {RawConnectedAccountListResponse['items'][0]|RawConnectedAccountRetrieveResponse} response - The raw API response to transform
30
+ * @returns {Promise<ConnectedAccountRetrieveResponse>} The transformed response
31
+ * @throws {ZodError} If the response fails validation against the expected schema
32
+ *
33
+ * @private
34
+ */
35
+ export function transformConnectedAccountResponse(
36
+ response: RawConnectedAccountRetrieveResponse | RawConnectedAccountListResponse['items'][0]
37
+ ): ConnectedAccountRetrieveResponse {
38
+ const responseWithLabels = response as RawConnectedAccountResponseWithLabels;
39
+
40
+ // Safely parse the state field, filtering out unsupported auth schemes
41
+ const parseState = (state: unknown) => {
42
+ try {
43
+ return state ? ConnectionDataSchema.parse(state) : undefined;
44
+ } catch (error) {
45
+ logger.warn('Unsupported auth scheme in connected account state, ignoring state field', {
46
+ error,
47
+ });
48
+ return undefined;
49
+ }
50
+ };
51
+
52
+ return transform(response)
53
+ .with(ConnectedAccountRetrieveResponseSchema)
54
+ .using(response => ({
55
+ ...response,
56
+ authConfig: {
57
+ ...response.auth_config,
58
+ id: response.auth_config.id,
59
+ authScheme: response.auth_config.auth_scheme,
60
+ isComposioManaged: response.auth_config.is_composio_managed,
61
+ isDisabled: response.auth_config.is_disabled,
62
+ },
63
+ wordId: responseWithLabels.word_id ?? null,
64
+ alias: responseWithLabels.alias ?? null,
65
+ data: (response as unknown as ConnectedAccountRetrieveResponse).data ?? undefined,
66
+ state: parseState(response.state),
67
+ status: response.status,
68
+ statusReason: response.status_reason,
69
+ isDisabled: response.is_disabled,
70
+ createdAt: response.created_at,
71
+ updatedAt: response.updated_at,
72
+ testRequestEndpoint: response.test_request_endpoint,
73
+ // Experimental — shape may change in future releases. Pass the
74
+ // nested `experimental` block straight through; the inner
75
+ // `aclConfigForShared` is conditionally visible (absent when the
76
+ // caller isn't authorised to see the ACL), so distinguish "I can't
77
+ // see the ACL" from "ACL is the default deny-by-default state" by
78
+ // checking field presence.
79
+ experimental: responseWithLabels.experimental
80
+ ? {
81
+ accountType: responseWithLabels.experimental.account_type,
82
+ aclConfigForShared: responseWithLabels.experimental.acl_config_for_shared
83
+ ? {
84
+ allowAllUsers:
85
+ responseWithLabels.experimental.acl_config_for_shared.allow_all_users,
86
+ allowedUserIds:
87
+ responseWithLabels.experimental.acl_config_for_shared.allowed_user_ids,
88
+ notAllowedUserIds:
89
+ responseWithLabels.experimental.acl_config_for_shared.not_allowed_user_ids,
90
+ }
91
+ : undefined,
92
+ }
93
+ : undefined,
94
+ }));
95
+ }
96
+
97
+ /**
98
+ * Transforms the raw connected account list response from the Composio API to the SDK format.
99
+ *
100
+ * This method converts property names from snake_case to camelCase and reorganizes
101
+ * the data structure to match the SDK's standardized format.
102
+ *
103
+ * @param {RawConnectedAccountListResponse} response - The raw API response to transform
104
+ * @returns {ConnectedAccountListResponse} The transformed response
105
+ * @throws {ZodError} If the response fails validation against the expected schema
106
+ *
107
+ * @private
108
+ */
109
+ export function transformConnectedAccountListResponse(
110
+ response: RawConnectedAccountListResponse
111
+ ): ConnectedAccountListResponse {
112
+ return transform(response)
113
+ .with(ConnectedAccountListResponseSchema)
114
+ .using(response => ({
115
+ items: response.items.map(transformConnectedAccountResponse),
116
+ nextCursor: response.next_cursor ?? null,
117
+ totalPages: response.total_pages,
118
+ }));
119
+ }
@@ -0,0 +1,164 @@
1
+ import { ValidationError } from '../../errors/ValidationErrors';
2
+ import {
3
+ CustomCreateResponseSchema,
4
+ McpListResponseSchema,
5
+ McpRetrieveResponseSchema,
6
+ McpDeleteResponseSchema,
7
+ McpUpdateResponseSchema,
8
+ CustomCreateResponse,
9
+ McpListResponse,
10
+ McpRetrieveResponse,
11
+ McpDeleteResponse,
12
+ McpUpdateResponse,
13
+ GenerateURLResponse,
14
+ GenerateURLResponseSchema,
15
+ } from '../../types/mcp.types';
16
+ import {
17
+ CustomCreateResponse as CustomCreateResponseRaw,
18
+ GenerateURLResponse as GenerateURLResponseRaw,
19
+ McpListResponse as McpListResponseRaw,
20
+ McpCreateResponse as McpCreateResponseRaw,
21
+ McpDeleteResponse as McpDeleteResponseRaw,
22
+ McpUpdateResponse as McpUpdateResponseRaw,
23
+ McpRetrieveResponse as McpRetrieveResponseRaw,
24
+ } from '@composio/client/resources/mcp';
25
+
26
+ /**
27
+ * Transform MCP create response from snake_case to camelCase
28
+ */
29
+ export function transformMcpCreateResponse(
30
+ response: CustomCreateResponseRaw | McpCreateResponseRaw
31
+ ): CustomCreateResponse {
32
+ const result = CustomCreateResponseSchema.safeParse({
33
+ id: response.id,
34
+ name: response.name,
35
+ createdAt: (response as unknown as Record<string, unknown>).created_at,
36
+ updatedAt: (response as unknown as Record<string, unknown>).updated_at,
37
+ status: (response as unknown as Record<string, unknown>).status,
38
+ });
39
+
40
+ if (!result.success) {
41
+ throw new ValidationError('Failed to parse MCP create response', {
42
+ cause: result.error,
43
+ });
44
+ }
45
+
46
+ return result.data;
47
+ }
48
+
49
+ /**
50
+ * Transform MCP list response from snake_case to camelCase
51
+ */
52
+ export function transformMcpListResponse(response: McpListResponseRaw): McpListResponse {
53
+ const transformedItems = response.items?.map(item => ({
54
+ id: item.id,
55
+ name: item.name,
56
+ createdAt: item.created_at,
57
+ updatedAt: item.updated_at,
58
+ status: (item as unknown as Record<string, unknown>).status,
59
+ }));
60
+
61
+ const result = McpListResponseSchema.safeParse({
62
+ items: transformedItems,
63
+ });
64
+
65
+ if (!result.success) {
66
+ throw new ValidationError('Failed to parse MCP list response', {
67
+ cause: result.error,
68
+ });
69
+ }
70
+
71
+ return result.data;
72
+ }
73
+
74
+ /**
75
+ * Transform MCP retrieve response from snake_case to camelCase
76
+ */
77
+ export function transformMcpRetrieveResponse(
78
+ response: McpRetrieveResponseRaw
79
+ ): McpRetrieveResponse {
80
+ const result = McpRetrieveResponseSchema.safeParse({
81
+ id: response.id,
82
+ name: response.name,
83
+ createdAt: response.created_at,
84
+ updatedAt: response.updated_at,
85
+ status: (response as unknown as Record<string, unknown>).status,
86
+ toolkits: response.toolkits,
87
+ tools: response.allowed_tools,
88
+ managedAuthViaComposio: response.managed_auth_via_composio,
89
+ authConfigIds: response.auth_config_ids,
90
+ mcpUrl: response.mcp_url,
91
+ commands: response.commands,
92
+ });
93
+
94
+ if (!result.success) {
95
+ throw new ValidationError('Failed to parse MCP retrieve response', {
96
+ cause: result.error,
97
+ });
98
+ }
99
+
100
+ return result.data;
101
+ }
102
+
103
+ /**
104
+ * Transform MCP delete response from snake_case to camelCase
105
+ */
106
+ export function transformMcpDeleteResponse(response: McpDeleteResponseRaw): McpDeleteResponse {
107
+ const result = McpDeleteResponseSchema.safeParse({
108
+ id: (response as unknown as Record<string, unknown>).id,
109
+ deleted: (response as unknown as Record<string, unknown>).deleted,
110
+ message: (response as unknown as Record<string, unknown>).message,
111
+ });
112
+
113
+ if (!result.success) {
114
+ throw new ValidationError('Failed to parse MCP delete response', {
115
+ cause: result.error,
116
+ });
117
+ }
118
+
119
+ return result.data;
120
+ }
121
+
122
+ /**
123
+ * Transform MCP update response from snake_case to camelCase
124
+ */
125
+ export function transformMcpUpdateResponse(response: McpUpdateResponseRaw): McpUpdateResponse {
126
+ const result = McpUpdateResponseSchema.safeParse({
127
+ id: response.id,
128
+ name: response.name,
129
+ createdAt: response.created_at,
130
+ updatedAt: response.updated_at,
131
+ status: (response as unknown as Record<string, unknown>).status,
132
+ toolkits: response.toolkits,
133
+ tools: (response as unknown as Record<string, unknown>).tools,
134
+ });
135
+
136
+ if (!result.success) {
137
+ throw new ValidationError('Failed to parse MCP update response', {
138
+ cause: result.error,
139
+ });
140
+ }
141
+
142
+ return result.data;
143
+ }
144
+
145
+ /**
146
+ * Transform MCP generate URL response from snake_case to camelCase
147
+ */
148
+ export function transformMcpGenerateUrlResponse(
149
+ response: GenerateURLResponseRaw
150
+ ): GenerateURLResponse {
151
+ const result = GenerateURLResponseSchema.safeParse({
152
+ connectedAccountUrls: response.connected_account_urls,
153
+ userIdsUrl: response.user_ids_url,
154
+ mcpUrl: response.mcp_url,
155
+ });
156
+
157
+ if (!result.success) {
158
+ throw new ValidationError('Failed to parse MCP generate URL response', {
159
+ cause: result.error,
160
+ });
161
+ }
162
+
163
+ return result.data;
164
+ }