@composio/core 0.10.0 → 0.12.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 (69) hide show
  1. package/dist/{tool.types-CwbAy9l_.d.cts → BaseProvider-BBnsv9kS.d.mts} +23683 -23635
  2. package/dist/CustomTool-DEB4BQPl.mjs +468 -0
  3. package/dist/{CustomTool-aber890o.d.cts → CustomTool-DH18rVQu.d.mts} +2 -4
  4. package/dist/{FileModifierErrors-C7z16Dfi.mjs → FileModifierErrors-3fSwIWoa.mjs} +35 -36
  5. package/dist/{FileToolModifier.utils.neutral-B7P7wn-b.mjs → FileToolModifier.utils.neutral-B5rT711M.mjs} +1 -7
  6. package/dist/{Telemetry-kgWlkavX.mjs → Telemetry-DhGI_J4G.mjs} +48 -23
  7. package/dist/{composio-CSMCZZgj.d.cts → composio-CHnEggnv.d.mts} +433 -435
  8. package/dist/{customTool.types-BzEWHa0w.d.cts → customTool.types-DpIdOJjL.d.mts} +177 -236
  9. package/dist/{CustomTool-D7-1S2at.mjs → errors-D5f4pfvI.mjs} +132 -519
  10. package/dist/experimental/index.d.mts +2 -3
  11. package/dist/experimental/index.mjs +1 -3
  12. package/dist/{fileUtils.node-Dq7ebZPC.mjs → fileUtils.node-BiO1JQsJ.mjs} +26 -25
  13. package/dist/index.d.mts +2034 -2356
  14. package/dist/index.mjs +2546 -2335
  15. package/dist/jsonSchema-daqF3S3d.mjs +251 -0
  16. package/dist/models/Files.node.d.mts +1 -2
  17. package/dist/models/Files.node.mjs +3 -4
  18. package/dist/models/Files.workerd.d.mts +0 -1
  19. package/dist/platform/node.d.mts +1 -2
  20. package/dist/platform/workerd.d.mts +1 -2
  21. package/dist/{chunk-CWQeghP5.mjs → rolldown-runtime-w6R9maHv.mjs} +3 -5
  22. package/dist/{types-DE7O6Z6S.d.cts → types-CaI5Z4PA.d.mts} +2 -3
  23. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -4
  24. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -4
  25. package/dist/utils/config-defaults/ConfigDefaults.workerd.mjs +3 -0
  26. package/dist/utils/json-schema.d.mts +2 -0
  27. package/dist/utils/json-schema.mjs +3 -0
  28. package/dist/utils/modifiers/FileToolModifier.node.d.mts +3 -1
  29. package/dist/utils/modifiers/FileToolModifier.node.mjs +81 -44
  30. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +3 -1
  31. package/dist/utils/modifiers/FileToolModifier.workerd.mjs +1 -1
  32. package/package.json +48 -88
  33. package/dist/CustomTool-CQ_YjABZ.cjs +0 -1341
  34. package/dist/CustomTool-DJUGNOer.d.mts +0 -76
  35. package/dist/FileModifierErrors-BYJBHiay.cjs +0 -554
  36. package/dist/FileToolModifier.utils.neutral-Dfwqgimk.cjs +0 -102
  37. package/dist/Telemetry-Dm-0sewu.cjs +0 -335
  38. package/dist/buffer-BjWptbNH.cjs +0 -63
  39. package/dist/chunk-CQwRTUmo.cjs +0 -53
  40. package/dist/composio-DRl6WCI9.d.mts +0 -5484
  41. package/dist/customTool.types-CMOMgxoM.d.mts +0 -2513
  42. package/dist/experimental/index.cjs +0 -5
  43. package/dist/experimental/index.d.cts +0 -3
  44. package/dist/fileUtils.node-DtnSRMWa.cjs +0 -462
  45. package/dist/files.types-lo4zZd87.d.cts +0 -17
  46. package/dist/index.cjs +0 -8637
  47. package/dist/index.d.cts +0 -5672
  48. package/dist/models/Files.node.cjs +0 -55
  49. package/dist/models/Files.node.d.cts +0 -56
  50. package/dist/models/Files.workerd.cjs +0 -29
  51. package/dist/models/Files.workerd.d.cts +0 -13
  52. package/dist/platform/node.cjs +0 -55
  53. package/dist/platform/node.d.cts +0 -11
  54. package/dist/platform/workerd.cjs +0 -42
  55. package/dist/platform/workerd.d.cts +0 -12
  56. package/dist/tool.types-CB_4JKhV.d.mts +0 -29377
  57. package/dist/types-BTOPdg4d.d.mts +0 -13
  58. package/dist/types-pDNm1lYs.d.cts +0 -69
  59. package/dist/utils/config-defaults/ConfigDefaults.node.cjs +0 -10
  60. package/dist/utils/config-defaults/ConfigDefaults.node.d.cts +0 -7
  61. package/dist/utils/config-defaults/ConfigDefaults.workerd.cjs +0 -10
  62. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.cts +0 -7
  63. package/dist/utils/modifiers/FileToolModifier.node.cjs +0 -207
  64. package/dist/utils/modifiers/FileToolModifier.node.d.cts +0 -22
  65. package/dist/utils/modifiers/FileToolModifier.workerd.cjs +0 -27
  66. package/dist/utils/modifiers/FileToolModifier.workerd.d.cts +0 -20
  67. /package/dist/{buffer-yOtEsT4J.mjs → buffer-PcbMMsgm.mjs} +0 -0
  68. /package/dist/{files.types-BXDWA_zS.d.mts → files.types-DeMC_mAW.d.mts} +0 -0
  69. /package/dist/{types-HpJQ8K9l.d.mts → types-DdoCRzLj.d.mts} +0 -0
