@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.
- package/dist/BaseProvider-Brb3o86-.d.mts +29425 -0
- package/dist/{CustomTool-DEB4BQPl.mjs → CustomTool-D9qwyMrv.mjs} +1 -1
- package/dist/{CustomTool-DH18rVQu.d.mts → CustomTool-Dmi6ti3I.d.mts} +1 -1
- package/dist/CustomTool-DrJpOhY2.d.mts +74 -0
- package/dist/{composio-CHnEggnv.d.mts → composio-DHIKRdeG.d.mts} +253 -37
- package/dist/composio-vMwhASRc.d.mts +5698 -0
- package/dist/{customTool.types-DpIdOJjL.d.mts → customTool.types-CKH2R2ia.d.mts} +344 -25
- package/dist/customTool.types-DXin7Cfc.d.mts +2773 -0
- package/dist/docs/error-consistency.md +97 -0
- package/dist/docs/reference/sdk-reference/typescript/auth-configs.mdx +306 -0
- package/dist/docs/reference/sdk-reference/typescript/composio.mdx +205 -0
- package/dist/docs/reference/sdk-reference/typescript/connected-accounts.mdx +488 -0
- package/dist/docs/reference/sdk-reference/typescript/experimental.mdx +94 -0
- package/dist/docs/reference/sdk-reference/typescript/index.mdx +67 -0
- package/dist/docs/reference/sdk-reference/typescript/mcp.mdx +304 -0
- package/dist/docs/reference/sdk-reference/typescript/meta.json +17 -0
- package/dist/docs/reference/sdk-reference/typescript/remote-file.mdx +107 -0
- package/dist/docs/reference/sdk-reference/typescript/session-files.mdx +163 -0
- package/dist/docs/reference/sdk-reference/typescript/session.mdx +229 -0
- package/dist/docs/reference/sdk-reference/typescript/sessions.mdx +131 -0
- package/dist/docs/reference/sdk-reference/typescript/toolkits.mdx +169 -0
- package/dist/docs/reference/sdk-reference/typescript/tools.mdx +453 -0
- package/dist/docs/reference/sdk-reference/typescript/triggers.mdx +434 -0
- package/dist/{errors-D5f4pfvI.mjs → errors-DSIlYfl5.mjs} +2 -2
- package/dist/experimental/index.d.mts +2 -2
- package/dist/experimental/index.mjs +1 -1
- package/dist/index.d.mts +27 -4
- package/dist/index.mjs +423 -123
- package/dist/{jsonSchema-daqF3S3d.mjs → jsonSchema-CFKdONpP.mjs} +1 -1
- package/dist/{types-CaI5Z4PA.d.mts → types-D4Id3wXA.d.mts} +1 -1
- package/dist/types-qTbYYBJw.d.mts +12 -0
- package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
- package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
- package/dist/utils/modifiers/FileToolModifier.node.mjs +2 -2
- package/docs/error-consistency.md +97 -0
- package/package.json +4 -3
- package/src/composio.ts +509 -0
- package/src/errors/AuthConfigErrors.ts +23 -0
- package/src/errors/ComposioError.ts +408 -0
- package/src/errors/ConnectedAccountsErrors.ts +158 -0
- package/src/errors/ConnectionRequestErrors.ts +32 -0
- package/src/errors/FileModifierErrors.ts +100 -0
- package/src/errors/PusherErrors.ts +28 -0
- package/src/errors/RemoteFileErrors.ts +62 -0
- package/src/errors/SDKErrors.ts +92 -0
- package/src/errors/ToolErrors.ts +244 -0
- package/src/errors/ToolkitErrors.ts +39 -0
- package/src/errors/TriggerErrors.ts +120 -0
- package/src/errors/ValidationErrors.ts +99 -0
- package/src/errors/index.ts +41 -0
- package/src/experimental/index.ts +28 -0
- package/src/index.ts +64 -0
- package/src/lib/toolRouterConstants.ts +1 -0
- package/src/lib/toolRouterParams.ts +306 -0
- package/src/models/AuthConfigs.ts +398 -0
- package/src/models/AuthScheme.ts +206 -0
- package/src/models/ConnectedAccounts.ts +735 -0
- package/src/models/ConnectionRequest.ts +150 -0
- package/src/models/CustomTool.ts +676 -0
- package/src/models/Experimental.ts +202 -0
- package/src/models/Files.node.ts +93 -0
- package/src/models/Files.workerd.ts +49 -0
- package/src/models/MCP.ts +478 -0
- package/src/models/RemoteFile.ts +172 -0
- package/src/models/SessionContext.ts +147 -0
- package/src/models/Sessions.ts +21 -0
- package/src/models/ToolRouter.ts +391 -0
- package/src/models/ToolRouterSession.ts +827 -0
- package/src/models/ToolRouterSessionFileMount.ts +389 -0
- package/src/models/Toolkits.ts +412 -0
- package/src/models/Tools.ts +1260 -0
- package/src/models/Triggers.ts +1381 -0
- package/src/models/customToolExecution.ts +118 -0
- package/src/models/inlineCustomToolsPayload.ts +17 -0
- package/src/models/proxyParamsTransform.ts +26 -0
- package/src/provider/BaseProvider.ts +138 -0
- package/src/provider/ComposioProvider.ts +29 -0
- package/src/provider/OpenAIProvider.ts +547 -0
- package/src/services/internal/InternalService.ts +50 -0
- package/src/services/internal/InternalService.types.ts +14 -0
- package/src/services/pusher/Pusher.ts +230 -0
- package/src/services/telemetry/TelemetryService.ts +48 -0
- package/src/services/telemetry/TelemetryService.types.ts +67 -0
- package/src/telemetry/BatchProcessor.ts +77 -0
- package/src/telemetry/README.md +123 -0
- package/src/telemetry/Telemetry.ts +356 -0
- package/src/types/ToolRouterSessionFilesMount.types.ts +96 -0
- package/src/types/authConfigs.types.ts +174 -0
- package/src/types/composio.types.ts +1 -0
- package/src/types/connectedAccountAuthStates.types.ts +852 -0
- package/src/types/connectedAccounts.types.ts +395 -0
- package/src/types/connectionRequest.types.ts +16 -0
- package/src/types/customTool.types.ts +261 -0
- package/src/types/files.types.ts +15 -0
- package/src/types/mcp.experimental.types.ts +163 -0
- package/src/types/mcp.types.ts +362 -0
- package/src/types/modifiers.types.ts +663 -0
- package/src/types/org.types.ts +0 -0
- package/src/types/provider.types.ts +41 -0
- package/src/types/pusher.types.ts +18 -0
- package/src/types/requestOptions.types.ts +62 -0
- package/src/types/telemetry.types.ts +89 -0
- package/src/types/tool.types.ts +408 -0
- package/src/types/toolRouter.types.ts +761 -0
- package/src/types/toolkit.types.ts +130 -0
- package/src/types/triggers.types.ts +401 -0
- package/src/types/webhookEvents.types.ts +219 -0
- package/src/utils/buffer.ts +30 -0
- package/src/utils/cancellation.ts +22 -0
- package/src/utils/config-defaults/ConfigDefaults.node.ts +7 -0
- package/src/utils/config-defaults/ConfigDefaults.workerd.ts +10 -0
- package/src/utils/config-defaults/index.ts +1 -0
- package/src/utils/config-defaults/types.ts +14 -0
- package/src/utils/constants.ts +22 -0
- package/src/utils/crypto.ts +34 -0
- package/src/utils/env.ts +34 -0
- package/src/utils/fileDirs.ts +81 -0
- package/src/utils/fileUtils.node.ts +458 -0
- package/src/utils/json-schema.ts +1 -0
- package/src/utils/jsonSchema.ts +355 -0
- package/src/utils/logger.ts +99 -0
- package/src/utils/mime.ts +75 -0
- package/src/utils/modifiers/FileToolModifier.node.ts +477 -0
- package/src/utils/modifiers/FileToolModifier.utils.neutral.ts +132 -0
- package/src/utils/modifiers/FileToolModifier.workerd.ts +51 -0
- package/src/utils/pagination.ts +73 -0
- package/src/utils/pusher.ts +286 -0
- package/src/utils/schemaPropertyKeys.ts +433 -0
- package/src/utils/sdk.ts +110 -0
- package/src/utils/sensitiveFileUploadPaths.node.ts +105 -0
- package/src/utils/session.ts +114 -0
- package/src/utils/toolArguments.ts +73 -0
- package/src/utils/toolkitVersion.ts +26 -0
- package/src/utils/transform.ts +42 -0
- package/src/utils/transformers/authConfigs.ts +107 -0
- package/src/utils/transformers/connectedAccounts.ts +119 -0
- package/src/utils/transformers/mcp.ts +164 -0
- package/src/utils/transformers/toolRouterResponseTransform.ts +160 -0
- package/src/utils/transformers/toolkits.ts +100 -0
- package/src/utils/transformers/triggers.ts +118 -0
- package/src/utils/uploadDirAllowlist.node.ts +178 -0
- package/src/utils/uuid.ts +7 -0
- package/src/utils/version.ts +58 -0
- package/src/utils/zodSchema.ts +90 -0
|
@@ -0,0 +1,458 @@
|
|
|
1
|
+
/* eslint-disable-next-line no-restricted-imports */
|
|
2
|
+
import crypto from 'node:crypto'; // we're in a Node.js-specific module
|
|
3
|
+
import { platform } from '#platform';
|
|
4
|
+
import ComposioClient from '@composio/client';
|
|
5
|
+
import { COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME } from './constants';
|
|
6
|
+
import logger from './logger';
|
|
7
|
+
import { getRandomShortId } from './uuid';
|
|
8
|
+
import { base64ToUint8Array, uint8ArrayToBase64 } from './buffer';
|
|
9
|
+
import type { FileDownloadData, FileUploadData } from '../types/files.types';
|
|
10
|
+
import { assertSafeFileUploadPath } from './sensitiveFileUploadPaths.node';
|
|
11
|
+
import { assertPathInsideUploadDirs } from './uploadDirAllowlist.node';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Options for {@link getFileDataAfterUploadingToS3} (S3 presigned upload from local path, URL, or File).
|
|
15
|
+
*/
|
|
16
|
+
export type GetFileDataAfterUploadingToS3Options = {
|
|
17
|
+
toolSlug: string;
|
|
18
|
+
toolkitSlug: string;
|
|
19
|
+
client: ComposioClient;
|
|
20
|
+
/**
|
|
21
|
+
* When false, skips the sensitive-path blocklist. URLs and {@link File} objects are never checked.
|
|
22
|
+
* @default true
|
|
23
|
+
*/
|
|
24
|
+
sensitiveFileUploadProtection?: boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Extra path segments (one directory/file component) to block anywhere in the resolved path;
|
|
27
|
+
* merged with the built-in list.
|
|
28
|
+
*/
|
|
29
|
+
fileUploadPathDenySegments?: string[];
|
|
30
|
+
/**
|
|
31
|
+
* When provided, the local path must resolve inside one of these directories
|
|
32
|
+
* (after symlink resolution, on a component boundary) or upload is rejected.
|
|
33
|
+
* Intended for automatic upload during tool execution; manual
|
|
34
|
+
* `composio.files.upload()` calls pass `undefined` here to skip enforcement.
|
|
35
|
+
*
|
|
36
|
+
* An empty array means "no paths are allowed" (fail-closed).
|
|
37
|
+
*/
|
|
38
|
+
fileUploadAllowlist?: string[];
|
|
39
|
+
signal?: AbortSignal;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
// Helper function to get file extension from MIME type
|
|
43
|
+
const getExtensionFromMimeType = (mimeType: string): string => {
|
|
44
|
+
const mimeToExt: Record<string, string> = {
|
|
45
|
+
'text/plain': 'txt',
|
|
46
|
+
'text/html': 'html',
|
|
47
|
+
'text/css': 'css',
|
|
48
|
+
'text/javascript': 'js',
|
|
49
|
+
'application/json': 'json',
|
|
50
|
+
'application/xml': 'xml',
|
|
51
|
+
'application/pdf': 'pdf',
|
|
52
|
+
'application/zip': 'zip',
|
|
53
|
+
'application/x-zip-compressed': 'zip',
|
|
54
|
+
'application/gzip': 'gz',
|
|
55
|
+
'application/x-tar': 'tar',
|
|
56
|
+
'application/msword': 'doc',
|
|
57
|
+
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
|
|
58
|
+
'application/vnd.ms-excel': 'xls',
|
|
59
|
+
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',
|
|
60
|
+
'application/vnd.ms-powerpoint': 'ppt',
|
|
61
|
+
'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx',
|
|
62
|
+
'image/jpeg': 'jpg',
|
|
63
|
+
'image/jpg': 'jpg',
|
|
64
|
+
'image/png': 'png',
|
|
65
|
+
'image/gif': 'gif',
|
|
66
|
+
'image/svg+xml': 'svg',
|
|
67
|
+
'image/webp': 'webp',
|
|
68
|
+
'image/bmp': 'bmp',
|
|
69
|
+
'image/tiff': 'tiff',
|
|
70
|
+
'audio/mpeg': 'mp3',
|
|
71
|
+
'audio/wav': 'wav',
|
|
72
|
+
'audio/ogg': 'ogg',
|
|
73
|
+
'video/mp4': 'mp4',
|
|
74
|
+
'video/mpeg': 'mpeg',
|
|
75
|
+
'video/quicktime': 'mov',
|
|
76
|
+
'video/x-msvideo': 'avi',
|
|
77
|
+
'video/webm': 'webm',
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
// Clean the MIME type by removing parameters (e.g., "text/plain; charset=utf-8" -> "text/plain")
|
|
81
|
+
const cleanMimeType = mimeType.split(';')[0].toLowerCase().trim();
|
|
82
|
+
|
|
83
|
+
// Try exact match first
|
|
84
|
+
if (mimeToExt[cleanMimeType]) {
|
|
85
|
+
return mimeToExt[cleanMimeType];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Try to extract from the MIME type (e.g., "image/png" -> "png")
|
|
89
|
+
const parts = cleanMimeType.split('/');
|
|
90
|
+
if (parts.length === 2) {
|
|
91
|
+
const subtype = parts[1].toLowerCase();
|
|
92
|
+
const cleanSubtype = subtype; // Already cleaned above
|
|
93
|
+
|
|
94
|
+
// Handle structured MIME types with + (e.g., "application/vnd.api+json" -> "json")
|
|
95
|
+
if (cleanSubtype.includes('+')) {
|
|
96
|
+
const plusParts = cleanSubtype.split('+');
|
|
97
|
+
const prefix = plusParts[0];
|
|
98
|
+
const suffix = plusParts[plusParts.length - 1]; // Get the part after the last +
|
|
99
|
+
|
|
100
|
+
// For specific formats, prefer the prefix (e.g., "atom+xml" -> "atom")
|
|
101
|
+
const knownPrefixes = ['svg', 'atom', 'rss'];
|
|
102
|
+
if (knownPrefixes.includes(prefix)) {
|
|
103
|
+
return prefix;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// For common structured suffixes, use the suffix (e.g., "vnd.api+json" -> "json")
|
|
107
|
+
const structuredSuffixes = ['json', 'xml', 'yaml', 'zip', 'gzip'];
|
|
108
|
+
if (structuredSuffixes.includes(suffix)) {
|
|
109
|
+
return suffix;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Default to the suffix for other structured types
|
|
113
|
+
return suffix;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return cleanSubtype || 'txt';
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return 'txt'; // Default fallback
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
// Helper function to generate a filename with timestamp and random ID
|
|
123
|
+
const generateTimestampedFilename = (extension: string, prefix?: string): string => {
|
|
124
|
+
const basePrefix = prefix || 'file_ts';
|
|
125
|
+
return `${basePrefix}${Date.now()}${getRandomShortId()}.${extension}`;
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const readFileContent = async (
|
|
129
|
+
filePath: string
|
|
130
|
+
): Promise<{ fileName: string; content: string; mimeType: string }> => {
|
|
131
|
+
try {
|
|
132
|
+
if (!platform.supportsFileSystem) {
|
|
133
|
+
throw new Error('File system operations are not supported in this runtime environment');
|
|
134
|
+
}
|
|
135
|
+
const content = platform.readFileSync(filePath);
|
|
136
|
+
return {
|
|
137
|
+
fileName: generateTimestampedFilename(filePath.split('.').pop() || 'txt'),
|
|
138
|
+
content:
|
|
139
|
+
content instanceof Uint8Array
|
|
140
|
+
? uint8ArrayToBase64(content)
|
|
141
|
+
: uint8ArrayToBase64(new TextEncoder().encode(content)),
|
|
142
|
+
mimeType: 'application/octet-stream',
|
|
143
|
+
};
|
|
144
|
+
} catch (error) {
|
|
145
|
+
throw new Error(`Error reading file at ${filePath}: ${error}`);
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
const readFileContentFromURL = async (
|
|
150
|
+
path: string,
|
|
151
|
+
signal?: AbortSignal
|
|
152
|
+
): Promise<{ fileName: string; content: string; mimeType: string }> => {
|
|
153
|
+
const response = await fetch(path, { signal });
|
|
154
|
+
if (!response.ok) {
|
|
155
|
+
throw new Error(`Failed to fetch file: ${response.statusText}`);
|
|
156
|
+
}
|
|
157
|
+
const arrayBuffer = await response.arrayBuffer();
|
|
158
|
+
const content = new Uint8Array(arrayBuffer);
|
|
159
|
+
const mimeType = response.headers.get('content-type') || 'application/octet-stream';
|
|
160
|
+
|
|
161
|
+
// Extract clean filename from URL, removing query parameters
|
|
162
|
+
const url = new URL(path);
|
|
163
|
+
const pathname = url.pathname;
|
|
164
|
+
let fileName = platform.basename(pathname);
|
|
165
|
+
|
|
166
|
+
// If no filename from URL, generate one with appropriate extension
|
|
167
|
+
if (!fileName || fileName === '/') {
|
|
168
|
+
// Try to get extension from mimeType
|
|
169
|
+
const extension = getExtensionFromMimeType(mimeType);
|
|
170
|
+
fileName = generateTimestampedFilename(extension);
|
|
171
|
+
} else {
|
|
172
|
+
// If filename has no extension, try to add one from mimeType
|
|
173
|
+
const hasExtension = fileName.includes('.');
|
|
174
|
+
if (!hasExtension) {
|
|
175
|
+
const extension = getExtensionFromMimeType(mimeType);
|
|
176
|
+
fileName = generateTimestampedFilename(extension);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
return {
|
|
181
|
+
content: uint8ArrayToBase64(content),
|
|
182
|
+
mimeType,
|
|
183
|
+
fileName,
|
|
184
|
+
};
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
const uploadFileToS3 = async (
|
|
188
|
+
fileName: string,
|
|
189
|
+
content: string,
|
|
190
|
+
toolSlug: string,
|
|
191
|
+
toolkitSlug: string,
|
|
192
|
+
mimeType: string,
|
|
193
|
+
client: ComposioClient,
|
|
194
|
+
signal?: AbortSignal
|
|
195
|
+
): Promise<string> => {
|
|
196
|
+
const contentBytes = base64ToUint8Array(content);
|
|
197
|
+
const response = await client.files.createPresignedURL(
|
|
198
|
+
{
|
|
199
|
+
filename: fileName,
|
|
200
|
+
mimetype: mimeType,
|
|
201
|
+
md5: crypto.createHash('md5').update(contentBytes).digest('hex'),
|
|
202
|
+
tool_slug: toolSlug,
|
|
203
|
+
toolkit_slug: toolkitSlug,
|
|
204
|
+
},
|
|
205
|
+
{ signal }
|
|
206
|
+
);
|
|
207
|
+
|
|
208
|
+
const { key, new_presigned_url: signedURL } = response;
|
|
209
|
+
|
|
210
|
+
// Upload file using presigned URL
|
|
211
|
+
// Note: API now always returns type: 'new' with new_presigned_url
|
|
212
|
+
logger.debug(`Uploading ${key} file to S3: ${key}`);
|
|
213
|
+
|
|
214
|
+
// Create a new ArrayBuffer to ensure compatibility with fetch API
|
|
215
|
+
const uploadBuffer = new Uint8Array(contentBytes.byteLength);
|
|
216
|
+
uploadBuffer.set(contentBytes);
|
|
217
|
+
|
|
218
|
+
// Note: do not set `Content-Length` manually. Node.js's built-in fetch (undici)
|
|
219
|
+
// computes it from `body` and rejects any user-supplied value with
|
|
220
|
+
// `InvalidArgumentError: invalid content-length header`, which surfaces as
|
|
221
|
+
// `TypeError: fetch failed` and breaks every `file_uploadable` connector tool
|
|
222
|
+
// on Node 22+.
|
|
223
|
+
const uploadResponse = await fetch(signedURL, {
|
|
224
|
+
method: 'PUT',
|
|
225
|
+
body: uploadBuffer,
|
|
226
|
+
signal,
|
|
227
|
+
headers: {
|
|
228
|
+
'Content-Type': mimeType,
|
|
229
|
+
},
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
if (!uploadResponse.ok) {
|
|
233
|
+
throw new Error(`Failed to upload file to S3: ${uploadResponse.statusText}`);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
return key;
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
const readFile = async (
|
|
240
|
+
file: File | string,
|
|
241
|
+
signal?: AbortSignal
|
|
242
|
+
): Promise<{ fileName: string; content: string; mimeType: string }> => {
|
|
243
|
+
if (file instanceof File) {
|
|
244
|
+
const content = await file.arrayBuffer();
|
|
245
|
+
return {
|
|
246
|
+
fileName: file.name,
|
|
247
|
+
content: uint8ArrayToBase64(new Uint8Array(content)),
|
|
248
|
+
mimeType: file.type,
|
|
249
|
+
};
|
|
250
|
+
} else if (typeof file === 'string') {
|
|
251
|
+
if (file.startsWith('http')) {
|
|
252
|
+
return await readFileContentFromURL(file, signal);
|
|
253
|
+
} else {
|
|
254
|
+
return await readFileContent(file);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
throw new Error('Invalid file type');
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
export const getFileDataAfterUploadingToS3 = async (
|
|
261
|
+
file: File | string,
|
|
262
|
+
{
|
|
263
|
+
toolSlug,
|
|
264
|
+
toolkitSlug,
|
|
265
|
+
client,
|
|
266
|
+
sensitiveFileUploadProtection,
|
|
267
|
+
fileUploadPathDenySegments,
|
|
268
|
+
fileUploadAllowlist,
|
|
269
|
+
signal,
|
|
270
|
+
}: GetFileDataAfterUploadingToS3Options
|
|
271
|
+
): Promise<FileUploadData> => {
|
|
272
|
+
if (!file) {
|
|
273
|
+
throw new Error('Either path or blob must be provided');
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const isLocalPath = typeof file === 'string' && !file.startsWith('http');
|
|
277
|
+
|
|
278
|
+
if (isLocalPath && fileUploadAllowlist !== undefined) {
|
|
279
|
+
assertPathInsideUploadDirs(file as string, fileUploadAllowlist);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
if (sensitiveFileUploadProtection !== false && isLocalPath) {
|
|
283
|
+
assertSafeFileUploadPath(file as string, {
|
|
284
|
+
additionalDenySegments: fileUploadPathDenySegments,
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const fileData = await readFile(file, signal);
|
|
289
|
+
logger.debug(`Uploading file to S3...`);
|
|
290
|
+
const s3key = await uploadFileToS3(
|
|
291
|
+
platform.basename(fileData.fileName),
|
|
292
|
+
fileData.content,
|
|
293
|
+
toolSlug,
|
|
294
|
+
toolkitSlug,
|
|
295
|
+
fileData.mimeType,
|
|
296
|
+
client,
|
|
297
|
+
signal
|
|
298
|
+
);
|
|
299
|
+
|
|
300
|
+
logger.debug(`Done! File uploaded to S3: ${s3key}`, JSON.stringify(fileData, null, 2));
|
|
301
|
+
return {
|
|
302
|
+
name: fileData.fileName,
|
|
303
|
+
mimetype: fileData.mimeType,
|
|
304
|
+
s3key: s3key,
|
|
305
|
+
};
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
export const downloadFileFromS3 = async ({
|
|
309
|
+
toolSlug,
|
|
310
|
+
s3Url,
|
|
311
|
+
mimeType,
|
|
312
|
+
fileDownloadDir,
|
|
313
|
+
signal,
|
|
314
|
+
}: {
|
|
315
|
+
toolSlug: string;
|
|
316
|
+
s3Url: string;
|
|
317
|
+
mimeType: string;
|
|
318
|
+
/**
|
|
319
|
+
* Absolute path to the directory to save the file into. When omitted, falls
|
|
320
|
+
* back to `<home>/.composio/files` (the legacy default).
|
|
321
|
+
*/
|
|
322
|
+
fileDownloadDir?: string;
|
|
323
|
+
signal?: AbortSignal;
|
|
324
|
+
}): Promise<FileDownloadData> => {
|
|
325
|
+
const response = await fetch(s3Url, { signal });
|
|
326
|
+
if (!response.ok) {
|
|
327
|
+
throw new Error(`Failed to download file: ${response.statusText}`);
|
|
328
|
+
}
|
|
329
|
+
const data = await response.arrayBuffer();
|
|
330
|
+
|
|
331
|
+
const extension = getExtensionFromMimeType(mimeType);
|
|
332
|
+
const fileName = generateTimestampedFilename(extension, `${toolSlug}_`);
|
|
333
|
+
const filePath = saveFile(fileName, new Uint8Array(data), {
|
|
334
|
+
isTempFile: fileDownloadDir === undefined,
|
|
335
|
+
outputDir: fileDownloadDir,
|
|
336
|
+
});
|
|
337
|
+
return {
|
|
338
|
+
name: fileName,
|
|
339
|
+
mimeType: mimeType,
|
|
340
|
+
s3Url: s3Url,
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* @todo: fix in follow-up PR.
|
|
344
|
+
*/
|
|
345
|
+
filePath: filePath as string,
|
|
346
|
+
};
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Gets the Composio directory.
|
|
351
|
+
* @param createDirIfNotExists - Whether to create the directory if it doesn't exist.
|
|
352
|
+
* @returns The path to the Composio directory.
|
|
353
|
+
*/
|
|
354
|
+
export const getComposioDir = (createDirIfNotExists: boolean = false) => {
|
|
355
|
+
try {
|
|
356
|
+
const homeDir = platform.homedir();
|
|
357
|
+
if (!homeDir) {
|
|
358
|
+
return null;
|
|
359
|
+
}
|
|
360
|
+
const composioDir = platform.joinPath(homeDir, COMPOSIO_DIR);
|
|
361
|
+
if (createDirIfNotExists && platform.supportsFileSystem && !platform.existsSync(composioDir)) {
|
|
362
|
+
platform.mkdirSync(composioDir);
|
|
363
|
+
}
|
|
364
|
+
return composioDir;
|
|
365
|
+
} catch (_error) {
|
|
366
|
+
return null;
|
|
367
|
+
}
|
|
368
|
+
};
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Gets the Composio temporary files directory.
|
|
372
|
+
* @param createDirIfNotExists - Whether to create the directory if it doesn't exist.
|
|
373
|
+
* @returns The path to the Composio temporary files directory.
|
|
374
|
+
*/
|
|
375
|
+
export const getComposioTempFilesDir = (createDirIfNotExists: boolean = false) => {
|
|
376
|
+
try {
|
|
377
|
+
const homeDir = platform.homedir();
|
|
378
|
+
if (!homeDir) {
|
|
379
|
+
return null;
|
|
380
|
+
}
|
|
381
|
+
const composioFilesDir = platform.joinPath(homeDir, COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME);
|
|
382
|
+
if (
|
|
383
|
+
createDirIfNotExists &&
|
|
384
|
+
platform.supportsFileSystem &&
|
|
385
|
+
!platform.existsSync(composioFilesDir)
|
|
386
|
+
) {
|
|
387
|
+
platform.mkdirSync(composioFilesDir);
|
|
388
|
+
}
|
|
389
|
+
return composioFilesDir;
|
|
390
|
+
} catch (_error) {
|
|
391
|
+
return null;
|
|
392
|
+
}
|
|
393
|
+
};
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Saves a file to a local directory.
|
|
397
|
+
*
|
|
398
|
+
* Directory precedence (highest first):
|
|
399
|
+
* 1. `options.outputDir` (explicit, absolute or relative; created if missing)
|
|
400
|
+
* 2. `options.isTempFile === true` → `<home>/.composio/files`
|
|
401
|
+
* 3. fallback → `<home>/.composio`
|
|
402
|
+
*
|
|
403
|
+
* @returns The absolute path to the saved file, or `null` if the runtime has
|
|
404
|
+
* no filesystem (e.g. Cloudflare Workers) or the save failed.
|
|
405
|
+
*/
|
|
406
|
+
export const saveFile = (
|
|
407
|
+
file: string,
|
|
408
|
+
content: string | Uint8Array,
|
|
409
|
+
options: { isTempFile?: boolean; outputDir?: string } | boolean = {}
|
|
410
|
+
) => {
|
|
411
|
+
// Back-compat: legacy callers passed a boolean `isTempFile` positional.
|
|
412
|
+
const opts: { isTempFile?: boolean; outputDir?: string } =
|
|
413
|
+
typeof options === 'boolean' ? { isTempFile: options } : options;
|
|
414
|
+
|
|
415
|
+
try {
|
|
416
|
+
if (!platform.supportsFileSystem) {
|
|
417
|
+
logger.debug('File system operations are not supported in this runtime environment');
|
|
418
|
+
return null;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
let composioFilesDir: string | null | undefined;
|
|
422
|
+
if (opts.outputDir) {
|
|
423
|
+
const absDir = platform.joinPath(opts.outputDir); // platform.joinPath normalizes
|
|
424
|
+
try {
|
|
425
|
+
if (!platform.existsSync(absDir)) {
|
|
426
|
+
platform.mkdirSync(absDir);
|
|
427
|
+
}
|
|
428
|
+
composioFilesDir = absDir;
|
|
429
|
+
} catch (err) {
|
|
430
|
+
logger.warn(
|
|
431
|
+
`fileDownloadDir "${absDir}" is not writable, falling back to the default ` +
|
|
432
|
+
`(~/.composio/files). Error: ${err}`
|
|
433
|
+
);
|
|
434
|
+
composioFilesDir = getComposioTempFilesDir(true);
|
|
435
|
+
}
|
|
436
|
+
} else {
|
|
437
|
+
composioFilesDir = opts.isTempFile ? getComposioTempFilesDir(true) : getComposioDir(true);
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
if (!composioFilesDir) {
|
|
441
|
+
return null;
|
|
442
|
+
}
|
|
443
|
+
const filePath = platform.joinPath(composioFilesDir, platform.basename(file));
|
|
444
|
+
|
|
445
|
+
logger.info(`Saving file to: ${filePath}`);
|
|
446
|
+
|
|
447
|
+
if (content instanceof Uint8Array) {
|
|
448
|
+
platform.writeFileSync(filePath, content);
|
|
449
|
+
} else {
|
|
450
|
+
platform.writeFileSync(filePath, content, 'utf8');
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
return filePath;
|
|
454
|
+
} catch (_error) {
|
|
455
|
+
logger.debug(`Error saving file: ${_error}`);
|
|
456
|
+
return null;
|
|
457
|
+
}
|
|
458
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { jsonSchemaToZodShape } from '@composio/json-schema-to-zod';
|