@@ -1,5 +0,0 @@
1
- require('../FileModifierErrors-BYJBHiay.cjs');
2
- const require_CustomTool = require('../CustomTool-CQ_YjABZ.cjs');
3
-
4
- exports.experimental_createTool = require_CustomTool.createCustomTool;
5
- exports.experimental_createToolkit = require_CustomTool.createCustomToolkit;
@@ -1,3 +0,0 @@
1
- import { E as SessionContext, a as CustomTool, h as CustomToolkit, i as CreateCustomToolkitParams, n as CreateCustomToolParams, s as CustomToolExecuteFn } from "../customTool.types-BzEWHa0w.cjs";
2
- import { n as createCustomToolkit, t as createCustomTool } from "../CustomTool-aber890o.cjs";
3
- export { type CreateCustomToolParams, type CreateCustomToolkitParams, type CustomTool, type CustomToolExecuteFn, type CustomToolkit, type SessionContext, createCustomTool as experimental_createTool, createCustomToolkit as experimental_createToolkit };
@@ -1,462 +0,0 @@
1
- const require_chunk = require('./chunk-CQwRTUmo.cjs');
2
- const require_FileModifierErrors = require('./FileModifierErrors-BYJBHiay.cjs');
3
- const require_buffer = require('./buffer-BjWptbNH.cjs');
4
- let _platform = require("#platform");
5
- let node_fs = require("node:fs");
6
- node_fs = require_chunk.__toESM(node_fs);
7
- let node_path = require("node:path");
8
- node_path = require_chunk.__toESM(node_path);
9
- let node_crypto = require("node:crypto");
10
- node_crypto = require_chunk.__toESM(node_crypto);
11
-
12
- //#region src/utils/sensitiveFileUploadPaths.node.ts
13
- /**
14
- * Blocks accidental upload of local files from well-known secret/credential locations
15
- * during auto file upload (and {@link getFileDataAfterUploadingToS3}).
16
- */
17
- /**
18
- * Path segments (a single path component) that indicate a sensitive directory when
19
- * they appear anywhere in a resolved local path. Compared case-insensitively on Windows.
20
- */
21
- const BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS = [
22
- ".ssh",
23
- ".aws",
24
- ".azure",
25
- ".gnupg",
26
- ".kube",
27
- ".docker",
28
- ".claude",
29
- ".password-store",
30
- "keychains"
31
- ];
32
- const SECRET_LIKE_BASENAME = /^(\.env(\.|$)|\.netrc$|\.pgpass$)/i;
33
- /** Default SSH private key basenames (public keys like id_rsa.pub are allowed). */
34
- const DEFAULT_PRIVATE_KEY_BASENAME = /^id_(rsa|ed25519|ecdsa|dsa|ecdsa_sk)(\.old)?$/i;
35
- /**
36
- * Returns normalized path segments, resolving symlinks when the path exists.
37
- */
38
- function normalizePathSegments(filePath) {
39
- const absolute = node_path.resolve(filePath);
40
- let resolved = absolute;
41
- try {
42
- if (node_fs.default.existsSync(absolute)) resolved = node_fs.default.realpathSync(absolute);
43
- } catch {}
44
- return resolved.split(/[/\\]+/).filter(Boolean);
45
- }
46
- function getSensitiveFileUploadPathBlockReason(filePath, additionalDenySegments) {
47
- const segments = normalizePathSegments(filePath);
48
- const isWin = process.platform === "win32";
49
- const deny = new Set([...BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS, ...(additionalDenySegments ?? []).map((s) => s.trim()).filter(Boolean)].map((s) => isWin ? s.toLowerCase() : s));
50
- const segmentsForMatch = isWin ? segments.map((s) => s.toLowerCase()) : segments;
51
- for (let i = 0; i < segments.length; i++) if (deny.has(segmentsForMatch[i])) return `path segment "${segments[i]}" is in the sensitive file upload denylist`;
52
- const basename = segments.length > 0 ? segments[segments.length - 1] : "";
53
- if (basename) {
54
- if (SECRET_LIKE_BASENAME.test(basename) || DEFAULT_PRIVATE_KEY_BASENAME.test(basename)) return `file name "${basename}" looks like a credential, env, or private key file`;
55
- if (basename.toLowerCase() === "credentials") return "file name \"credentials\" is often used for cloud/API credential stores";
56
- }
57
- return null;
58
- }
59
- /**
60
- * @throws {ComposioSensitiveFilePathBlockedError} if the path is not allowed
61
- */
62
- function assertSafeFileUploadPath(filePath, options) {
63
- const reason = getSensitiveFileUploadPathBlockReason(filePath, options?.additionalDenySegments);
64
- if (reason) throw new require_FileModifierErrors.ComposioSensitiveFilePathBlockedError(`Refusing to upload: ${reason}. To upload from this path anyway, set sensitiveFileUploadProtection: false on Composio (not recommended) or use a copy outside sensitive locations.`, { meta: {
65
- filePath,
66
- reason
67
- } });
68
- }
69
-
70
- //#endregion
71
- //#region src/utils/uploadDirAllowlist.node.ts
72
- /**
73
- * Allowlist for automatic file upload during tool execution.
74
- *
75
- * This is only consulted when `dangerouslyAllowAutoUploadDownloadFiles` is enabled.
76
- * Manual `composio.files.upload()` calls are not subject to the allowlist.
77
- *
78
- * - A local path is accepted iff its real (symlink-resolved, absolute) path is
79
- * inside one of the allowed directories on a path-component boundary.
80
- * `/tmp/foo` allows `/tmp/foo/bar` but NOT `/tmp/foo-bar`.
81
- * - URLs (`http(s)://…`) and `File`/`Blob` values never hit this check.
82
- * - User-provided `fileUploadDirs` fully replaces the default `[~/.composio/temp]`.
83
- * - On Windows, path comparisons are case-insensitive.
84
- */
85
- function normalizeForCompare(p) {
86
- return process.platform === "win32" ? p.toLowerCase() : p;
87
- }
88
- /**
89
- * True if `child` is equal to `parent` or nested inside it on a component
90
- * boundary. Assumes both paths are absolute and normalized.
91
- */
92
- function isInsideDir(child, parent) {
93
- const a = normalizeForCompare(child);
94
- const b = normalizeForCompare(parent);
95
- if (a === b) return true;
96
- const sep = node_path.sep;
97
- const bWithSep = b.endsWith(sep) ? b : b + sep;
98
- return a.startsWith(bWithSep);
99
- }
100
- /**
101
- * Returns the real (symlink-resolved) absolute path when the target exists,
102
- * else `null`. Mirrors the semantics of the sensitive-path util.
103
- */
104
- function tryRealpath(absPath) {
105
- try {
106
- if (node_fs.default.existsSync(absPath)) return node_fs.default.realpathSync(absPath);
107
- } catch {}
108
- return null;
109
- }
110
- function formatAllowlist(dirs) {
111
- if (dirs.length === 0) return " (none configured — all local paths are blocked)";
112
- return dirs.map((d) => ` - ${d}`).join("\n");
113
- }
114
- function buildHelpFooter(allowlist) {
115
- return [
116
- "",
117
- "Allowed upload directories (fileUploadDirs):",
118
- formatAllowlist(allowlist),
119
- "",
120
- "Fix one of the following:",
121
- "",
122
- " 1. Recommended — move the file under an allowed directory, or add your",
123
- " directory to the allowlist:",
124
- " new Composio({",
125
- " fileUploadDirs: ['/abs/path/to/uploads', '~/.composio/temp'],",
126
- " })",
127
- " Note: user-provided `fileUploadDirs` REPLACES the default",
128
- " `~/.composio/temp`. Include it explicitly if you want staged uploads",
129
- " to keep working.",
130
- "",
131
- " 2. Pass the file by URL or as a File/Blob object instead of a filesystem",
132
- " path. URLs and File objects are never path-checked.",
133
- "",
134
- " 3. (Dangerous) Bypass the allowlist entirely by opting into automatic",
135
- " file upload/download from any readable path:",
136
- " new Composio({ dangerouslyAllowAutoUploadDownloadFiles: true })",
137
- " WARNING: This lets a prompt-injected or misbehaving tool read ANY",
138
- " file the process can access. Only enable it in trusted, sandboxed",
139
- " environments. The built-in sensitive-path denylist (.ssh, .aws,",
140
- " .env, private SSH keys, etc.) still applies unless you also set",
141
- " `sensitiveFileUploadProtection: false`."
142
- ].join("\n");
143
- }
144
- /**
145
- * @throws {ComposioFileNotFoundError} when `filePath` does not exist on disk.
146
- * @throws {ComposioFileUploadPathNotAllowedError} when the resolved path is
147
- * outside every entry of `allowlist`.
148
- */
149
- function assertPathInsideUploadDirs(filePath, allowlist) {
150
- const attempted = filePath;
151
- const abs = node_path.resolve(filePath);
152
- const real = tryRealpath(abs);
153
- if (!real) {
154
- const cwd = process.cwd();
155
- const parent = node_path.dirname(abs);
156
- const parentExists = (() => {
157
- try {
158
- return node_fs.default.existsSync(parent);
159
- } catch {
160
- return false;
161
- }
162
- })();
163
- throw new require_FileModifierErrors.ComposioFileNotFoundError([
164
- `Refusing to auto-upload "${attempted}": the file does not exist on disk.`,
165
- "",
166
- `Path attempted: ${attempted}`,
167
- `Resolved to: ${abs}`,
168
- `Process cwd: ${cwd}`,
169
- `Parent exists: ${parentExists ? "yes (" + parent + ")" : "no (" + parent + ")"}`,
170
- "",
171
- "Common causes:",
172
- " - Typo in the filename passed to the tool.",
173
- " - Relative path resolved against the wrong working directory",
174
- " (relative paths use process.cwd() at the moment of upload).",
175
- " - File was deleted between the tool being called and the upload starting.",
176
- "",
177
- buildHelpFooter(allowlist)
178
- ].join("\n"), { meta: {
179
- attempted,
180
- resolved: abs,
181
- cwd,
182
- allowlist
183
- } });
184
- }
185
- if (allowlist.length === 0) throw new require_FileModifierErrors.ComposioFileUploadPathNotAllowedError([
186
- `Refusing to auto-upload "${attempted}": no upload directories are configured.`,
187
- "",
188
- `Path attempted: ${attempted}`,
189
- `Resolved to: ${real}`,
190
- "",
191
- "Automatic file upload during tool execution is locked down by default",
192
- "to prevent a prompt-injected tool from exfiltrating server files",
193
- "(source code, .env, SSH keys, etc.).",
194
- buildHelpFooter(allowlist)
195
- ].join("\n"), { meta: {
196
- attempted,
197
- resolved: real,
198
- allowlist
199
- } });
200
- for (const dir of allowlist) if (isInsideDir(real, tryRealpath(dir) ?? node_path.resolve(dir))) return;
201
- throw new require_FileModifierErrors.ComposioFileUploadPathNotAllowedError([
202
- `Refusing to auto-upload "${attempted}": resolved path is not inside any`,
203
- "directory in the configured `fileUploadDirs` allowlist.",
204
- "",
205
- `Path attempted: ${attempted}`,
206
- `Resolved to: ${real}`,
207
- buildHelpFooter(allowlist)
208
- ].join("\n"), { meta: {
209
- attempted,
210
- resolved: real,
211
- allowlist
212
- } });
213
- }
214
-
215
- //#endregion
216
- //#region src/utils/fileUtils.node.ts
217
- const getExtensionFromMimeType = (mimeType) => {
218
- const mimeToExt = {
219
- "text/plain": "txt",
220
- "text/html": "html",
221
- "text/css": "css",
222
- "text/javascript": "js",
223
- "application/json": "json",
224
- "application/xml": "xml",
225
- "application/pdf": "pdf",
226
- "application/zip": "zip",
227
- "application/x-zip-compressed": "zip",
228
- "application/gzip": "gz",
229
- "application/x-tar": "tar",
230
- "application/msword": "doc",
231
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
232
- "application/vnd.ms-excel": "xls",
233
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
234
- "application/vnd.ms-powerpoint": "ppt",
235
- "application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",
236
- "image/jpeg": "jpg",
237
- "image/jpg": "jpg",
238
- "image/png": "png",
239
- "image/gif": "gif",
240
- "image/svg+xml": "svg",
241
- "image/webp": "webp",
242
- "image/bmp": "bmp",
243
- "image/tiff": "tiff",
244
- "audio/mpeg": "mp3",
245
- "audio/wav": "wav",
246
- "audio/ogg": "ogg",
247
- "video/mp4": "mp4",
248
- "video/mpeg": "mpeg",
249
- "video/quicktime": "mov",
250
- "video/x-msvideo": "avi",
251
- "video/webm": "webm"
252
- };
253
- const cleanMimeType = mimeType.split(";")[0].toLowerCase().trim();
254
- if (mimeToExt[cleanMimeType]) return mimeToExt[cleanMimeType];
255
- const parts = cleanMimeType.split("/");
256
- if (parts.length === 2) {
257
- const cleanSubtype = parts[1].toLowerCase();
258
- if (cleanSubtype.includes("+")) {
259
- const plusParts = cleanSubtype.split("+");
260
- const prefix = plusParts[0];
261
- const suffix = plusParts[plusParts.length - 1];
262
- if ([
263
- "svg",
264
- "atom",
265
- "rss"
266
- ].includes(prefix)) return prefix;
267
- if ([
268
- "json",
269
- "xml",
270
- "yaml",
271
- "zip",
272
- "gzip"
273
- ].includes(suffix)) return suffix;
274
- return suffix;
275
- }
276
- return cleanSubtype || "txt";
277
- }
278
- return "txt";
279
- };
280
- const generateTimestampedFilename = (extension, prefix) => {
281
- return `${prefix || "file_ts"}${Date.now()}${require_buffer.getRandomShortId()}.${extension}`;
282
- };
283
- const readFileContent = async (filePath) => {
284
- try {
285
- if (!_platform.platform.supportsFileSystem) throw new Error("File system operations are not supported in this runtime environment");
286
- const content = _platform.platform.readFileSync(filePath);
287
- return {
288
- fileName: generateTimestampedFilename(filePath.split(".").pop() || "txt"),
289
- content: content instanceof Uint8Array ? require_buffer.uint8ArrayToBase64(content) : require_buffer.uint8ArrayToBase64(new TextEncoder().encode(content)),
290
- mimeType: "application/octet-stream"
291
- };
292
- } catch (error) {
293
- throw new Error(`Error reading file at ${filePath}: ${error}`);
294
- }
295
- };
296
- const readFileContentFromURL = async (path) => {
297
- const response = await fetch(path);
298
- if (!response.ok) throw new Error(`Failed to fetch file: ${response.statusText}`);
299
- const arrayBuffer = await response.arrayBuffer();
300
- const content = new Uint8Array(arrayBuffer);
301
- const mimeType = response.headers.get("content-type") || "application/octet-stream";
302
- const pathname = new URL(path).pathname;
303
- let fileName = _platform.platform.basename(pathname);
304
- if (!fileName || fileName === "/") fileName = generateTimestampedFilename(getExtensionFromMimeType(mimeType));
305
- else if (!fileName.includes(".")) fileName = generateTimestampedFilename(getExtensionFromMimeType(mimeType));
306
- return {
307
- content: require_buffer.uint8ArrayToBase64(content),
308
- mimeType,
309
- fileName
310
- };
311
- };
312
- const uploadFileToS3 = async (fileName, content, toolSlug, toolkitSlug, mimeType, client) => {
313
- const contentBytes = require_buffer.base64ToUint8Array(content);
314
- const { key, new_presigned_url: signedURL } = await client.files.createPresignedURL({
315
- filename: fileName,
316
- mimetype: mimeType,
317
- md5: node_crypto.default.createHash("md5").update(contentBytes).digest("hex"),
318
- tool_slug: toolSlug,
319
- toolkit_slug: toolkitSlug
320
- });
321
- require_FileModifierErrors.logger_default.debug(`Uploading ${key} file to S3: ${key}`);
322
- const uploadBuffer = new Uint8Array(contentBytes.byteLength);
323
- uploadBuffer.set(contentBytes);
324
- const uploadResponse = await fetch(signedURL, {
325
- method: "PUT",
326
- body: uploadBuffer,
327
- headers: {
328
- "Content-Type": mimeType,
329
- "Content-Length": contentBytes.length.toString()
330
- }
331
- });
332
- if (!uploadResponse.ok) throw new Error(`Failed to upload file to S3: ${uploadResponse.statusText}`);
333
- return key;
334
- };
335
- const readFile = async (file) => {
336
- if (file instanceof File) {
337
- const content = await file.arrayBuffer();
338
- return {
339
- fileName: file.name,
340
- content: require_buffer.uint8ArrayToBase64(new Uint8Array(content)),
341
- mimeType: file.type
342
- };
343
- } else if (typeof file === "string") if (file.startsWith("http")) return await readFileContentFromURL(file);
344
- else return await readFileContent(file);
345
- throw new Error("Invalid file type");
346
- };
347
- const getFileDataAfterUploadingToS3 = async (file, { toolSlug, toolkitSlug, client, sensitiveFileUploadProtection, fileUploadPathDenySegments, fileUploadAllowlist }) => {
348
- if (!file) throw new Error("Either path or blob must be provided");
349
- const isLocalPath = typeof file === "string" && !file.startsWith("http");
350
- if (isLocalPath && fileUploadAllowlist !== void 0) assertPathInsideUploadDirs(file, fileUploadAllowlist);
351
- if (sensitiveFileUploadProtection !== false && isLocalPath) assertSafeFileUploadPath(file, { additionalDenySegments: fileUploadPathDenySegments });
352
- const fileData = await readFile(file);
353
- require_FileModifierErrors.logger_default.debug(`Uploading file to S3...`);
354
- const s3key = await uploadFileToS3(_platform.platform.basename(fileData.fileName), fileData.content, toolSlug, toolkitSlug, fileData.mimeType, client);
355
- require_FileModifierErrors.logger_default.debug(`Done! File uploaded to S3: ${s3key}`, JSON.stringify(fileData, null, 2));
356
- return {
357
- name: fileData.fileName,
358
- mimetype: fileData.mimeType,
359
- s3key
360
- };
361
- };
362
- const downloadFileFromS3 = async ({ toolSlug, s3Url, mimeType, fileDownloadDir }) => {
363
- const response = await fetch(s3Url);
364
- if (!response.ok) throw new Error(`Failed to download file: ${response.statusText}`);
365
- const data = await response.arrayBuffer();
366
- const fileName = generateTimestampedFilename(getExtensionFromMimeType(mimeType), `${toolSlug}_`);
367
- return {
368
- name: fileName,
369
- mimeType,
370
- s3Url,
371
- filePath: saveFile(fileName, new Uint8Array(data), {
372
- isTempFile: fileDownloadDir === void 0,
373
- outputDir: fileDownloadDir
374
- })
375
- };
376
- };
377
- /**
378
- * Gets the Composio directory.
379
- * @param createDirIfNotExists - Whether to create the directory if it doesn't exist.
380
- * @returns The path to the Composio directory.
381
- */
382
- const getComposioDir = (createDirIfNotExists = false) => {
383
- try {
384
- const homeDir = _platform.platform.homedir();
385
- if (!homeDir) return null;
386
- const composioDir = _platform.platform.joinPath(homeDir, require_FileModifierErrors.COMPOSIO_DIR);
387
- if (createDirIfNotExists && _platform.platform.supportsFileSystem && !_platform.platform.existsSync(composioDir)) _platform.platform.mkdirSync(composioDir);
388
- return composioDir;
389
- } catch (_error) {
390
- return null;
391
- }
392
- };
393
- /**
394
- * Gets the Composio temporary files directory.
395
- * @param createDirIfNotExists - Whether to create the directory if it doesn't exist.
396
- * @returns The path to the Composio temporary files directory.
397
- */
398
- const getComposioTempFilesDir = (createDirIfNotExists = false) => {
399
- try {
400
- const homeDir = _platform.platform.homedir();
401
- if (!homeDir) return null;
402
- const composioFilesDir = _platform.platform.joinPath(homeDir, require_FileModifierErrors.COMPOSIO_DIR, require_FileModifierErrors.TEMP_FILES_DIRECTORY_NAME);
403
- if (createDirIfNotExists && _platform.platform.supportsFileSystem && !_platform.platform.existsSync(composioFilesDir)) _platform.platform.mkdirSync(composioFilesDir);
404
- return composioFilesDir;
405
- } catch (_error) {
406
- return null;
407
- }
408
- };
409
- /**
410
- * Saves a file to a local directory.
411
- *
412
- * Directory precedence (highest first):
413
- * 1. `options.outputDir` (explicit, absolute or relative; created if missing)
414
- * 2. `options.isTempFile === true` → `<home>/.composio/files`
415
- * 3. fallback → `<home>/.composio`
416
- *
417
- * @returns The absolute path to the saved file, or `null` if the runtime has
418
- * no filesystem (e.g. Cloudflare Workers) or the save failed.
419
- */
420
- const saveFile = (file, content, options = {}) => {
421
- const opts = typeof options === "boolean" ? { isTempFile: options } : options;
422
- try {
423
- if (!_platform.platform.supportsFileSystem) {
424
- require_FileModifierErrors.logger_default.debug("File system operations are not supported in this runtime environment");
425
- return null;
426
- }
427
- let composioFilesDir;
428
- if (opts.outputDir) {
429
- const absDir = _platform.platform.joinPath(opts.outputDir);
430
- try {
431
- if (!_platform.platform.existsSync(absDir)) _platform.platform.mkdirSync(absDir);
432
- composioFilesDir = absDir;
433
- } catch (err) {
434
- require_FileModifierErrors.logger_default.warn(`fileDownloadDir "${absDir}" is not writable, falling back to the default (~/.composio/files). Error: ${err}`);
435
- composioFilesDir = getComposioTempFilesDir(true);
436
- }
437
- } else composioFilesDir = opts.isTempFile ? getComposioTempFilesDir(true) : getComposioDir(true);
438
- if (!composioFilesDir) return null;
439
- const filePath = _platform.platform.joinPath(composioFilesDir, _platform.platform.basename(file));
440
- require_FileModifierErrors.logger_default.info(`Saving file to: ${filePath}`);
441
- if (content instanceof Uint8Array) _platform.platform.writeFileSync(filePath, content);
442
- else _platform.platform.writeFileSync(filePath, content, "utf8");
443
- return filePath;
444
- } catch (_error) {
445
- require_FileModifierErrors.logger_default.debug(`Error saving file: ${_error}`);
446
- return null;
447
- }
448
- };
449
-
450
- //#endregion
451
- Object.defineProperty(exports, 'downloadFileFromS3', {
452
- enumerable: true,
453
- get: function () {
454
- return downloadFileFromS3;
455
- }
456
- });
457
- Object.defineProperty(exports, 'getFileDataAfterUploadingToS3', {
458
- enumerable: true,
459
- get: function () {
460
- return getFileDataAfterUploadingToS3;
461
- }
462
- });
@@ -1,17 +0,0 @@
1
- //#region src/types/files.types.d.ts
2
- type FileUploadData = {
3
- name: string;
4
- mimetype: string;
5
- s3key: string;
6
- };
7
- type FileDownloadData = {
8
- name: string;
9
- mimeType: string;
10
- s3Url: string;
11
- /**
12
- * @todo: actually, this can be null.
13
- */
14
- filePath: string;
15
- };
16
- //#endregion
17
- export { FileUploadData as n, FileDownloadData as t };