@composio/core 0.4.0 → 0.5.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/{chunk-SfbczIpV.mjs → chunk-0j-ceAHr.mjs} +3 -4
- package/dist/chunk-CQwRTUmo.cjs +53 -0
- package/dist/fileUtils-CJjp8sBn.cjs +931 -0
- package/dist/fileUtils-XEoNI39Q.mjs +852 -0
- package/dist/files.types-B7P5A1Z5.d.mts +17 -0
- package/dist/files.types-D-RzIOHq.d.cts +17 -0
- package/dist/index.cjs +363 -1069
- package/dist/index.d.cts +656 -384
- package/dist/index.d.mts +655 -384
- package/dist/index.mjs +251 -920
- package/dist/models/Files.node.cjs +38 -0
- package/dist/models/Files.node.d.cts +41 -0
- package/dist/models/Files.node.d.mts +41 -0
- package/dist/models/Files.node.mjs +39 -0
- package/dist/models/Files.workerd.cjs +29 -0
- package/dist/models/Files.workerd.d.cts +13 -0
- package/dist/models/Files.workerd.d.mts +13 -0
- package/dist/models/Files.workerd.mjs +28 -0
- package/dist/platform/node.cjs +46 -0
- package/dist/platform/node.d.cts +11 -0
- package/dist/platform/node.d.mts +11 -0
- package/dist/platform/node.mjs +42 -0
- package/dist/platform/workerd.cjs +36 -0
- package/dist/platform/workerd.d.cts +12 -0
- package/dist/platform/workerd.d.mts +12 -0
- package/dist/platform/workerd.mjs +35 -0
- package/dist/types-BaUqjuX3.d.mts +56 -0
- package/dist/types-BrsW5suw.d.cts +56 -0
- package/generated/index.d.ts +6 -0
- package/generated/index.js +18 -0
- package/package.json +74 -14
- package/src/platform/index.ts +2 -0
- package/src/platform/node.ts +51 -0
- package/src/platform/types.ts +60 -0
- package/src/platform/workerd.ts +57 -0
package/dist/index.cjs
CHANGED
|
@@ -1,62 +1,19 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __export = (all, symbols) => {
|
|
9
|
-
let target = {};
|
|
10
|
-
for (var name in all) {
|
|
11
|
-
__defProp(target, name, {
|
|
12
|
-
get: all[name],
|
|
13
|
-
enumerable: true
|
|
14
|
-
});
|
|
15
|
-
}
|
|
16
|
-
if (symbols) {
|
|
17
|
-
__defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
18
|
-
}
|
|
19
|
-
return target;
|
|
20
|
-
};
|
|
21
|
-
var __copyProps = (to, from, except, desc) => {
|
|
22
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
23
|
-
for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
24
|
-
key = keys[i];
|
|
25
|
-
if (!__hasOwnProp.call(to, key) && key !== except) {
|
|
26
|
-
__defProp(to, key, {
|
|
27
|
-
get: ((k) => from[k]).bind(null, key),
|
|
28
|
-
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
29
|
-
});
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
return to;
|
|
34
|
-
};
|
|
35
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
36
|
-
value: mod,
|
|
37
|
-
enumerable: true
|
|
38
|
-
}) : target, mod));
|
|
39
|
-
|
|
40
|
-
//#endregion
|
|
41
|
-
let __composio_client = require("@composio/client");
|
|
42
|
-
__composio_client = __toESM(__composio_client);
|
|
1
|
+
const require_chunk = require('./chunk-CQwRTUmo.cjs');
|
|
2
|
+
const require_fileUtils = require('./fileUtils-CJjp8sBn.cjs');
|
|
3
|
+
let _composio_client = require("@composio/client");
|
|
4
|
+
_composio_client = require_chunk.__toESM(_composio_client);
|
|
43
5
|
let zod_v3 = require("zod/v3");
|
|
44
|
-
zod_v3 = __toESM(zod_v3);
|
|
6
|
+
zod_v3 = require_chunk.__toESM(zod_v3);
|
|
45
7
|
let zod_to_json_schema = require("zod-to-json-schema");
|
|
46
|
-
zod_to_json_schema = __toESM(zod_to_json_schema);
|
|
47
|
-
let chalk = require("chalk");
|
|
48
|
-
chalk = __toESM(chalk);
|
|
49
|
-
let uuid = require("uuid");
|
|
50
|
-
let crypto = require("crypto");
|
|
51
|
-
crypto = __toESM(crypto);
|
|
52
|
-
let path = require("path");
|
|
53
|
-
path = __toESM(path);
|
|
54
|
-
let openai = require("openai");
|
|
8
|
+
zod_to_json_schema = require_chunk.__toESM(zod_to_json_schema);
|
|
55
9
|
let node_crypto = require("node:crypto");
|
|
56
|
-
node_crypto = __toESM(node_crypto);
|
|
10
|
+
node_crypto = require_chunk.__toESM(node_crypto);
|
|
11
|
+
let _platform = require("#platform");
|
|
12
|
+
let openai = require("openai");
|
|
57
13
|
let semver = require("semver");
|
|
58
|
-
semver = __toESM(semver);
|
|
59
|
-
let
|
|
14
|
+
semver = require_chunk.__toESM(semver);
|
|
15
|
+
let _files = require("#files");
|
|
16
|
+
let _composio_json_schema_to_zod = require("@composio/json-schema-to-zod");
|
|
60
17
|
|
|
61
18
|
//#region src/types/authConfigs.types.ts
|
|
62
19
|
const AuthConfigTypes = {
|
|
@@ -962,350 +919,6 @@ const ToolProxyParamsSchema = zod_v3.z.object({
|
|
|
962
919
|
customConnectionData: CustomConnectionDataSchema.describe("DEPRECATED: This field is deprecated and will be removed in the future.").optional()
|
|
963
920
|
});
|
|
964
921
|
|
|
965
|
-
//#endregion
|
|
966
|
-
//#region src/utils/env.ts
|
|
967
|
-
const getEnvVariable = (name, defaultValue = void 0) => {
|
|
968
|
-
try {
|
|
969
|
-
return process.env[name] || defaultValue;
|
|
970
|
-
} catch (_e) {
|
|
971
|
-
return defaultValue;
|
|
972
|
-
}
|
|
973
|
-
};
|
|
974
|
-
/**
|
|
975
|
-
* Method to return all the envs based on a specific prefix
|
|
976
|
-
* @param prefix
|
|
977
|
-
* @example
|
|
978
|
-
* COMPOSIO_TOOLKIT_VERSION_GITHUB=20250902_00
|
|
979
|
-
* COMPOSIO_TOOLKIT_VERSION_SLACK=20250902_00
|
|
980
|
-
* COMPOSIO_TOOLKIT_VERSION_GMAIL=latest
|
|
981
|
-
* @returns {Record<string, unknown>}
|
|
982
|
-
* @returns
|
|
983
|
-
*/
|
|
984
|
-
const getEnvsWithPrefix = (prefix) => {
|
|
985
|
-
try {
|
|
986
|
-
if (process && process.env) return Object.fromEntries(Object.entries(process.env).filter(([key]) => key.startsWith(prefix)));
|
|
987
|
-
else return {};
|
|
988
|
-
} catch (error) {
|
|
989
|
-
return {};
|
|
990
|
-
}
|
|
991
|
-
};
|
|
992
|
-
|
|
993
|
-
//#endregion
|
|
994
|
-
//#region src/utils/constants.ts
|
|
995
|
-
var constants_exports = /* @__PURE__ */ __export({
|
|
996
|
-
CLIENT_PUSHER_KEY: () => CLIENT_PUSHER_KEY,
|
|
997
|
-
COMPOSIO_DIR: () => COMPOSIO_DIR,
|
|
998
|
-
COMPOSIO_LOG_LEVEL: () => COMPOSIO_LOG_LEVEL,
|
|
999
|
-
DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
|
|
1000
|
-
DEFAULT_WEB_URL: () => DEFAULT_WEB_URL,
|
|
1001
|
-
IS_DEVELOPMENT_OR_CI: () => IS_DEVELOPMENT_OR_CI,
|
|
1002
|
-
TELEMETRY_URL: () => TELEMETRY_URL$1,
|
|
1003
|
-
TEMP_FILES_DIRECTORY_NAME: () => TEMP_FILES_DIRECTORY_NAME,
|
|
1004
|
-
USER_DATA_FILE_NAME: () => USER_DATA_FILE_NAME
|
|
1005
|
-
});
|
|
1006
|
-
const COMPOSIO_DIR = ".composio";
|
|
1007
|
-
const USER_DATA_FILE_NAME = "user_data.json";
|
|
1008
|
-
const TEMP_FILES_DIRECTORY_NAME = "files";
|
|
1009
|
-
const DEFAULT_BASE_URL = "https://backend.composio.dev";
|
|
1010
|
-
const DEFAULT_WEB_URL = "https://platform.composio.dev";
|
|
1011
|
-
const TELEMETRY_URL$1 = "https://app.composio.dev";
|
|
1012
|
-
const CLIENT_PUSHER_KEY = getEnvVariable("CLIENT_PUSHER_KEY") || "ff9f18c208855d77a152";
|
|
1013
|
-
const COMPOSIO_LOG_LEVEL = getEnvVariable("COMPOSIO_LOG_LEVEL");
|
|
1014
|
-
const IS_DEVELOPMENT_OR_CI = getEnvVariable("DEVELOPMENT") || getEnvVariable("CI") || false;
|
|
1015
|
-
|
|
1016
|
-
//#endregion
|
|
1017
|
-
//#region src/utils/logger.ts
|
|
1018
|
-
const LOG_LEVELS = {
|
|
1019
|
-
silent: -1,
|
|
1020
|
-
error: 0,
|
|
1021
|
-
warn: 1,
|
|
1022
|
-
info: 2,
|
|
1023
|
-
debug: 3
|
|
1024
|
-
};
|
|
1025
|
-
/**
|
|
1026
|
-
* Get the current log level from environment variables.
|
|
1027
|
-
* Defaults to 'info' if not set or invalid.
|
|
1028
|
-
* @returns {LogLevel} The current log level
|
|
1029
|
-
*/
|
|
1030
|
-
const getLogLevel = () => {
|
|
1031
|
-
const envLevel = (COMPOSIO_LOG_LEVEL ?? "info")?.toLowerCase();
|
|
1032
|
-
return envLevel && envLevel in LOG_LEVELS ? envLevel : "info";
|
|
1033
|
-
};
|
|
1034
|
-
var Logger = class {
|
|
1035
|
-
level;
|
|
1036
|
-
includeTimestamp;
|
|
1037
|
-
console;
|
|
1038
|
-
constructor(options = {}) {
|
|
1039
|
-
this.level = options.level ?? getLogLevel();
|
|
1040
|
-
this.includeTimestamp = options.includeTimestamp ?? true;
|
|
1041
|
-
this.console = console;
|
|
1042
|
-
}
|
|
1043
|
-
formatMessage(args) {
|
|
1044
|
-
const formattedArgs = args.map((arg, index) => {
|
|
1045
|
-
if (typeof arg === "object") return JSON.stringify(arg);
|
|
1046
|
-
else {
|
|
1047
|
-
if (index === 0) if (args.length > 1) return chalk.default.yellow(`${arg}`);
|
|
1048
|
-
else return String(arg);
|
|
1049
|
-
return String(arg);
|
|
1050
|
-
}
|
|
1051
|
-
}).join("\n");
|
|
1052
|
-
if (!this.includeTimestamp) return formattedArgs;
|
|
1053
|
-
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
1054
|
-
return `${chalk.default.gray(timestamp)} - ${formattedArgs}`;
|
|
1055
|
-
}
|
|
1056
|
-
shouldLog(level) {
|
|
1057
|
-
return LOG_LEVELS[level] <= LOG_LEVELS[this.level];
|
|
1058
|
-
}
|
|
1059
|
-
error(...args) {
|
|
1060
|
-
if (this.shouldLog("error")) this.console.error(this.formatMessage(args));
|
|
1061
|
-
}
|
|
1062
|
-
warn(...args) {
|
|
1063
|
-
if (this.shouldLog("warn")) this.console.warn(this.formatMessage(args));
|
|
1064
|
-
}
|
|
1065
|
-
info(...args) {
|
|
1066
|
-
if (this.shouldLog("info")) this.console.info(this.formatMessage(args));
|
|
1067
|
-
}
|
|
1068
|
-
debug(...args) {
|
|
1069
|
-
if (this.shouldLog("debug")) this.console.debug(this.formatMessage(args));
|
|
1070
|
-
}
|
|
1071
|
-
};
|
|
1072
|
-
const logger = new Logger();
|
|
1073
|
-
var logger_default = logger;
|
|
1074
|
-
|
|
1075
|
-
//#endregion
|
|
1076
|
-
//#region src/errors/ComposioError.ts
|
|
1077
|
-
/**
|
|
1078
|
-
* @fileoverview Error class for Composio.
|
|
1079
|
-
*
|
|
1080
|
-
* This error class is used to create custom errors for Composio.
|
|
1081
|
-
* It extends the built-in Error class and adds additional properties for code, status code, cause, meta, and possible fixes.
|
|
1082
|
-
*
|
|
1083
|
-
* @author Musthaq Ahamad <musthaq@composio.dev>
|
|
1084
|
-
* @module errors/ComposioError
|
|
1085
|
-
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error}
|
|
1086
|
-
*/
|
|
1087
|
-
/**
|
|
1088
|
-
* Base error class for all Composio errors
|
|
1089
|
-
*/
|
|
1090
|
-
var ComposioError = class ComposioError extends Error {
|
|
1091
|
-
/** @readonly Error name */
|
|
1092
|
-
name = "ComposioError";
|
|
1093
|
-
code;
|
|
1094
|
-
possibleFixes;
|
|
1095
|
-
errorId;
|
|
1096
|
-
/**
|
|
1097
|
-
* Creates a new ComposioError
|
|
1098
|
-
* @param message Error message
|
|
1099
|
-
* @param options Additional error options
|
|
1100
|
-
*/
|
|
1101
|
-
constructor(message, options = {}) {
|
|
1102
|
-
super(message);
|
|
1103
|
-
if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
|
|
1104
|
-
const statusCode = options.statusCode || (options.cause instanceof __composio_client.BadRequestError ? options.cause.status : void 0);
|
|
1105
|
-
this.code = `TS-SDK::${options.code}`;
|
|
1106
|
-
this.possibleFixes = options.possibleFixes;
|
|
1107
|
-
this.definePropertyIfExists("statusCode", statusCode);
|
|
1108
|
-
this.definePropertyIfExists("cause", options.cause);
|
|
1109
|
-
const combinedStack = options.cause instanceof Error ? ComposioError.combineStackTraces(options.cause.stack, this.stack) : options.stack ?? this.stack;
|
|
1110
|
-
this.definePropertyIfExists("stack", combinedStack);
|
|
1111
|
-
if (options.meta && Object.keys(options.meta).length > 0) this.definePropertyIfExists("meta", options.meta);
|
|
1112
|
-
}
|
|
1113
|
-
/**
|
|
1114
|
-
* Helper method to define a property only if it has a value
|
|
1115
|
-
* @param propertyName Name of the property to define
|
|
1116
|
-
* @param value Value to assign to the property
|
|
1117
|
-
* @private
|
|
1118
|
-
*/
|
|
1119
|
-
definePropertyIfExists(propertyName, value) {
|
|
1120
|
-
if (value !== void 0) Object.defineProperty(this, propertyName, {
|
|
1121
|
-
value,
|
|
1122
|
-
enumerable: true,
|
|
1123
|
-
writable: false,
|
|
1124
|
-
configurable: true
|
|
1125
|
-
});
|
|
1126
|
-
}
|
|
1127
|
-
/**
|
|
1128
|
-
* Helper method to combine stack traces when wrapping errors
|
|
1129
|
-
* This ensures the full call chain is preserved
|
|
1130
|
-
* @param originalStack The stack of the error being wrapped
|
|
1131
|
-
* @param currentStack The stack of the wrapper error
|
|
1132
|
-
* @returns Combined stack trace
|
|
1133
|
-
* @private
|
|
1134
|
-
*/
|
|
1135
|
-
static combineStackTraces(originalStack, currentStack) {
|
|
1136
|
-
if (!originalStack) return currentStack;
|
|
1137
|
-
if (!currentStack) return originalStack;
|
|
1138
|
-
const currentHeader = currentStack.split("\n")[0];
|
|
1139
|
-
const originalStackBody = originalStack.split("\n").slice(1).join("\n");
|
|
1140
|
-
return `${currentHeader}\n${currentStack.split("\n").slice(1).join("\n")}\n\nCaused by:\n${originalStackBody}`;
|
|
1141
|
-
}
|
|
1142
|
-
/**
|
|
1143
|
-
* Extract and normalize error data for formatting
|
|
1144
|
-
* @param includeStack Whether to include stack trace information
|
|
1145
|
-
* @returns Structured error data for formatting
|
|
1146
|
-
* @private
|
|
1147
|
-
*/
|
|
1148
|
-
getErrorData(includeStack = false) {
|
|
1149
|
-
const data = {
|
|
1150
|
-
name: this.name,
|
|
1151
|
-
message: this.message
|
|
1152
|
-
};
|
|
1153
|
-
const { cause, code, stack, statusCode, meta, possibleFixes } = this;
|
|
1154
|
-
if (cause !== void 0) {
|
|
1155
|
-
const rawCause = cause;
|
|
1156
|
-
data.cause = rawCause instanceof Error ? rawCause.message : String(rawCause);
|
|
1157
|
-
}
|
|
1158
|
-
if (code) data.code = code;
|
|
1159
|
-
if (statusCode !== void 0) data.statusCode = statusCode;
|
|
1160
|
-
if (meta) data.meta = meta;
|
|
1161
|
-
if (possibleFixes) data.possibleFixes = possibleFixes;
|
|
1162
|
-
if (includeStack && stack) if (stack.includes("Caused by:")) {
|
|
1163
|
-
const [currentStack, causeStack] = stack.split("Caused by:");
|
|
1164
|
-
data.stack = [
|
|
1165
|
-
...currentStack.split("\n").slice(1),
|
|
1166
|
-
"Caused by:",
|
|
1167
|
-
...causeStack.split("\n")
|
|
1168
|
-
];
|
|
1169
|
-
} else data.stack = stack.split("\n").slice(1);
|
|
1170
|
-
return data;
|
|
1171
|
-
}
|
|
1172
|
-
/**
|
|
1173
|
-
* Prints a user-friendly, colorful representation of the error to the logger
|
|
1174
|
-
* @param includeStack Whether to include the stack trace in the output (default: false)
|
|
1175
|
-
*/
|
|
1176
|
-
prettyPrint(includeStack = false) {
|
|
1177
|
-
const data = this.getErrorData(includeStack);
|
|
1178
|
-
let output = "\n" + chalk.default.bgRed.white.bold(" ERROR ") + " " + chalk.default.white.bold(data.message) + "\n";
|
|
1179
|
-
if (data.code) output += chalk.default.yellow(`Error Code: ${data.code}`) + "\n";
|
|
1180
|
-
if (data.statusCode !== void 0) output += chalk.default.yellow(`Status: ${data.statusCode}`) + "\n";
|
|
1181
|
-
if (data.cause) {
|
|
1182
|
-
output += chalk.default.gray("Reason:") + "\n";
|
|
1183
|
-
output += " " + chalk.default.white(data.cause) + "\n";
|
|
1184
|
-
}
|
|
1185
|
-
if (data.meta) {
|
|
1186
|
-
output += chalk.default.gray("Additional Information:") + "\n";
|
|
1187
|
-
output += " " + chalk.default.white(JSON.stringify(data.meta, null, 2).replace(/\n/g, "\n ")) + "\n";
|
|
1188
|
-
}
|
|
1189
|
-
if (data.possibleFixes?.length) {
|
|
1190
|
-
output += "\n" + chalk.default.cyan.bold("Try the following:") + "\n";
|
|
1191
|
-
const fixes = data.possibleFixes?.map((fix, index) => ` ${index + 1}. ` + chalk.default.white(fix));
|
|
1192
|
-
output += fixes?.join("\n") + "\n";
|
|
1193
|
-
}
|
|
1194
|
-
if (data.stack?.length) {
|
|
1195
|
-
output += "\n" + chalk.default.gray("Stack Trace:") + "\n";
|
|
1196
|
-
output += chalk.default.gray(data.stack.join("\n")) + "\n";
|
|
1197
|
-
}
|
|
1198
|
-
output += "\n";
|
|
1199
|
-
logger_default.error(output);
|
|
1200
|
-
}
|
|
1201
|
-
/**
|
|
1202
|
-
* Static factory method to create and pretty print an error in one step
|
|
1203
|
-
* @param message Error message
|
|
1204
|
-
* @param options Error options
|
|
1205
|
-
* @param includeStack Whether to include the stack trace in the output
|
|
1206
|
-
* @returns The created error instance
|
|
1207
|
-
*/
|
|
1208
|
-
static createAndPrint(message, options = {}, includeStack = false) {
|
|
1209
|
-
const error = new ComposioError(message, options);
|
|
1210
|
-
error.prettyPrint(includeStack);
|
|
1211
|
-
return error;
|
|
1212
|
-
}
|
|
1213
|
-
/**
|
|
1214
|
-
* Utility function to handle errors in a consistent way
|
|
1215
|
-
* This properly displays the error without throwing
|
|
1216
|
-
* @param error The error to handle
|
|
1217
|
-
* @param options Options for error handling
|
|
1218
|
-
*/
|
|
1219
|
-
static handle(error, options = {}) {
|
|
1220
|
-
const { includeStack = false, exitProcess = false } = options;
|
|
1221
|
-
if (error instanceof ComposioError) error.prettyPrint(includeStack);
|
|
1222
|
-
else if (error instanceof zod_v3.ZodError) this.handleZodError(error, includeStack);
|
|
1223
|
-
else if (error instanceof Error) this.handleStandardError(error, includeStack);
|
|
1224
|
-
else this.handleUnknownError(error);
|
|
1225
|
-
if (exitProcess) this.throwError(error);
|
|
1226
|
-
}
|
|
1227
|
-
/**
|
|
1228
|
-
* Utility function to handle errors and then throw them
|
|
1229
|
-
* This properly displays the error and then throws it, allowing callers to catch it.
|
|
1230
|
-
* Use this for fatal errors that should stop execution.
|
|
1231
|
-
* @param error The error to handle and throw
|
|
1232
|
-
* @param includeStack Whether to include the stack trace in the output
|
|
1233
|
-
* @throws ComposioError - Always throws after displaying the error
|
|
1234
|
-
*/
|
|
1235
|
-
static handleAndThrow(error, includeStack = false) {
|
|
1236
|
-
this.handle(error, { includeStack });
|
|
1237
|
-
this.throwError(error);
|
|
1238
|
-
}
|
|
1239
|
-
/**
|
|
1240
|
-
* Helper method to throw an error as a ComposioError
|
|
1241
|
-
* @param error The error to throw
|
|
1242
|
-
* @private
|
|
1243
|
-
*/
|
|
1244
|
-
static throwError(error) {
|
|
1245
|
-
if (error instanceof ComposioError) throw error;
|
|
1246
|
-
else if (error instanceof Error) throw new ComposioError(error.message, { cause: error });
|
|
1247
|
-
else throw new ComposioError(String(error));
|
|
1248
|
-
}
|
|
1249
|
-
/**
|
|
1250
|
-
* Helper method to handle Zod validation errors
|
|
1251
|
-
* @param error The Zod error to handle
|
|
1252
|
-
* @param includeStack Whether to include the stack trace
|
|
1253
|
-
* @private
|
|
1254
|
-
*/
|
|
1255
|
-
static handleZodError(error, includeStack) {
|
|
1256
|
-
logger_default.error("\n" + chalk.default.bgRed.white.bold(" ERROR ") + " " + chalk.default.white.bold(error.message));
|
|
1257
|
-
logger_default.error(chalk.default.gray("Invalid parameters:"));
|
|
1258
|
-
error.errors.forEach((err) => {
|
|
1259
|
-
logger_default.error(chalk.default.yellow(err.path.join(".")) + " " + chalk.default.white(err.message));
|
|
1260
|
-
});
|
|
1261
|
-
logger_default.error(chalk.default.gray("Expected parameters:"));
|
|
1262
|
-
error.errors.forEach((err) => {
|
|
1263
|
-
logger_default.error(chalk.default.yellow(err.path.join(".")) + " " + chalk.default.white(err.message));
|
|
1264
|
-
});
|
|
1265
|
-
if (includeStack) {
|
|
1266
|
-
logger_default.error("\n" + chalk.default.gray("Validation Errors:"));
|
|
1267
|
-
error.errors.forEach((err) => {
|
|
1268
|
-
const path$1 = err.path.join(".");
|
|
1269
|
-
logger_default.error(chalk.default.gray(" • ") + chalk.default.yellow(path$1 ? `${path$1}: ` : "") + chalk.default.white(err.message));
|
|
1270
|
-
});
|
|
1271
|
-
if (error.stack) {
|
|
1272
|
-
logger_default.error("\n" + chalk.default.gray("Stack Trace:"));
|
|
1273
|
-
const stackLines = error.stack.split("\n").slice(1);
|
|
1274
|
-
logger_default.error(chalk.default.gray(stackLines.join("\n")));
|
|
1275
|
-
}
|
|
1276
|
-
}
|
|
1277
|
-
logger_default.error("");
|
|
1278
|
-
}
|
|
1279
|
-
/**
|
|
1280
|
-
* Helper method to handle standard Error objects
|
|
1281
|
-
* @param error The standard error to handle
|
|
1282
|
-
* @param includeStack Whether to include the stack trace
|
|
1283
|
-
* @private
|
|
1284
|
-
*/
|
|
1285
|
-
static handleStandardError(error, includeStack) {
|
|
1286
|
-
logger_default.error("\n" + chalk.default.bgRed.white.bold(" ERROR ") + " " + chalk.default.white.bold(error.message));
|
|
1287
|
-
if (includeStack && error.stack) {
|
|
1288
|
-
logger_default.error("\n" + chalk.default.gray("Stack Trace:"));
|
|
1289
|
-
const stackLines = error.stack.split("\n").slice(1);
|
|
1290
|
-
logger_default.error(chalk.default.gray(stackLines.join("\n")));
|
|
1291
|
-
}
|
|
1292
|
-
logger_default.error("");
|
|
1293
|
-
}
|
|
1294
|
-
/**
|
|
1295
|
-
* Helper method to handle unknown error types
|
|
1296
|
-
* @param error The unknown error value
|
|
1297
|
-
* @private
|
|
1298
|
-
*/
|
|
1299
|
-
static handleUnknownError(error) {
|
|
1300
|
-
logger_default.error("\n" + chalk.default.bgRed.white.bold(" ERROR ") + " " + chalk.default.white.bold("Unknown error occurred"));
|
|
1301
|
-
if (error !== null && error !== void 0) {
|
|
1302
|
-
logger_default.error(chalk.default.gray("Error details:"));
|
|
1303
|
-
logger_default.error(" " + chalk.default.white(String(error)));
|
|
1304
|
-
}
|
|
1305
|
-
logger_default.error("");
|
|
1306
|
-
}
|
|
1307
|
-
};
|
|
1308
|
-
|
|
1309
922
|
//#endregion
|
|
1310
923
|
//#region src/errors/ConnectedAccountsErrors.ts
|
|
1311
924
|
const ConnectedAccountErrorCodes = {
|
|
@@ -1313,7 +926,7 @@ const ConnectedAccountErrorCodes = {
|
|
|
1313
926
|
MULTIPLE_CONNECTED_ACCOUNTS: "MULTIPLE_CONNECTED_ACCOUNTS",
|
|
1314
927
|
FAILED_TO_CREATE_CONNECTED_ACCOUNT_LINK: "FAILED_TO_CREATE_CONNECTED_ACCOUNT_LINK"
|
|
1315
928
|
};
|
|
1316
|
-
var ComposioConnectedAccountNotFoundError = class extends ComposioError {
|
|
929
|
+
var ComposioConnectedAccountNotFoundError = class extends require_fileUtils.ComposioError {
|
|
1317
930
|
constructor(message = "Connected account not found", options = {}) {
|
|
1318
931
|
super(message, {
|
|
1319
932
|
...options,
|
|
@@ -1324,7 +937,7 @@ var ComposioConnectedAccountNotFoundError = class extends ComposioError {
|
|
|
1324
937
|
this.name = "ComposioConnectedAccountNotFoundError";
|
|
1325
938
|
}
|
|
1326
939
|
};
|
|
1327
|
-
var ComposioMultipleConnectedAccountsError = class extends ComposioError {
|
|
940
|
+
var ComposioMultipleConnectedAccountsError = class extends require_fileUtils.ComposioError {
|
|
1328
941
|
constructor(message = "Multiple connected accounts found", options = {}) {
|
|
1329
942
|
super(message, {
|
|
1330
943
|
...options,
|
|
@@ -1334,7 +947,7 @@ var ComposioMultipleConnectedAccountsError = class extends ComposioError {
|
|
|
1334
947
|
this.name = "ComposioMultipleConnectedAccountsError";
|
|
1335
948
|
}
|
|
1336
949
|
};
|
|
1337
|
-
var ComposioFailedToCreateConnectedAccountLink = class extends ComposioError {
|
|
950
|
+
var ComposioFailedToCreateConnectedAccountLink = class extends require_fileUtils.ComposioError {
|
|
1338
951
|
constructor(message = "Failed to create connected account link", options = {}) {
|
|
1339
952
|
super(message, {
|
|
1340
953
|
...options,
|
|
@@ -1356,7 +969,7 @@ const ToolErrorCodes = {
|
|
|
1356
969
|
GLOBAL_EXECUTE_TOOL_FN_NOT_SET: "GLOBAL_EXECUTE_TOOL_FN_NOT_SET",
|
|
1357
970
|
TOOL_VERSION_REQUIRED: "TOOL_VERSION_REQUIRED"
|
|
1358
971
|
};
|
|
1359
|
-
var ComposioProviderNotDefinedError = class extends ComposioError {
|
|
972
|
+
var ComposioProviderNotDefinedError = class extends require_fileUtils.ComposioError {
|
|
1360
973
|
constructor(message = "Provider not defined", options = {}) {
|
|
1361
974
|
super(message, {
|
|
1362
975
|
...options,
|
|
@@ -1366,7 +979,7 @@ var ComposioProviderNotDefinedError = class extends ComposioError {
|
|
|
1366
979
|
this.name = "ComposioProviderNotDefinedError";
|
|
1367
980
|
}
|
|
1368
981
|
};
|
|
1369
|
-
var ComposioToolNotFoundError = class extends ComposioError {
|
|
982
|
+
var ComposioToolNotFoundError = class extends require_fileUtils.ComposioError {
|
|
1370
983
|
constructor(message = "Tool not found", options = {}) {
|
|
1371
984
|
super(message, {
|
|
1372
985
|
...options,
|
|
@@ -1376,7 +989,7 @@ var ComposioToolNotFoundError = class extends ComposioError {
|
|
|
1376
989
|
this.name = "ComposioToolNotFoundError";
|
|
1377
990
|
}
|
|
1378
991
|
};
|
|
1379
|
-
var ComposioInvalidModifierError = class extends ComposioError {
|
|
992
|
+
var ComposioInvalidModifierError = class extends require_fileUtils.ComposioError {
|
|
1380
993
|
constructor(message = "Invalid modifier", options = {}) {
|
|
1381
994
|
super(message, {
|
|
1382
995
|
...options,
|
|
@@ -1386,7 +999,7 @@ var ComposioInvalidModifierError = class extends ComposioError {
|
|
|
1386
999
|
this.name = "ComposioInvalidModifierError";
|
|
1387
1000
|
}
|
|
1388
1001
|
};
|
|
1389
|
-
var ComposioCustomToolsNotInitializedError = class extends ComposioError {
|
|
1002
|
+
var ComposioCustomToolsNotInitializedError = class extends require_fileUtils.ComposioError {
|
|
1390
1003
|
constructor(message = "Custom tools not initialized", options = {}) {
|
|
1391
1004
|
super(message, {
|
|
1392
1005
|
...options,
|
|
@@ -1396,7 +1009,7 @@ var ComposioCustomToolsNotInitializedError = class extends ComposioError {
|
|
|
1396
1009
|
this.name = "ComposioCustomToolsNotInitializedError";
|
|
1397
1010
|
}
|
|
1398
1011
|
};
|
|
1399
|
-
var ComposioToolExecutionError = class extends ComposioError {
|
|
1012
|
+
var ComposioToolExecutionError = class extends require_fileUtils.ComposioError {
|
|
1400
1013
|
constructor(message = "Tool execution error", options = {}) {
|
|
1401
1014
|
super(message, {
|
|
1402
1015
|
...options,
|
|
@@ -1407,7 +1020,7 @@ var ComposioToolExecutionError = class extends ComposioError {
|
|
|
1407
1020
|
this.name = "ComposioToolExecutionError";
|
|
1408
1021
|
}
|
|
1409
1022
|
};
|
|
1410
|
-
var ComposioInvalidExecuteFunctionError = class extends ComposioError {
|
|
1023
|
+
var ComposioInvalidExecuteFunctionError = class extends require_fileUtils.ComposioError {
|
|
1411
1024
|
constructor(message = "Invalid execute function", options = {}) {
|
|
1412
1025
|
super(message, {
|
|
1413
1026
|
...options,
|
|
@@ -1417,7 +1030,7 @@ var ComposioInvalidExecuteFunctionError = class extends ComposioError {
|
|
|
1417
1030
|
this.name = "ComposioInvalidExecuteFunctionError";
|
|
1418
1031
|
}
|
|
1419
1032
|
};
|
|
1420
|
-
var ComposioGlobalExecuteToolFnNotSetError = class extends ComposioError {
|
|
1033
|
+
var ComposioGlobalExecuteToolFnNotSetError = class extends require_fileUtils.ComposioError {
|
|
1421
1034
|
constructor(message = "Global execute tool function not set", options = {}) {
|
|
1422
1035
|
super(message, {
|
|
1423
1036
|
...options,
|
|
@@ -1490,7 +1103,7 @@ var ComposioGlobalExecuteToolFnNotSetError = class extends ComposioError {
|
|
|
1490
1103
|
* });
|
|
1491
1104
|
* ```
|
|
1492
1105
|
*/
|
|
1493
|
-
var ComposioToolVersionRequiredError = class extends ComposioError {
|
|
1106
|
+
var ComposioToolVersionRequiredError = class extends require_fileUtils.ComposioError {
|
|
1494
1107
|
constructor(message = "Toolkit version not specified. For manual execution of the tool please pass a specific toolkit version", options = {}) {
|
|
1495
1108
|
super(message, {
|
|
1496
1109
|
...options,
|
|
@@ -1506,7 +1119,7 @@ var ComposioToolVersionRequiredError = class extends ComposioError {
|
|
|
1506
1119
|
};
|
|
1507
1120
|
const ERROR_CODE_HANDLERS = new Map([[1803, (msg) => new ComposioConnectedAccountNotFoundError(msg)]]);
|
|
1508
1121
|
const handleToolExecutionError = (tool, actualError) => {
|
|
1509
|
-
if (actualError instanceof
|
|
1122
|
+
if (actualError instanceof _composio_client.APIError && actualError.error) {
|
|
1510
1123
|
const errorBody = actualError.error;
|
|
1511
1124
|
const errorCode = errorBody?.error?.code;
|
|
1512
1125
|
const errorMessage = errorBody?.error?.message;
|
|
@@ -1518,294 +1131,10 @@ const handleToolExecutionError = (tool, actualError) => {
|
|
|
1518
1131
|
});
|
|
1519
1132
|
};
|
|
1520
1133
|
|
|
1521
|
-
//#endregion
|
|
1522
|
-
//#region src/types/telemetry.types.ts
|
|
1523
|
-
const TELEMETRY_EVENTS = {
|
|
1524
|
-
SDK_INITIALIZED: "SDK_INITIALIZED",
|
|
1525
|
-
SDK_METHOD_INVOKED: "SDK_METHOD_INVOKED",
|
|
1526
|
-
SDK_METHOD_ERROR: "SDK_METHOD_ERROR",
|
|
1527
|
-
CLI_INVOKED: "CLI_INVOKED"
|
|
1528
|
-
};
|
|
1529
|
-
|
|
1530
|
-
//#endregion
|
|
1531
|
-
//#region src/telemetry/BatchProcessor.ts
|
|
1532
|
-
var BatchProcessor = class {
|
|
1533
|
-
batch = [];
|
|
1534
|
-
time;
|
|
1535
|
-
batchSize;
|
|
1536
|
-
processBatchCallback;
|
|
1537
|
-
timer = null;
|
|
1538
|
-
constructor(time = 2e3, batchSize = 100, processBatchCallback) {
|
|
1539
|
-
this.batch = [];
|
|
1540
|
-
this.time = time;
|
|
1541
|
-
this.batchSize = batchSize;
|
|
1542
|
-
this.processBatchCallback = processBatchCallback;
|
|
1543
|
-
}
|
|
1544
|
-
pushItem(item) {
|
|
1545
|
-
this.batch.push(item);
|
|
1546
|
-
if (this.batch.length >= this.batchSize) this.processBatch();
|
|
1547
|
-
else if (!this.timer) this.timer = setTimeout(() => this.processBatch(), this.time);
|
|
1548
|
-
}
|
|
1549
|
-
processBatch() {
|
|
1550
|
-
if (this.batch.length > 0) {
|
|
1551
|
-
this.processBatchCallback(this.batch);
|
|
1552
|
-
this.batch = [];
|
|
1553
|
-
}
|
|
1554
|
-
if (this.timer) {
|
|
1555
|
-
clearTimeout(this.timer);
|
|
1556
|
-
this.timer = null;
|
|
1557
|
-
}
|
|
1558
|
-
}
|
|
1559
|
-
};
|
|
1560
|
-
|
|
1561
|
-
//#endregion
|
|
1562
|
-
//#region src/utils/uuid.ts
|
|
1563
|
-
function getRandomUUID() {
|
|
1564
|
-
return (0, uuid.v4)();
|
|
1565
|
-
}
|
|
1566
|
-
function getRandomShortId() {
|
|
1567
|
-
return getRandomUUID().slice(0, 8).replace(/-/g, "");
|
|
1568
|
-
}
|
|
1569
|
-
|
|
1570
|
-
//#endregion
|
|
1571
|
-
//#region src/services/telemetry/TelemetryService.ts
|
|
1572
|
-
const TELEMETRY_URL = "https://telemetry.composio.dev/v1";
|
|
1573
|
-
var TelemetryService = class {
|
|
1574
|
-
/**
|
|
1575
|
-
* Sends a metric to the Telemetry API.
|
|
1576
|
-
* @param payload - The payload to send to the Telemetry API.
|
|
1577
|
-
* @returns The response from the Telemetry API.
|
|
1578
|
-
*/
|
|
1579
|
-
static async sendMetric(payload) {
|
|
1580
|
-
try {
|
|
1581
|
-
return await fetch(`${TELEMETRY_URL}/metrics/invocations`, {
|
|
1582
|
-
method: "POST",
|
|
1583
|
-
headers: { "Content-Type": "application/json" },
|
|
1584
|
-
body: JSON.stringify(payload)
|
|
1585
|
-
});
|
|
1586
|
-
} catch (error) {
|
|
1587
|
-
logger_default.debug("Error sending metric telemetry", error);
|
|
1588
|
-
}
|
|
1589
|
-
}
|
|
1590
|
-
/**
|
|
1591
|
-
* Sends an error log to the Telemetry API.
|
|
1592
|
-
* @param payload - The payload to send to the Telemetry API.
|
|
1593
|
-
* @returns The response from the Telemetry API.
|
|
1594
|
-
*/
|
|
1595
|
-
static async sendErrorLog(payload) {
|
|
1596
|
-
try {
|
|
1597
|
-
return await fetch(`${TELEMETRY_URL}/errors`, {
|
|
1598
|
-
method: "POST",
|
|
1599
|
-
headers: { "Content-Type": "application/json" },
|
|
1600
|
-
body: JSON.stringify(payload)
|
|
1601
|
-
});
|
|
1602
|
-
} catch (error) {
|
|
1603
|
-
logger_default.debug("Error sending error telemetry", error);
|
|
1604
|
-
}
|
|
1605
|
-
}
|
|
1606
|
-
};
|
|
1607
|
-
|
|
1608
|
-
//#endregion
|
|
1609
|
-
//#region src/telemetry/Telemetry.ts
|
|
1610
|
-
/**
|
|
1611
|
-
* The Telemetry class is used to log the telemetry for any given instance which extends InstrumentedInstance.
|
|
1612
|
-
*
|
|
1613
|
-
* This class is used to instrument the telemetry for the given instance and send the telemetry to the server.
|
|
1614
|
-
* This class is also used to create a global error handler for the given instance.
|
|
1615
|
-
*
|
|
1616
|
-
* @example
|
|
1617
|
-
*
|
|
1618
|
-
* const telemetry = new Telemetry({...});
|
|
1619
|
-
* const composio = new Composio({...})
|
|
1620
|
-
*
|
|
1621
|
-
* telemetry.instrument(composio);
|
|
1622
|
-
* telemetry.instrument(composio.tools);
|
|
1623
|
-
* telemetry.instrument(composio.toolkits);
|
|
1624
|
-
* telemetry.instrument(composio.triggers);
|
|
1625
|
-
*
|
|
1626
|
-
*/
|
|
1627
|
-
var TelemetryTransport = class {
|
|
1628
|
-
telemetryMetadata;
|
|
1629
|
-
isTelemetryDisabled = true;
|
|
1630
|
-
telemetrySource;
|
|
1631
|
-
telemetrySourceName = "typescript-sdk";
|
|
1632
|
-
telemetryServiceName = "sdk";
|
|
1633
|
-
telemetryLanguage = "typescript";
|
|
1634
|
-
batchProcessor = new BatchProcessor(200, 10, async (data) => {
|
|
1635
|
-
logger_default.debug("Sending batch of telemetry metrics", data);
|
|
1636
|
-
await TelemetryService.sendMetric(data);
|
|
1637
|
-
});
|
|
1638
|
-
setup(metadata) {
|
|
1639
|
-
this.telemetryMetadata = metadata;
|
|
1640
|
-
this.isTelemetryDisabled = false;
|
|
1641
|
-
this.telemetrySource = {
|
|
1642
|
-
host: this.telemetryMetadata?.host ?? this.telemetrySourceName,
|
|
1643
|
-
service: this.telemetryServiceName,
|
|
1644
|
-
language: this.telemetryLanguage,
|
|
1645
|
-
version: this.telemetryMetadata?.version,
|
|
1646
|
-
platform: this.telemetryMetadata?.isBrowser ? "browser" : "node",
|
|
1647
|
-
environment: getEnvVariable("NODE_ENV", "production")
|
|
1648
|
-
};
|
|
1649
|
-
this.sendMetric([{
|
|
1650
|
-
functionName: TELEMETRY_EVENTS.SDK_INITIALIZED,
|
|
1651
|
-
durationMs: 0,
|
|
1652
|
-
timestamp: Date.now() / 1e3,
|
|
1653
|
-
props: {},
|
|
1654
|
-
source: this.telemetrySource,
|
|
1655
|
-
metadata: { provider: this.telemetryMetadata?.provider ?? "openai" },
|
|
1656
|
-
error: void 0
|
|
1657
|
-
}]);
|
|
1658
|
-
}
|
|
1659
|
-
/**
|
|
1660
|
-
* Instrument the telemetry for the given instance.
|
|
1661
|
-
*
|
|
1662
|
-
* You can pass the instance and the file name of the instance to instrument the telemetry.
|
|
1663
|
-
* This will instrument all the methods of the instance and log the telemetry for each method call.
|
|
1664
|
-
* @param instance - any instance that extends InstrumentedInstance
|
|
1665
|
-
* @param fileName - the file name of the instance
|
|
1666
|
-
* @returns
|
|
1667
|
-
*/
|
|
1668
|
-
instrument(instance, fileName) {
|
|
1669
|
-
const proto = Object.getPrototypeOf(instance);
|
|
1670
|
-
const methodNames = Object.getOwnPropertyNames(proto).filter((key) => {
|
|
1671
|
-
const descriptor = Object.getOwnPropertyDescriptor(proto, key);
|
|
1672
|
-
return key !== "constructor" && descriptor && typeof descriptor.value === "function" && descriptor.value.constructor.name === "AsyncFunction";
|
|
1673
|
-
});
|
|
1674
|
-
const instrumentedClassName = fileName ?? instance.constructor?.name ?? "unknown";
|
|
1675
|
-
for (const name of methodNames) {
|
|
1676
|
-
const originalMethod = instance[name];
|
|
1677
|
-
instance[name] = async (...args) => {
|
|
1678
|
-
const telemetryEnabled = this.shouldSendTelemetry();
|
|
1679
|
-
const startTime = telemetryEnabled ? Date.now() : void 0;
|
|
1680
|
-
try {
|
|
1681
|
-
const result = await originalMethod.apply(instance, args);
|
|
1682
|
-
if (telemetryEnabled && startTime !== void 0) {
|
|
1683
|
-
const durationMs = Date.now() - startTime;
|
|
1684
|
-
const telemetryPayload = {
|
|
1685
|
-
functionName: `${instrumentedClassName}.${name}`,
|
|
1686
|
-
durationMs,
|
|
1687
|
-
timestamp: startTime / 1e3,
|
|
1688
|
-
props: {
|
|
1689
|
-
fileName: instrumentedClassName,
|
|
1690
|
-
method: name,
|
|
1691
|
-
params: args
|
|
1692
|
-
},
|
|
1693
|
-
metadata: { provider: this.telemetryMetadata?.provider ?? "openai" },
|
|
1694
|
-
error: void 0,
|
|
1695
|
-
source: this.telemetrySource
|
|
1696
|
-
};
|
|
1697
|
-
this.batchProcessor.pushItem(telemetryPayload);
|
|
1698
|
-
}
|
|
1699
|
-
return result;
|
|
1700
|
-
} catch (error) {
|
|
1701
|
-
if (error instanceof Error) {
|
|
1702
|
-
if (!error.errorId) {
|
|
1703
|
-
error.errorId = getRandomUUID();
|
|
1704
|
-
if (telemetryEnabled && startTime !== void 0) {
|
|
1705
|
-
const durationMs = Date.now() - startTime;
|
|
1706
|
-
await this.prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args, startTime, durationMs);
|
|
1707
|
-
}
|
|
1708
|
-
}
|
|
1709
|
-
}
|
|
1710
|
-
throw error;
|
|
1711
|
-
}
|
|
1712
|
-
};
|
|
1713
|
-
}
|
|
1714
|
-
return instance;
|
|
1715
|
-
}
|
|
1716
|
-
/**
|
|
1717
|
-
* Check if the telemetry should be sent.
|
|
1718
|
-
* @returns true if the telemetry should be sent, false otherwise
|
|
1719
|
-
*/
|
|
1720
|
-
shouldSendTelemetry() {
|
|
1721
|
-
const telemetryDisabledEnvironments = ["test", "ci"];
|
|
1722
|
-
const nodeEnv = (getEnvVariable("NODE_ENV", "development") || "").toLowerCase();
|
|
1723
|
-
const isDisabledEnvironment = telemetryDisabledEnvironments.includes(nodeEnv);
|
|
1724
|
-
const isTelemetryDisabledByEnv = getEnvVariable("TELEMETRY_DISABLED", "false") === "true";
|
|
1725
|
-
return !this.isTelemetryDisabled && !isTelemetryDisabledByEnv && !isDisabledEnvironment;
|
|
1726
|
-
}
|
|
1727
|
-
/**
|
|
1728
|
-
* Prepare and send the error telemetry.
|
|
1729
|
-
*
|
|
1730
|
-
* @TODO This currently blocks the thread and sends the telemetry to the server.
|
|
1731
|
-
*
|
|
1732
|
-
* @param {unknown} error - The error to send.
|
|
1733
|
-
* @param {string} instrumentedClassName - The class name of the instrumented class.
|
|
1734
|
-
* @param {string} name - The name of the method that threw the error.
|
|
1735
|
-
* @param {unknown[]} args - The arguments passed to the method.
|
|
1736
|
-
* @param {number} startTime - The start time of the method invocation in milliseconds.
|
|
1737
|
-
* @param {number} durationMs - The duration of the method invocation in milliseconds.
|
|
1738
|
-
*/
|
|
1739
|
-
async prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args, startTime, durationMs) {
|
|
1740
|
-
const telemetryPayload = {
|
|
1741
|
-
functionName: `${instrumentedClassName}.${name}`,
|
|
1742
|
-
durationMs,
|
|
1743
|
-
timestamp: startTime / 1e3,
|
|
1744
|
-
props: {
|
|
1745
|
-
fileName: instrumentedClassName,
|
|
1746
|
-
method: name,
|
|
1747
|
-
params: args
|
|
1748
|
-
},
|
|
1749
|
-
metadata: { provider: this.telemetryMetadata?.provider ?? "openai" },
|
|
1750
|
-
source: this.telemetrySource
|
|
1751
|
-
};
|
|
1752
|
-
if (error instanceof __composio_client.ComposioError) telemetryPayload.error = {
|
|
1753
|
-
errorId: error.errorId,
|
|
1754
|
-
name: error.name,
|
|
1755
|
-
message: error.message,
|
|
1756
|
-
stack: error.stack
|
|
1757
|
-
};
|
|
1758
|
-
else if (error instanceof ComposioError) telemetryPayload.error = {
|
|
1759
|
-
errorId: error.errorId,
|
|
1760
|
-
name: error.name,
|
|
1761
|
-
code: error.code,
|
|
1762
|
-
message: error.message,
|
|
1763
|
-
stack: error.stack
|
|
1764
|
-
};
|
|
1765
|
-
else if (error instanceof Error) telemetryPayload.error = {
|
|
1766
|
-
errorId: error.errorId,
|
|
1767
|
-
name: error.name ?? "Unknown error",
|
|
1768
|
-
message: error.message,
|
|
1769
|
-
stack: error.stack
|
|
1770
|
-
};
|
|
1771
|
-
await this.sendErrorTelemetry(telemetryPayload);
|
|
1772
|
-
}
|
|
1773
|
-
/**
|
|
1774
|
-
* Send the telemetry payload to the server.
|
|
1775
|
-
* @param payload - the telemetry payload to send
|
|
1776
|
-
* @returns
|
|
1777
|
-
*/
|
|
1778
|
-
async sendMetric(payload) {
|
|
1779
|
-
if (!this.shouldSendTelemetry()) {
|
|
1780
|
-
logger_default.debug("Telemetry is disabled, skipping metric telemetry", payload);
|
|
1781
|
-
return;
|
|
1782
|
-
}
|
|
1783
|
-
try {
|
|
1784
|
-
logger_default.debug("SDK Metric", payload);
|
|
1785
|
-
await TelemetryService.sendMetric(payload);
|
|
1786
|
-
} catch (error) {
|
|
1787
|
-
logger_default.error("Error sending metric telemetry", error);
|
|
1788
|
-
}
|
|
1789
|
-
}
|
|
1790
|
-
async sendErrorTelemetry(payload) {
|
|
1791
|
-
if (!this.shouldSendTelemetry()) {
|
|
1792
|
-
logger_default.debug("Telemetry is disabled, skipping metric telemetry", payload);
|
|
1793
|
-
return;
|
|
1794
|
-
}
|
|
1795
|
-
try {
|
|
1796
|
-
logger_default.debug("SDK Error Telemetry", payload);
|
|
1797
|
-
await TelemetryService.sendErrorLog(payload);
|
|
1798
|
-
} catch (error) {
|
|
1799
|
-
logger_default.error("Error sending error telemetry", error);
|
|
1800
|
-
}
|
|
1801
|
-
}
|
|
1802
|
-
};
|
|
1803
|
-
const telemetry = new TelemetryTransport();
|
|
1804
|
-
|
|
1805
1134
|
//#endregion
|
|
1806
1135
|
//#region src/errors/AuthConfigErrors.ts
|
|
1807
1136
|
const AuthConfigErrorCodes = { AUTH_CONFIG_NOT_FOUND: "AUTH_CONFIG_NOT_FOUND" };
|
|
1808
|
-
var ComposioAuthConfigNotFoundError = class extends ComposioError {
|
|
1137
|
+
var ComposioAuthConfigNotFoundError = class extends require_fileUtils.ComposioError {
|
|
1809
1138
|
constructor(message = "Auth config not found", options = {}) {
|
|
1810
1139
|
super(message, {
|
|
1811
1140
|
...options,
|
|
@@ -1826,7 +1155,7 @@ const ConnectionRequestErrorCodes = {
|
|
|
1826
1155
|
CONNECTION_REQUEST_TIMEOUT: "CONNECTION_REQUEST_TIMEOUT",
|
|
1827
1156
|
CONNECTION_REQUEST_FAILED: "CONNECTION_REQUEST_FAILED"
|
|
1828
1157
|
};
|
|
1829
|
-
var ConnectionRequestTimeoutError = class extends ComposioError {
|
|
1158
|
+
var ConnectionRequestTimeoutError = class extends require_fileUtils.ComposioError {
|
|
1830
1159
|
constructor(message = "Connection request timed out", options = {}) {
|
|
1831
1160
|
super(message, {
|
|
1832
1161
|
...options,
|
|
@@ -1835,7 +1164,7 @@ var ConnectionRequestTimeoutError = class extends ComposioError {
|
|
|
1835
1164
|
this.name = "ConnectionRequestTimeoutError";
|
|
1836
1165
|
}
|
|
1837
1166
|
};
|
|
1838
|
-
var ConnectionRequestFailedError = class extends ComposioError {
|
|
1167
|
+
var ConnectionRequestFailedError = class extends require_fileUtils.ComposioError {
|
|
1839
1168
|
constructor(message = "Connection request failed", options = {}) {
|
|
1840
1169
|
super(message, {
|
|
1841
1170
|
...options,
|
|
@@ -1848,7 +1177,7 @@ var ConnectionRequestFailedError = class extends ComposioError {
|
|
|
1848
1177
|
//#endregion
|
|
1849
1178
|
//#region src/errors/ToolkitErrors.ts
|
|
1850
1179
|
const ToolkitErrorCodes = { TOOLKIT_NOT_FOUND: "TOOLKIT_NOT_FOUND" };
|
|
1851
|
-
var ComposioToolkitNotFoundError = class extends ComposioError {
|
|
1180
|
+
var ComposioToolkitNotFoundError = class extends require_fileUtils.ComposioError {
|
|
1852
1181
|
constructor(message = "Toolkit not found", options = {}) {
|
|
1853
1182
|
super(message, {
|
|
1854
1183
|
...options,
|
|
@@ -1858,7 +1187,7 @@ var ComposioToolkitNotFoundError = class extends ComposioError {
|
|
|
1858
1187
|
this.name = "ComposioToolkitNotFoundError";
|
|
1859
1188
|
}
|
|
1860
1189
|
};
|
|
1861
|
-
var ComposioToolkitFetchError = class extends ComposioError {
|
|
1190
|
+
var ComposioToolkitFetchError = class extends require_fileUtils.ComposioError {
|
|
1862
1191
|
constructor(message = "Failed to fetch toolkit", options = {}) {
|
|
1863
1192
|
super(message, {
|
|
1864
1193
|
...options,
|
|
@@ -1882,7 +1211,7 @@ const ValidationErrorCodes = {
|
|
|
1882
1211
|
VALIDATION_ERROR: "VALIDATION_ERROR",
|
|
1883
1212
|
JSON_SCHEMA_TO_ZOD_ERROR: "JSON_SCHEMA_TO_ZOD_ERROR"
|
|
1884
1213
|
};
|
|
1885
|
-
var ValidationError = class extends ComposioError {
|
|
1214
|
+
var ValidationError = class extends require_fileUtils.ComposioError {
|
|
1886
1215
|
constructor(message = "Input validation failed", options = {}) {
|
|
1887
1216
|
const { cause: providedZodError, ...restOptions } = options;
|
|
1888
1217
|
let zodErrorInstance;
|
|
@@ -1912,7 +1241,7 @@ var ValidationError = class extends ComposioError {
|
|
|
1912
1241
|
return "Please check your input parameters";
|
|
1913
1242
|
}
|
|
1914
1243
|
};
|
|
1915
|
-
var JsonSchemaToZodError = class extends ComposioError {
|
|
1244
|
+
var JsonSchemaToZodError = class extends require_fileUtils.ComposioError {
|
|
1916
1245
|
constructor(message = "Failed to convert JSON schema to Zod schema", options = {}) {
|
|
1917
1246
|
super(message, {
|
|
1918
1247
|
...options,
|
|
@@ -1924,7 +1253,7 @@ var JsonSchemaToZodError = class extends ComposioError {
|
|
|
1924
1253
|
//#endregion
|
|
1925
1254
|
//#region src/errors/SDKErrors.ts
|
|
1926
1255
|
const SDKErrorCodes = { NO_API_KEY_PROVIDED: "NO_API_KEY_PROVIDED" };
|
|
1927
|
-
var ComposioNoAPIKeyError = class extends ComposioError {
|
|
1256
|
+
var ComposioNoAPIKeyError = class extends require_fileUtils.ComposioError {
|
|
1928
1257
|
constructor(message = "No Composio API key provided", options = {}) {
|
|
1929
1258
|
const defaultCause = "Couldn't find an API key in the params, environment variables or in the user config file";
|
|
1930
1259
|
super(message, {
|
|
@@ -1953,7 +1282,7 @@ const TriggerErrorCodes = {
|
|
|
1953
1282
|
WEBHOOK_SIGNATURE_VERIFICATION_FAILED: "WEBHOOK_SIGNATURE_VERIFICATION_FAILED",
|
|
1954
1283
|
WEBHOOK_PAYLOAD_INVALID: "WEBHOOK_PAYLOAD_INVALID"
|
|
1955
1284
|
};
|
|
1956
|
-
var ComposioFailedToGetSDKRealtimeCredentialsError = class extends ComposioError {
|
|
1285
|
+
var ComposioFailedToGetSDKRealtimeCredentialsError = class extends require_fileUtils.ComposioError {
|
|
1957
1286
|
constructor(message = "Failed to get SDK realtime credentials", options = {}) {
|
|
1958
1287
|
super(message, {
|
|
1959
1288
|
...options,
|
|
@@ -1963,7 +1292,7 @@ var ComposioFailedToGetSDKRealtimeCredentialsError = class extends ComposioError
|
|
|
1963
1292
|
this.name = "ComposioFailedToGetSDKRealtimeCredentialsError";
|
|
1964
1293
|
}
|
|
1965
1294
|
};
|
|
1966
|
-
var ComposioFailedToCreatePusherClientError = class extends ComposioError {
|
|
1295
|
+
var ComposioFailedToCreatePusherClientError = class extends require_fileUtils.ComposioError {
|
|
1967
1296
|
constructor(message = "Failed to create Pusher client", options = {}) {
|
|
1968
1297
|
super(message, {
|
|
1969
1298
|
...options,
|
|
@@ -1973,7 +1302,7 @@ var ComposioFailedToCreatePusherClientError = class extends ComposioError {
|
|
|
1973
1302
|
this.name = "ComposioFailedToCreatePusherClientError";
|
|
1974
1303
|
}
|
|
1975
1304
|
};
|
|
1976
|
-
var ComposioFailedToSubscribeToPusherChannelError = class extends ComposioError {
|
|
1305
|
+
var ComposioFailedToSubscribeToPusherChannelError = class extends require_fileUtils.ComposioError {
|
|
1977
1306
|
constructor(message = "Failed to subscribe to Pusher channel", options = {}) {
|
|
1978
1307
|
super(message, {
|
|
1979
1308
|
...options,
|
|
@@ -1983,7 +1312,7 @@ var ComposioFailedToSubscribeToPusherChannelError = class extends ComposioError
|
|
|
1983
1312
|
this.name = "ComposioFailedToSubscribeToPusherChannelError";
|
|
1984
1313
|
}
|
|
1985
1314
|
};
|
|
1986
|
-
var ComposioFailedToUnsubscribeFromPusherChannelError = class extends ComposioError {
|
|
1315
|
+
var ComposioFailedToUnsubscribeFromPusherChannelError = class extends require_fileUtils.ComposioError {
|
|
1987
1316
|
constructor(message = "Failed to unsubscribe from Pusher channel", options = {}) {
|
|
1988
1317
|
super(message, {
|
|
1989
1318
|
...options,
|
|
@@ -1993,7 +1322,7 @@ var ComposioFailedToUnsubscribeFromPusherChannelError = class extends ComposioEr
|
|
|
1993
1322
|
this.name = "ComposioFailedToUnsubscribeFromPusherChannelError";
|
|
1994
1323
|
}
|
|
1995
1324
|
};
|
|
1996
|
-
var ComposioTriggerTypeNotFoundError = class extends ComposioError {
|
|
1325
|
+
var ComposioTriggerTypeNotFoundError = class extends require_fileUtils.ComposioError {
|
|
1997
1326
|
constructor(message = "Trigger type not found", options = {}) {
|
|
1998
1327
|
super(message, {
|
|
1999
1328
|
...options,
|
|
@@ -2004,7 +1333,7 @@ var ComposioTriggerTypeNotFoundError = class extends ComposioError {
|
|
|
2004
1333
|
this.name = "ComposioTriggerTypeNotFoundError";
|
|
2005
1334
|
}
|
|
2006
1335
|
};
|
|
2007
|
-
var ComposioWebhookSignatureVerificationError = class extends ComposioError {
|
|
1336
|
+
var ComposioWebhookSignatureVerificationError = class extends require_fileUtils.ComposioError {
|
|
2008
1337
|
constructor(message = "Webhook signature verification failed", options = {}) {
|
|
2009
1338
|
super(message, {
|
|
2010
1339
|
...options,
|
|
@@ -2019,7 +1348,7 @@ var ComposioWebhookSignatureVerificationError = class extends ComposioError {
|
|
|
2019
1348
|
this.name = "ComposioWebhookSignatureVerificationError";
|
|
2020
1349
|
}
|
|
2021
1350
|
};
|
|
2022
|
-
var ComposioWebhookPayloadError = class extends ComposioError {
|
|
1351
|
+
var ComposioWebhookPayloadError = class extends require_fileUtils.ComposioError {
|
|
2023
1352
|
constructor(message = "Invalid webhook payload", options = {}) {
|
|
2024
1353
|
super(message, {
|
|
2025
1354
|
...options,
|
|
@@ -2126,7 +1455,7 @@ function transform(raw) {
|
|
|
2126
1455
|
const transformed = transformer(raw);
|
|
2127
1456
|
const result = schema.safeParse(transformed);
|
|
2128
1457
|
if (!result.success) {
|
|
2129
|
-
logger_default.error(result.error);
|
|
1458
|
+
require_fileUtils.logger_default.error(result.error);
|
|
2130
1459
|
return transformed;
|
|
2131
1460
|
}
|
|
2132
1461
|
return result.data;
|
|
@@ -2153,7 +1482,7 @@ function transformConnectedAccountResponse(response) {
|
|
|
2153
1482
|
try {
|
|
2154
1483
|
return state ? ConnectionDataSchema.parse(state) : void 0;
|
|
2155
1484
|
} catch (error) {
|
|
2156
|
-
logger_default.warn("Unsupported auth scheme in connected account state, ignoring state field", { error });
|
|
1485
|
+
require_fileUtils.logger_default.warn("Unsupported auth scheme in connected account state, ignoring state field", { error });
|
|
2157
1486
|
return;
|
|
2158
1487
|
}
|
|
2159
1488
|
};
|
|
@@ -2201,10 +1530,10 @@ var CustomTools = class {
|
|
|
2201
1530
|
client;
|
|
2202
1531
|
customToolsRegistry;
|
|
2203
1532
|
constructor(client) {
|
|
2204
|
-
if (!client) throw new ComposioError("ComposioClient is required");
|
|
1533
|
+
if (!client) throw new require_fileUtils.ComposioError("ComposioClient is required");
|
|
2205
1534
|
this.client = client;
|
|
2206
1535
|
this.customToolsRegistry = /* @__PURE__ */ new Map();
|
|
2207
|
-
telemetry.instrument(this, "CustomTools");
|
|
1536
|
+
require_fileUtils.telemetry.instrument(this, "CustomTools");
|
|
2208
1537
|
}
|
|
2209
1538
|
/**
|
|
2210
1539
|
* Create a custom tool and registers it in the registry.
|
|
@@ -2309,7 +1638,7 @@ var CustomTools = class {
|
|
|
2309
1638
|
try {
|
|
2310
1639
|
return this.customToolsRegistry.get(slug.toLowerCase())?.schema;
|
|
2311
1640
|
} catch (error) {
|
|
2312
|
-
logger_default.error(`Error getting custom tool: ${error}`);
|
|
1641
|
+
require_fileUtils.logger_default.error(`Error getting custom tool: ${error}`);
|
|
2313
1642
|
return;
|
|
2314
1643
|
}
|
|
2315
1644
|
}
|
|
@@ -2355,7 +1684,7 @@ var CustomTools = class {
|
|
|
2355
1684
|
let connectedAccountId = body.connectedAccountId;
|
|
2356
1685
|
if (toolkitSlug && toolkitSlug !== "custom" && body.userId) {
|
|
2357
1686
|
const connectedAccount = await this.getConnectedAccountForToolkit(toolkitSlug, body.userId, body.connectedAccountId);
|
|
2358
|
-
logger_default.debug(`[CustomTool] Connected account for ${toolkitSlug} found for user ${body.userId}`, JSON.stringify(connectedAccount, null, 2));
|
|
1687
|
+
require_fileUtils.logger_default.debug(`[CustomTool] Connected account for ${toolkitSlug} found for user ${body.userId}`, JSON.stringify(connectedAccount, null, 2));
|
|
2359
1688
|
if (!connectedAccount) throw new ComposioConnectedAccountNotFoundError(`Connected account not found for toolkit ${toolkitSlug} for user ${body.userId}`, { meta: {
|
|
2360
1689
|
toolkitSlug,
|
|
2361
1690
|
userId: body.userId
|
|
@@ -2395,7 +1724,7 @@ var CustomTools = class {
|
|
|
2395
1724
|
//#endregion
|
|
2396
1725
|
//#region src/errors/FileModifierErrors.ts
|
|
2397
1726
|
const FileModifierErrorCodes = { FILE_UPLOAD_FAILED: "FILE_UPLOAD_FAILED" };
|
|
2398
|
-
var ComposioFileUploadError = class extends ComposioError {
|
|
1727
|
+
var ComposioFileUploadError = class extends require_fileUtils.ComposioError {
|
|
2399
1728
|
constructor(message = "Failed to upload file", options = {}) {
|
|
2400
1729
|
super(message, {
|
|
2401
1730
|
...options,
|
|
@@ -2406,220 +1735,6 @@ var ComposioFileUploadError = class extends ComposioError {
|
|
|
2406
1735
|
}
|
|
2407
1736
|
};
|
|
2408
1737
|
|
|
2409
|
-
//#endregion
|
|
2410
|
-
//#region src/utils/fileUtils.ts
|
|
2411
|
-
const getExtensionFromMimeType = (mimeType) => {
|
|
2412
|
-
const mimeToExt = {
|
|
2413
|
-
"text/plain": "txt",
|
|
2414
|
-
"text/html": "html",
|
|
2415
|
-
"text/css": "css",
|
|
2416
|
-
"text/javascript": "js",
|
|
2417
|
-
"application/json": "json",
|
|
2418
|
-
"application/xml": "xml",
|
|
2419
|
-
"application/pdf": "pdf",
|
|
2420
|
-
"application/zip": "zip",
|
|
2421
|
-
"application/x-zip-compressed": "zip",
|
|
2422
|
-
"application/gzip": "gz",
|
|
2423
|
-
"application/x-tar": "tar",
|
|
2424
|
-
"application/msword": "doc",
|
|
2425
|
-
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
|
|
2426
|
-
"application/vnd.ms-excel": "xls",
|
|
2427
|
-
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
|
|
2428
|
-
"application/vnd.ms-powerpoint": "ppt",
|
|
2429
|
-
"application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",
|
|
2430
|
-
"image/jpeg": "jpg",
|
|
2431
|
-
"image/jpg": "jpg",
|
|
2432
|
-
"image/png": "png",
|
|
2433
|
-
"image/gif": "gif",
|
|
2434
|
-
"image/svg+xml": "svg",
|
|
2435
|
-
"image/webp": "webp",
|
|
2436
|
-
"image/bmp": "bmp",
|
|
2437
|
-
"image/tiff": "tiff",
|
|
2438
|
-
"audio/mpeg": "mp3",
|
|
2439
|
-
"audio/wav": "wav",
|
|
2440
|
-
"audio/ogg": "ogg",
|
|
2441
|
-
"video/mp4": "mp4",
|
|
2442
|
-
"video/mpeg": "mpeg",
|
|
2443
|
-
"video/quicktime": "mov",
|
|
2444
|
-
"video/x-msvideo": "avi",
|
|
2445
|
-
"video/webm": "webm"
|
|
2446
|
-
};
|
|
2447
|
-
const cleanMimeType = mimeType.split(";")[0].toLowerCase().trim();
|
|
2448
|
-
if (mimeToExt[cleanMimeType]) return mimeToExt[cleanMimeType];
|
|
2449
|
-
const parts = cleanMimeType.split("/");
|
|
2450
|
-
if (parts.length === 2) {
|
|
2451
|
-
const cleanSubtype = parts[1].toLowerCase();
|
|
2452
|
-
if (cleanSubtype.includes("+")) {
|
|
2453
|
-
const plusParts = cleanSubtype.split("+");
|
|
2454
|
-
const prefix = plusParts[0];
|
|
2455
|
-
const suffix = plusParts[plusParts.length - 1];
|
|
2456
|
-
if ([
|
|
2457
|
-
"svg",
|
|
2458
|
-
"atom",
|
|
2459
|
-
"rss"
|
|
2460
|
-
].includes(prefix)) return prefix;
|
|
2461
|
-
if ([
|
|
2462
|
-
"json",
|
|
2463
|
-
"xml",
|
|
2464
|
-
"yaml",
|
|
2465
|
-
"zip",
|
|
2466
|
-
"gzip"
|
|
2467
|
-
].includes(suffix)) return suffix;
|
|
2468
|
-
return suffix;
|
|
2469
|
-
}
|
|
2470
|
-
return cleanSubtype || "txt";
|
|
2471
|
-
}
|
|
2472
|
-
return "txt";
|
|
2473
|
-
};
|
|
2474
|
-
const generateTimestampedFilename = (extension, prefix) => {
|
|
2475
|
-
return `${prefix || "file_ts"}${Date.now()}${getRandomShortId()}.${extension}`;
|
|
2476
|
-
};
|
|
2477
|
-
const readFileContent = async (path$1) => {
|
|
2478
|
-
try {
|
|
2479
|
-
const content = require("fs").readFileSync(path$1);
|
|
2480
|
-
return {
|
|
2481
|
-
fileName: generateTimestampedFilename(path$1.split(".").pop() || "txt"),
|
|
2482
|
-
content: content.toString("base64"),
|
|
2483
|
-
mimeType: "application/octet-stream"
|
|
2484
|
-
};
|
|
2485
|
-
} catch (error) {
|
|
2486
|
-
throw new Error(`Error reading file at ${path$1}: ${error}`);
|
|
2487
|
-
}
|
|
2488
|
-
};
|
|
2489
|
-
const readFileContentFromURL = async (path$1) => {
|
|
2490
|
-
const response = await fetch(path$1);
|
|
2491
|
-
if (!response.ok) throw new Error(`Failed to fetch file: ${response.statusText}`);
|
|
2492
|
-
const arrayBuffer = await response.arrayBuffer();
|
|
2493
|
-
const content = Buffer.from(arrayBuffer);
|
|
2494
|
-
const mimeType = response.headers.get("content-type") || "application/octet-stream";
|
|
2495
|
-
const pathname = new URL(path$1).pathname;
|
|
2496
|
-
let fileName = path.default.basename(pathname);
|
|
2497
|
-
if (!fileName || fileName === "/") fileName = generateTimestampedFilename(getExtensionFromMimeType(mimeType));
|
|
2498
|
-
else if (!fileName.includes(".")) fileName = generateTimestampedFilename(getExtensionFromMimeType(mimeType));
|
|
2499
|
-
return {
|
|
2500
|
-
content: content.toString("base64"),
|
|
2501
|
-
mimeType,
|
|
2502
|
-
fileName
|
|
2503
|
-
};
|
|
2504
|
-
};
|
|
2505
|
-
const uploadFileToS3 = async (fileName, content, toolSlug, toolkitSlug, mimeType, client) => {
|
|
2506
|
-
const response = await client.files.createPresignedURL({
|
|
2507
|
-
filename: fileName,
|
|
2508
|
-
mimetype: mimeType,
|
|
2509
|
-
md5: crypto.default.createHash("md5").update(Buffer.from(content, "base64")).digest("hex"),
|
|
2510
|
-
tool_slug: toolSlug,
|
|
2511
|
-
toolkit_slug: toolkitSlug
|
|
2512
|
-
});
|
|
2513
|
-
const { key, type } = response;
|
|
2514
|
-
if (type === "new" || type === "update") {
|
|
2515
|
-
logger_default.debug(`Uploading ${key} file to S3: ${key}`);
|
|
2516
|
-
const buffer = Buffer.from(content, "base64");
|
|
2517
|
-
const signedURL = response.type === "update" ? response.update_presigned_url : response.new_presigned_url;
|
|
2518
|
-
const uploadResponse = await fetch(signedURL, {
|
|
2519
|
-
method: "PUT",
|
|
2520
|
-
body: buffer,
|
|
2521
|
-
headers: {
|
|
2522
|
-
"Content-Type": mimeType,
|
|
2523
|
-
"Content-Length": buffer.length.toString()
|
|
2524
|
-
}
|
|
2525
|
-
});
|
|
2526
|
-
if (!uploadResponse.ok) throw new Error(`Failed to upload file to S3: ${uploadResponse.statusText}`);
|
|
2527
|
-
} else logger_default.debug(`File already exists in S3: ${key}`);
|
|
2528
|
-
return key;
|
|
2529
|
-
};
|
|
2530
|
-
const readFile = async (file) => {
|
|
2531
|
-
if (file instanceof File) {
|
|
2532
|
-
const content = await file.arrayBuffer();
|
|
2533
|
-
return {
|
|
2534
|
-
fileName: file.name,
|
|
2535
|
-
content: Buffer.from(content).toString("base64"),
|
|
2536
|
-
mimeType: file.type
|
|
2537
|
-
};
|
|
2538
|
-
} else if (typeof file === "string") if (file.startsWith("http")) return await readFileContentFromURL(file);
|
|
2539
|
-
else return await readFileContent(file);
|
|
2540
|
-
throw new Error("Invalid file type");
|
|
2541
|
-
};
|
|
2542
|
-
const getFileDataAfterUploadingToS3 = async (file, { toolSlug, toolkitSlug, client }) => {
|
|
2543
|
-
if (!file) throw new Error("Either path or blob must be provided");
|
|
2544
|
-
const fileData = await readFile(file);
|
|
2545
|
-
logger_default.debug(`Uploading file to S3...`);
|
|
2546
|
-
const s3key = await uploadFileToS3(path.default.basename(fileData.fileName), fileData.content, toolSlug, toolkitSlug, fileData.mimeType, client);
|
|
2547
|
-
logger_default.debug(`Done! File uploaded to S3: ${s3key}`, JSON.stringify(fileData, null, 2));
|
|
2548
|
-
return {
|
|
2549
|
-
name: fileData.fileName,
|
|
2550
|
-
mimetype: fileData.mimeType,
|
|
2551
|
-
s3key
|
|
2552
|
-
};
|
|
2553
|
-
};
|
|
2554
|
-
const downloadFileFromS3 = async ({ toolSlug, s3Url, mimeType }) => {
|
|
2555
|
-
const response = await fetch(s3Url);
|
|
2556
|
-
if (!response.ok) throw new Error(`Failed to download file: ${response.statusText}`);
|
|
2557
|
-
const data = await response.arrayBuffer();
|
|
2558
|
-
const fileName = generateTimestampedFilename(getExtensionFromMimeType(mimeType), `${toolSlug}_`);
|
|
2559
|
-
return {
|
|
2560
|
-
name: fileName,
|
|
2561
|
-
mimeType,
|
|
2562
|
-
s3Url,
|
|
2563
|
-
filePath: saveFile(fileName, Buffer.from(data), true)
|
|
2564
|
-
};
|
|
2565
|
-
};
|
|
2566
|
-
/**
|
|
2567
|
-
* Gets the Composio directory.
|
|
2568
|
-
* @param createDirIfNotExists - Whether to create the directory if it doesn't exist.
|
|
2569
|
-
* @returns The path to the Composio directory.
|
|
2570
|
-
*/
|
|
2571
|
-
const getComposioDir = (createDirIfNotExists = false) => {
|
|
2572
|
-
try {
|
|
2573
|
-
const os = require("os");
|
|
2574
|
-
const path$1 = require("path");
|
|
2575
|
-
const fs = require("fs");
|
|
2576
|
-
const composioDir = path$1.join(os.homedir(), COMPOSIO_DIR);
|
|
2577
|
-
if (createDirIfNotExists && !fs.existsSync(composioDir)) fs.mkdirSync(composioDir, { recursive: true });
|
|
2578
|
-
return composioDir;
|
|
2579
|
-
} catch (_error) {
|
|
2580
|
-
return null;
|
|
2581
|
-
}
|
|
2582
|
-
};
|
|
2583
|
-
/**
|
|
2584
|
-
* Gets the Composio temporary files directory.
|
|
2585
|
-
* @param createDirIfNotExists - Whether to create the directory if it doesn't exist.
|
|
2586
|
-
* @returns The path to the Composio temporary files directory.
|
|
2587
|
-
*/
|
|
2588
|
-
const getComposioTempFilesDir = (createDirIfNotExists = false) => {
|
|
2589
|
-
try {
|
|
2590
|
-
const os = require("os");
|
|
2591
|
-
const path$1 = require("path");
|
|
2592
|
-
const fs = require("fs");
|
|
2593
|
-
const composioFilesDir = path$1.join(os.homedir(), COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME);
|
|
2594
|
-
if (createDirIfNotExists && !fs.existsSync(composioFilesDir)) fs.mkdirSync(composioFilesDir, { recursive: true });
|
|
2595
|
-
return composioFilesDir;
|
|
2596
|
-
} catch (_error) {
|
|
2597
|
-
return null;
|
|
2598
|
-
}
|
|
2599
|
-
};
|
|
2600
|
-
/**
|
|
2601
|
-
* Saves a file to the Composio directory.
|
|
2602
|
-
* @param file - The name of the file to save.
|
|
2603
|
-
* @param content - The content of the file to save. Can be a string or Buffer.
|
|
2604
|
-
* @param isTempFile - Whether the file is a temporary file.
|
|
2605
|
-
* @returns The path to the saved file.
|
|
2606
|
-
*/
|
|
2607
|
-
const saveFile = (file, content, isTempFile = false) => {
|
|
2608
|
-
try {
|
|
2609
|
-
const path$1 = require("path");
|
|
2610
|
-
const fs = require("fs");
|
|
2611
|
-
const composioFilesDir = isTempFile ? getComposioTempFilesDir(true) : getComposioDir(true);
|
|
2612
|
-
const filePath = path$1.join(composioFilesDir, path$1.basename(file));
|
|
2613
|
-
logger_default.info(`Saving file to: ${filePath}`);
|
|
2614
|
-
if (Buffer.isBuffer(content)) fs.writeFileSync(filePath, content);
|
|
2615
|
-
else fs.writeFileSync(filePath, content, "utf8");
|
|
2616
|
-
return filePath;
|
|
2617
|
-
} catch (_error) {
|
|
2618
|
-
logger_default.debug(`Error saving file: ${_error}`);
|
|
2619
|
-
return null;
|
|
2620
|
-
}
|
|
2621
|
-
};
|
|
2622
|
-
|
|
2623
1738
|
//#endregion
|
|
2624
1739
|
//#region src/utils/modifiers/FileToolModifier.ts
|
|
2625
1740
|
/**
|
|
@@ -2655,8 +1770,8 @@ const transformProperties = (properties) => {
|
|
|
2655
1770
|
const hydrateFiles = async (value, schema, ctx) => {
|
|
2656
1771
|
if (schema?.file_uploadable) {
|
|
2657
1772
|
if (typeof value !== "string" && !(value instanceof File)) return value;
|
|
2658
|
-
logger_default.debug(`Uploading file "${value}"`);
|
|
2659
|
-
return getFileDataAfterUploadingToS3(value, {
|
|
1773
|
+
require_fileUtils.logger_default.debug(`Uploading file "${value}"`);
|
|
1774
|
+
return require_fileUtils.getFileDataAfterUploadingToS3(value, {
|
|
2660
1775
|
toolSlug: ctx.toolSlug,
|
|
2661
1776
|
toolkitSlug: ctx.toolkitSlug,
|
|
2662
1777
|
client: ctx.client
|
|
@@ -2701,13 +1816,13 @@ const hydrateDownloads = async (value, ctx) => {
|
|
|
2701
1816
|
if (isPlainObject(value) && typeof value.s3url === "string") {
|
|
2702
1817
|
const { s3url, mimetype } = value;
|
|
2703
1818
|
try {
|
|
2704
|
-
logger_default.debug(`Downloading from S3: ${s3url}`);
|
|
2705
|
-
const dl = await downloadFileFromS3({
|
|
1819
|
+
require_fileUtils.logger_default.debug(`Downloading from S3: ${s3url}`);
|
|
1820
|
+
const dl = await require_fileUtils.downloadFileFromS3({
|
|
2706
1821
|
toolSlug: ctx.toolSlug,
|
|
2707
1822
|
s3Url: s3url,
|
|
2708
1823
|
mimeType: mimetype ?? "application/octet-stream"
|
|
2709
1824
|
});
|
|
2710
|
-
logger_default.debug(`Downloaded → ${dl.filePath}`);
|
|
1825
|
+
require_fileUtils.logger_default.debug(`Downloaded → ${dl.filePath}`);
|
|
2711
1826
|
return {
|
|
2712
1827
|
uri: dl.filePath,
|
|
2713
1828
|
file_downloaded: dl.filePath ? true : false,
|
|
@@ -2715,7 +1830,7 @@ const hydrateDownloads = async (value, ctx) => {
|
|
|
2715
1830
|
mimeType: dl.mimeType
|
|
2716
1831
|
};
|
|
2717
1832
|
} catch (err) {
|
|
2718
|
-
logger_default.error(`Download failed: ${s3url}`, { cause: err });
|
|
1833
|
+
require_fileUtils.logger_default.error(`Download failed: ${s3url}`, { cause: err });
|
|
2719
1834
|
return {
|
|
2720
1835
|
uri: "",
|
|
2721
1836
|
file_downloaded: false,
|
|
@@ -2846,7 +1961,7 @@ var Tools = class {
|
|
|
2846
1961
|
this.provider._setExecuteToolFn(this.createExecuteFnForProviders());
|
|
2847
1962
|
this.getRawComposioToolBySlug = this.getRawComposioToolBySlug.bind(this);
|
|
2848
1963
|
this.getRawComposioTools = this.getRawComposioTools.bind(this);
|
|
2849
|
-
telemetry.instrument(this, "Tools");
|
|
1964
|
+
require_fileUtils.telemetry.instrument(this, "Tools");
|
|
2850
1965
|
}
|
|
2851
1966
|
/**
|
|
2852
1967
|
* Transforms tool data from snake_case API format to camelCase for internal SDK use.
|
|
@@ -3020,7 +2135,7 @@ var Tools = class {
|
|
|
3020
2135
|
..."authConfigIds" in queryParams.data ? { auth_config_ids: queryParams.data.authConfigIds } : {},
|
|
3021
2136
|
toolkit_versions: this.toolkitVersions
|
|
3022
2137
|
};
|
|
3023
|
-
logger_default.debug(`Fetching tools with filters: ${JSON.stringify(filters, null, 2)}`);
|
|
2138
|
+
require_fileUtils.logger_default.debug(`Fetching tools with filters: ${JSON.stringify(filters, null, 2)}`);
|
|
3024
2139
|
const tools = await this.client.tools.list(filters);
|
|
3025
2140
|
if (!tools) return [];
|
|
3026
2141
|
const caseTransformedTools = tools.items.map((tool) => this.transformToolCases(tool));
|
|
@@ -3123,9 +2238,9 @@ var Tools = class {
|
|
|
3123
2238
|
async getRawComposioToolBySlug(slug, options) {
|
|
3124
2239
|
const customTool = await this.customTools.getCustomToolBySlug(slug);
|
|
3125
2240
|
if (customTool) {
|
|
3126
|
-
logger_default.debug(`Found ${slug} to be a custom tool`, JSON.stringify(customTool, null, 2));
|
|
2241
|
+
require_fileUtils.logger_default.debug(`Found ${slug} to be a custom tool`, JSON.stringify(customTool, null, 2));
|
|
3127
2242
|
return customTool;
|
|
3128
|
-
} else logger_default.debug(`Tool ${slug} is not a custom tool. Fetching from Composio API`);
|
|
2243
|
+
} else require_fileUtils.logger_default.debug(`Tool ${slug} is not a custom tool. Fetching from Composio API`);
|
|
3129
2244
|
let tool;
|
|
3130
2245
|
try {
|
|
3131
2246
|
tool = await this.client.tools.retrieve(slug, { toolkit_versions: this.toolkitVersions });
|
|
@@ -3715,7 +2830,7 @@ var AuthConfigs = class {
|
|
|
3715
2830
|
client;
|
|
3716
2831
|
constructor(client) {
|
|
3717
2832
|
this.client = client;
|
|
3718
|
-
telemetry.instrument(this, "AuthConfigs");
|
|
2833
|
+
require_fileUtils.telemetry.instrument(this, "AuthConfigs");
|
|
3719
2834
|
}
|
|
3720
2835
|
/**
|
|
3721
2836
|
* Protected getter for the client instance.
|
|
@@ -3983,7 +3098,7 @@ function createConnectionRequest(client, connectedAccountId, status, redirectUrl
|
|
|
3983
3098
|
status: status || ConnectedAccountStatuses.INITIATED,
|
|
3984
3099
|
redirectUrl
|
|
3985
3100
|
};
|
|
3986
|
-
telemetry.instrument(state, "ConnectionRequest");
|
|
3101
|
+
require_fileUtils.telemetry.instrument(state, "ConnectionRequest");
|
|
3987
3102
|
/**
|
|
3988
3103
|
* Waits for the connection request to complete and become active.
|
|
3989
3104
|
*
|
|
@@ -4018,7 +3133,7 @@ function createConnectionRequest(client, connectedAccountId, status, redirectUrl
|
|
|
4018
3133
|
return transformConnectedAccountResponse(response);
|
|
4019
3134
|
}
|
|
4020
3135
|
} catch (error) {
|
|
4021
|
-
if (error instanceof
|
|
3136
|
+
if (error instanceof _composio_client.default.NotFoundError) throw new ComposioConnectedAccountNotFoundError(`Connected account with id ${state.id} not found`, { meta: { connectedAccountId: state.id } });
|
|
4022
3137
|
else throw error;
|
|
4023
3138
|
}
|
|
4024
3139
|
const terminalErrorStates = [ConnectedAccountStatuses.FAILED, ConnectedAccountStatuses.EXPIRED];
|
|
@@ -4059,7 +3174,7 @@ var ConnectedAccounts = class {
|
|
|
4059
3174
|
client;
|
|
4060
3175
|
constructor(client) {
|
|
4061
3176
|
this.client = client;
|
|
4062
|
-
telemetry.instrument(this, "ConnectedAccounts");
|
|
3177
|
+
require_fileUtils.telemetry.instrument(this, "ConnectedAccounts");
|
|
4063
3178
|
}
|
|
4064
3179
|
/**
|
|
4065
3180
|
* Lists all connected accounts based on provided filter criteria.
|
|
@@ -4159,7 +3274,7 @@ var ConnectedAccounts = class {
|
|
|
4159
3274
|
authConfigIds: [authConfigId]
|
|
4160
3275
|
});
|
|
4161
3276
|
if (connectedAccount.items.length > 0 && !options?.allowMultiple) throw new ComposioMultipleConnectedAccountsError(`Multiple connected accounts found for user ${userId} in auth config ${authConfigId}. Please use the allowMultiple option to allow multiple connected accounts.`);
|
|
4162
|
-
else if (connectedAccount.items.length > 0) logger_default.warn(`[Warn:AllowMultiple] Multiple connected accounts found for user ${userId} in auth config ${authConfigId}`);
|
|
3277
|
+
else if (connectedAccount.items.length > 0) require_fileUtils.logger_default.warn(`[Warn:AllowMultiple] Multiple connected accounts found for user ${userId} in auth config ${authConfigId}`);
|
|
4163
3278
|
const state = options?.config ?? void 0;
|
|
4164
3279
|
const response = await this.client.connectedAccounts.create({
|
|
4165
3280
|
auth_config: { id: authConfigId },
|
|
@@ -4447,7 +3562,7 @@ var Toolkits = class {
|
|
|
4447
3562
|
constructor(client) {
|
|
4448
3563
|
this.client = client;
|
|
4449
3564
|
this.authorize = this.authorize.bind(this);
|
|
4450
|
-
telemetry.instrument(this, "Toolkits");
|
|
3565
|
+
require_fileUtils.telemetry.instrument(this, "Toolkits");
|
|
4451
3566
|
}
|
|
4452
3567
|
/**
|
|
4453
3568
|
* Retrieves a list of toolkits based on the provided query parameters.
|
|
@@ -4515,7 +3630,7 @@ var Toolkits = class {
|
|
|
4515
3630
|
async getAuthConfigFields(toolkitSlug, authScheme, authConfigType, requiredOnly) {
|
|
4516
3631
|
const toolkit = await this.getToolkitBySlug(toolkitSlug);
|
|
4517
3632
|
if (!toolkit.authConfigDetails) throw new ComposioAuthConfigNotFoundError("No auth config found for toolkit", { meta: { toolkitSlug } });
|
|
4518
|
-
if (toolkit.authConfigDetails.length > 1 && !authScheme) logger_default.warn(`Multiple auth configs found for ${toolkitSlug}, please specify the auth scheme to get details of specific auth scheme. Selecting the first scheme by default.`, { meta: { toolkitSlug } });
|
|
3633
|
+
if (toolkit.authConfigDetails.length > 1 && !authScheme) require_fileUtils.logger_default.warn(`Multiple auth configs found for ${toolkitSlug}, please specify the auth scheme to get details of specific auth scheme. Selecting the first scheme by default.`, { meta: { toolkitSlug } });
|
|
4519
3634
|
const authConfig = authScheme ? toolkit.authConfigDetails.find((authConfig$1) => authConfig$1.mode === authScheme) : toolkit.authConfigDetails[0];
|
|
4520
3635
|
if (!authConfig) throw new ComposioAuthConfigNotFoundError(`Auth schema ${authScheme} not found for toolkit ${toolkitSlug} with auth scheme ${authScheme}`, { meta: {
|
|
4521
3636
|
toolkitSlug,
|
|
@@ -4594,7 +3709,7 @@ var Toolkits = class {
|
|
|
4594
3709
|
name: `${toolkit.name} Auth Config`
|
|
4595
3710
|
})).id;
|
|
4596
3711
|
} catch (error) {
|
|
4597
|
-
if (error instanceof
|
|
3712
|
+
if (error instanceof _composio_client.default.APIError && error.status === 400) throw new ComposioAuthConfigNotFoundError(`No Default auth config found for toolkit ${toolkitSlug}`, {
|
|
4598
3713
|
meta: { toolkitSlug },
|
|
4599
3714
|
cause: error,
|
|
4600
3715
|
possibleFixes: [`Please Create an auth config for the toolkit ${toolkitSlug} via the dashboard`]
|
|
@@ -4705,12 +3820,66 @@ const TriggersTypeListResponseSchema = zod_v3.z.object({
|
|
|
4705
3820
|
totalPages: zod_v3.z.number()
|
|
4706
3821
|
});
|
|
4707
3822
|
/**
|
|
3823
|
+
* Webhook payload schemas for V1, V2, V3 versions
|
|
3824
|
+
* These schemas represent the raw payload structure sent by Composio's webhook system
|
|
3825
|
+
*/
|
|
3826
|
+
/** V1 webhook payload - legacy format */
|
|
3827
|
+
const WebhookPayloadV1Schema = zod_v3.z.object({
|
|
3828
|
+
trigger_name: zod_v3.z.string(),
|
|
3829
|
+
connection_id: zod_v3.z.string(),
|
|
3830
|
+
trigger_id: zod_v3.z.string(),
|
|
3831
|
+
payload: zod_v3.z.record(zod_v3.z.unknown()),
|
|
3832
|
+
log_id: zod_v3.z.string()
|
|
3833
|
+
});
|
|
3834
|
+
/** V2 webhook payload - includes timestamp and nested data */
|
|
3835
|
+
const WebhookPayloadV2Schema = zod_v3.z.object({
|
|
3836
|
+
type: zod_v3.z.string(),
|
|
3837
|
+
timestamp: zod_v3.z.string(),
|
|
3838
|
+
log_id: zod_v3.z.string(),
|
|
3839
|
+
data: zod_v3.z.object({
|
|
3840
|
+
connection_id: zod_v3.z.string(),
|
|
3841
|
+
connection_nano_id: zod_v3.z.string(),
|
|
3842
|
+
trigger_nano_id: zod_v3.z.string(),
|
|
3843
|
+
trigger_id: zod_v3.z.string(),
|
|
3844
|
+
user_id: zod_v3.z.string()
|
|
3845
|
+
}).passthrough()
|
|
3846
|
+
});
|
|
3847
|
+
/** V3 webhook payload - current format with metadata */
|
|
3848
|
+
const WebhookPayloadV3Schema = zod_v3.z.object({
|
|
3849
|
+
id: zod_v3.z.string(),
|
|
3850
|
+
timestamp: zod_v3.z.string(),
|
|
3851
|
+
type: zod_v3.z.literal("composio.trigger.message"),
|
|
3852
|
+
metadata: zod_v3.z.object({
|
|
3853
|
+
log_id: zod_v3.z.string(),
|
|
3854
|
+
trigger_slug: zod_v3.z.string(),
|
|
3855
|
+
trigger_id: zod_v3.z.string(),
|
|
3856
|
+
connected_account_id: zod_v3.z.string(),
|
|
3857
|
+
auth_config_id: zod_v3.z.string(),
|
|
3858
|
+
user_id: zod_v3.z.string()
|
|
3859
|
+
}),
|
|
3860
|
+
data: zod_v3.z.record(zod_v3.z.unknown())
|
|
3861
|
+
});
|
|
3862
|
+
/** Union of all webhook payload versions */
|
|
3863
|
+
const WebhookPayloadSchema = zod_v3.z.union([
|
|
3864
|
+
WebhookPayloadV3Schema,
|
|
3865
|
+
WebhookPayloadV2Schema,
|
|
3866
|
+
WebhookPayloadV1Schema
|
|
3867
|
+
]);
|
|
3868
|
+
/** Webhook version enum */
|
|
3869
|
+
const WebhookVersions = {
|
|
3870
|
+
V1: "V1",
|
|
3871
|
+
V2: "V2",
|
|
3872
|
+
V3: "V3"
|
|
3873
|
+
};
|
|
3874
|
+
/**
|
|
4708
3875
|
* Parameters for verifying a webhook signature
|
|
4709
3876
|
*/
|
|
4710
3877
|
const VerifyWebhookParamsSchema = zod_v3.z.object({
|
|
3878
|
+
id: zod_v3.z.string(),
|
|
4711
3879
|
payload: zod_v3.z.string(),
|
|
4712
|
-
signature: zod_v3.z.string(),
|
|
4713
3880
|
secret: zod_v3.z.string(),
|
|
3881
|
+
signature: zod_v3.z.string(),
|
|
3882
|
+
timestamp: zod_v3.z.string(),
|
|
4714
3883
|
tolerance: zod_v3.z.number().optional().default(300)
|
|
4715
3884
|
});
|
|
4716
3885
|
|
|
@@ -4744,7 +3913,7 @@ var InternalService = class {
|
|
|
4744
3913
|
projectId: response.project_id,
|
|
4745
3914
|
pusherCluster: response.pusher_cluster
|
|
4746
3915
|
});
|
|
4747
|
-
logger_default.debug(`[InternalService] SDK realtime credentials: ${JSON.stringify(parsedResponse, null, 2)}`);
|
|
3916
|
+
require_fileUtils.logger_default.debug(`[InternalService] SDK realtime credentials: ${JSON.stringify(parsedResponse, null, 2)}`);
|
|
4748
3917
|
if (!parsedResponse.success) throw new ValidationError(`Failed to parse SDK realtime credentials`, { cause: parsedResponse.error });
|
|
4749
3918
|
return parsedResponse.data;
|
|
4750
3919
|
}
|
|
@@ -4765,7 +3934,7 @@ var PusherService = class {
|
|
|
4765
3934
|
this.composioClient = client;
|
|
4766
3935
|
this.pusherBaseURL = client.baseURL;
|
|
4767
3936
|
this.apiKey = client.apiKey ?? process.env.COMPOSIO_API_KEY ?? "";
|
|
4768
|
-
telemetry.instrument(this, "PusherService");
|
|
3937
|
+
require_fileUtils.telemetry.instrument(this, "PusherService");
|
|
4769
3938
|
}
|
|
4770
3939
|
/**
|
|
4771
3940
|
* Creates a Pusher client
|
|
@@ -4786,7 +3955,7 @@ var PusherService = class {
|
|
|
4786
3955
|
this.pusherKey = sdkRealtimeCredentials.pusherKey;
|
|
4787
3956
|
this.pusherCluster = sdkRealtimeCredentials.pusherCluster;
|
|
4788
3957
|
this.pusherChannel = `private-${this.clientId}_triggers`;
|
|
4789
|
-
logger_default.debug(`[PusherService] Creating Pusher client for client ID: ${this.clientId} in cluster ${this.pusherCluster}`);
|
|
3958
|
+
require_fileUtils.logger_default.debug(`[PusherService] Creating Pusher client for client ID: ${this.clientId} in cluster ${this.pusherCluster}`);
|
|
4790
3959
|
try {
|
|
4791
3960
|
const { default: Pusher } = await import("pusher-js");
|
|
4792
3961
|
this.pusherClient = new Pusher(this.pusherKey, {
|
|
@@ -4830,19 +3999,19 @@ var PusherService = class {
|
|
|
4830
3999
|
callback(JSON.parse(ev.chunks.join("")));
|
|
4831
4000
|
} catch (parseError) {
|
|
4832
4001
|
const errorMessage = parseError instanceof Error ? parseError.message : String(parseError);
|
|
4833
|
-
logger_default.error("Failed to parse chunked data:", errorMessage);
|
|
4002
|
+
require_fileUtils.logger_default.error("Failed to parse chunked data:", errorMessage);
|
|
4834
4003
|
} finally {
|
|
4835
4004
|
delete events[typedData.id];
|
|
4836
4005
|
}
|
|
4837
4006
|
} catch (error) {
|
|
4838
4007
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
4839
|
-
logger_default.error("Error processing chunked trigger data:", errorMessage);
|
|
4008
|
+
require_fileUtils.logger_default.error("Error processing chunked trigger data:", errorMessage);
|
|
4840
4009
|
if (data && typeof data === "object" && "id" in data) delete events[data.id];
|
|
4841
4010
|
}
|
|
4842
4011
|
});
|
|
4843
4012
|
} catch (error) {
|
|
4844
4013
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
4845
|
-
logger_default.error("Failed to bind chunked events:", error);
|
|
4014
|
+
require_fileUtils.logger_default.error("Failed to bind chunked events:", error);
|
|
4846
4015
|
throw new Error(`Failed to bind chunked events: ${errorMessage}`);
|
|
4847
4016
|
}
|
|
4848
4017
|
}
|
|
@@ -4858,7 +4027,7 @@ var PusherService = class {
|
|
|
4858
4027
|
*/
|
|
4859
4028
|
async subscribe(fn) {
|
|
4860
4029
|
try {
|
|
4861
|
-
logger_default.debug(`[PusherService] Subscribing to channel: ${this.pusherChannel}`);
|
|
4030
|
+
require_fileUtils.logger_default.debug(`[PusherService] Subscribing to channel: ${this.pusherChannel}`);
|
|
4862
4031
|
const channel = await (await this.getPusherClient()).subscribe(this.pusherChannel);
|
|
4863
4032
|
channel.bind("pusher:subscription_error", (data) => {
|
|
4864
4033
|
const error = data.error ? String(data.error) : "Unknown subscription error";
|
|
@@ -4869,11 +4038,11 @@ var PusherService = class {
|
|
|
4869
4038
|
fn(data);
|
|
4870
4039
|
} catch (error) {
|
|
4871
4040
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
4872
|
-
logger_default.error("❌ Error in trigger callback:", errorMessage);
|
|
4041
|
+
require_fileUtils.logger_default.error("❌ Error in trigger callback:", errorMessage);
|
|
4873
4042
|
}
|
|
4874
4043
|
};
|
|
4875
4044
|
this.bindWithChunking(channel, "trigger_to_client", safeCallback);
|
|
4876
|
-
logger_default.info(`✅ Subscribed to triggers. You should start receiving events now.`);
|
|
4045
|
+
require_fileUtils.logger_default.info(`✅ Subscribed to triggers. You should start receiving events now.`);
|
|
4877
4046
|
} catch (error) {
|
|
4878
4047
|
throw new ComposioFailedToSubscribeToPusherChannelError("Failed to subscribe to Pusher channel", { cause: error });
|
|
4879
4048
|
}
|
|
@@ -4888,9 +4057,9 @@ var PusherService = class {
|
|
|
4888
4057
|
*/
|
|
4889
4058
|
async unsubscribe() {
|
|
4890
4059
|
try {
|
|
4891
|
-
logger_default.debug(`[PusherService] Unsubscribing from channel: ${this.pusherChannel}`);
|
|
4060
|
+
require_fileUtils.logger_default.debug(`[PusherService] Unsubscribing from channel: ${this.pusherChannel}`);
|
|
4892
4061
|
await (await this.getPusherClient()).unsubscribe(this.pusherChannel);
|
|
4893
|
-
logger_default.info(`✅ Unsubscribed from triggers.`);
|
|
4062
|
+
require_fileUtils.logger_default.info(`✅ Unsubscribed from triggers.`);
|
|
4894
4063
|
} catch (error) {
|
|
4895
4064
|
throw new ComposioFailedToSubscribeToPusherChannelError("Failed to unsubscribe from Pusher channel", { cause: error });
|
|
4896
4065
|
}
|
|
@@ -4991,7 +4160,7 @@ var Triggers = class {
|
|
|
4991
4160
|
this.client = client;
|
|
4992
4161
|
this.pusherService = new PusherService(client);
|
|
4993
4162
|
this.toolkitVersions = config?.toolkitVersions ?? "latest";
|
|
4994
|
-
telemetry.instrument(this, "Triggers");
|
|
4163
|
+
require_fileUtils.telemetry.instrument(this, "Triggers");
|
|
4995
4164
|
}
|
|
4996
4165
|
/**
|
|
4997
4166
|
* Fetch list of all the active triggers
|
|
@@ -5041,7 +4210,7 @@ var Triggers = class {
|
|
|
5041
4210
|
triggerType = await this.getType(slug);
|
|
5042
4211
|
toolkitSlug = triggerType.toolkit.slug;
|
|
5043
4212
|
} catch (error) {
|
|
5044
|
-
if (error instanceof
|
|
4213
|
+
if (error instanceof _composio_client.APIError && (error.status === 400 || error.status === 404)) throw new ComposioTriggerTypeNotFoundError(`Trigger type ${slug} not found`, {
|
|
5045
4214
|
cause: error,
|
|
5046
4215
|
possibleFixes: [
|
|
5047
4216
|
`Please check the trigger slug`,
|
|
@@ -5068,10 +4237,10 @@ var Triggers = class {
|
|
|
5068
4237
|
});
|
|
5069
4238
|
if (!connectedAccountId) {
|
|
5070
4239
|
connectedAccountId = connectedAccounts[0].id;
|
|
5071
|
-
logger_default.warn(`[Warn] Multiple connected accounts found for user ${userId}, using the first one. Pass connectedAccountId to select a specific account.`);
|
|
4240
|
+
require_fileUtils.logger_default.warn(`[Warn] Multiple connected accounts found for user ${userId}, using the first one. Pass connectedAccountId to select a specific account.`);
|
|
5072
4241
|
}
|
|
5073
4242
|
} catch (error) {
|
|
5074
|
-
if (error instanceof
|
|
4243
|
+
if (error instanceof _composio_client.APIError && [400, 404].includes(error.status)) throw new ComposioConnectedAccountNotFoundError(`No connected account found for user ${userId} for toolkit ${toolkitSlug}`, {
|
|
5075
4244
|
cause: error,
|
|
5076
4245
|
possibleFixes: [`Create a new connected account for user ${userId}`]
|
|
5077
4246
|
});
|
|
@@ -5165,30 +4334,30 @@ var Triggers = class {
|
|
|
5165
4334
|
*/
|
|
5166
4335
|
shouldSendTriggerAfterFilters(filters, data) {
|
|
5167
4336
|
if (filters.toolkits?.length && !filters.toolkits.map((toolkit) => toolkit.toLowerCase()).includes(data.toolkitSlug.toLowerCase())) {
|
|
5168
|
-
logger_default.debug("Trigger does not match toolkits filter", JSON.stringify(filters.toolkits, null, 2));
|
|
4337
|
+
require_fileUtils.logger_default.debug("Trigger does not match toolkits filter", JSON.stringify(filters.toolkits, null, 2));
|
|
5169
4338
|
return false;
|
|
5170
4339
|
}
|
|
5171
4340
|
if (filters.triggerId && filters.triggerId !== data.id) {
|
|
5172
|
-
logger_default.debug("Trigger does not match triggerId filter", JSON.stringify(filters.triggerId, null, 2));
|
|
4341
|
+
require_fileUtils.logger_default.debug("Trigger does not match triggerId filter", JSON.stringify(filters.triggerId, null, 2));
|
|
5173
4342
|
return false;
|
|
5174
4343
|
}
|
|
5175
4344
|
if (filters.connectedAccountId && filters.connectedAccountId !== data.metadata.connectedAccount.id) {
|
|
5176
|
-
logger_default.debug("Trigger does not match connectedAccountId filter", JSON.stringify(filters.connectedAccountId, null, 2));
|
|
4345
|
+
require_fileUtils.logger_default.debug("Trigger does not match connectedAccountId filter", JSON.stringify(filters.connectedAccountId, null, 2));
|
|
5177
4346
|
return false;
|
|
5178
4347
|
}
|
|
5179
4348
|
if (filters.triggerSlug?.length && !filters.triggerSlug.map((triggerSlug) => triggerSlug.toLowerCase()).includes(data.triggerSlug.toLowerCase())) {
|
|
5180
|
-
logger_default.debug("Trigger does not match triggerSlug filter", JSON.stringify(filters.triggerSlug, null, 2));
|
|
4349
|
+
require_fileUtils.logger_default.debug("Trigger does not match triggerSlug filter", JSON.stringify(filters.triggerSlug, null, 2));
|
|
5181
4350
|
return false;
|
|
5182
4351
|
}
|
|
5183
4352
|
if (filters.triggerData && filters.triggerData !== data.metadata.triggerData) {
|
|
5184
|
-
logger_default.debug("Trigger does not match triggerData filter", JSON.stringify(filters.triggerData, null, 2));
|
|
4353
|
+
require_fileUtils.logger_default.debug("Trigger does not match triggerData filter", JSON.stringify(filters.triggerData, null, 2));
|
|
5185
4354
|
return false;
|
|
5186
4355
|
}
|
|
5187
4356
|
if (filters.userId && filters.userId !== data.metadata.connectedAccount.userId) {
|
|
5188
|
-
logger_default.debug("Trigger does not match userId filter", JSON.stringify(filters.userId, null, 2));
|
|
4357
|
+
require_fileUtils.logger_default.debug("Trigger does not match userId filter", JSON.stringify(filters.userId, null, 2));
|
|
5189
4358
|
return false;
|
|
5190
4359
|
}
|
|
5191
|
-
logger_default.debug("Trigger matches all filters", JSON.stringify(filters, null, 2));
|
|
4360
|
+
require_fileUtils.logger_default.debug("Trigger matches all filters", JSON.stringify(filters, null, 2));
|
|
5192
4361
|
return true;
|
|
5193
4362
|
}
|
|
5194
4363
|
/**
|
|
@@ -5209,16 +4378,16 @@ var Triggers = class {
|
|
|
5209
4378
|
if (!fn) throw new Error("Function is required for trigger subscription");
|
|
5210
4379
|
const parsedFilters = TriggerSubscribeParamSchema.safeParse(filters);
|
|
5211
4380
|
if (!parsedFilters.success) throw new ValidationError(`Invalid parameters passed to subscribe to triggers`, { cause: parsedFilters.error });
|
|
5212
|
-
logger_default.debug("🔄 Subscribing to triggers with filters: ", JSON.stringify(filters, null, 2));
|
|
4381
|
+
require_fileUtils.logger_default.debug("🔄 Subscribing to triggers with filters: ", JSON.stringify(filters, null, 2));
|
|
5213
4382
|
await this.pusherService.subscribe((_data) => {
|
|
5214
|
-
logger_default.debug("Received raw trigger data", JSON.stringify(_data, null, 2));
|
|
4383
|
+
require_fileUtils.logger_default.debug("Received raw trigger data", JSON.stringify(_data, null, 2));
|
|
5215
4384
|
const parsedData = transformIncomingTriggerPayload(_data);
|
|
5216
4385
|
if (this.shouldSendTriggerAfterFilters(parsedFilters.data, parsedData)) try {
|
|
5217
4386
|
fn(parsedData);
|
|
5218
4387
|
} catch (error) {
|
|
5219
|
-
logger_default.error("❌ Error in trigger callback:", error);
|
|
4388
|
+
require_fileUtils.logger_default.error("❌ Error in trigger callback:", error);
|
|
5220
4389
|
}
|
|
5221
|
-
else logger_default.debug("Trigger does not match filters", JSON.stringify(parsedFilters.data, null, 2));
|
|
4390
|
+
else require_fileUtils.logger_default.debug("Trigger does not match filters", JSON.stringify(parsedFilters.data, null, 2));
|
|
5222
4391
|
});
|
|
5223
4392
|
}
|
|
5224
4393
|
/**
|
|
@@ -5242,15 +4411,20 @@ var Triggers = class {
|
|
|
5242
4411
|
* Verify an incoming webhook payload and signature.
|
|
5243
4412
|
*
|
|
5244
4413
|
* This method validates that the webhook request is authentic by:
|
|
5245
|
-
* 1. Verifying the HMAC-SHA256 signature matches the payload
|
|
4414
|
+
* 1. Verifying the HMAC-SHA256 signature matches the payload using the correct signing format
|
|
5246
4415
|
* 2. Optionally checking that the webhook timestamp is within the tolerance window
|
|
5247
4416
|
*
|
|
4417
|
+
* The signature is computed as: `HMAC-SHA256(${webhookId}.${webhookTimestamp}.${payload}, secret)`
|
|
4418
|
+
* and is expected in the format: `v1,base64EncodedSignature`
|
|
4419
|
+
*
|
|
5248
4420
|
* @param {VerifyWebhookParams} params - The verification parameters
|
|
5249
4421
|
* @param {string} params.payload - The raw webhook payload as a string (request body)
|
|
5250
|
-
* @param {string} params.signature - The signature from the webhook
|
|
4422
|
+
* @param {string} params.signature - The signature from the 'webhook-signature' header
|
|
5251
4423
|
* @param {string} params.secret - The webhook secret used to sign the payload
|
|
4424
|
+
* @param {string} params.webhookId - The webhook ID from the 'webhook-id' header
|
|
4425
|
+
* @param {string} params.webhookTimestamp - The timestamp from the 'webhook-timestamp' header (Unix seconds)
|
|
5252
4426
|
* @param {number} [params.tolerance=300] - Maximum allowed age of the webhook in seconds (default: 5 minutes). Set to 0 to disable timestamp validation.
|
|
5253
|
-
* @returns {VerifyWebhookResult} The verified and parsed webhook payload
|
|
4427
|
+
* @returns {VerifyWebhookResult} The verified and parsed webhook payload with version information
|
|
5254
4428
|
*
|
|
5255
4429
|
* @throws {ValidationError} If the parameters are invalid
|
|
5256
4430
|
* @throws {ComposioWebhookSignatureVerificationError} If the signature verification fails
|
|
@@ -5261,14 +4435,17 @@ var Triggers = class {
|
|
|
5261
4435
|
* // In an Express.js webhook handler
|
|
5262
4436
|
* app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
|
|
5263
4437
|
* try {
|
|
5264
|
-
* const
|
|
4438
|
+
* const result = composio.triggers.verifyWebhook({
|
|
5265
4439
|
* payload: req.body.toString(),
|
|
5266
|
-
* signature: req.headers['
|
|
4440
|
+
* signature: req.headers['webhook-signature'] as string,
|
|
4441
|
+
* webhookId: req.headers['webhook-id'] as string,
|
|
4442
|
+
* webhookTimestamp: req.headers['webhook-timestamp'] as string,
|
|
5267
4443
|
* secret: process.env.COMPOSIO_WEBHOOK_SECRET!,
|
|
5268
4444
|
* });
|
|
5269
4445
|
*
|
|
5270
4446
|
* // Process the verified payload
|
|
5271
|
-
* console.log('
|
|
4447
|
+
* console.log('Webhook version:', result.version);
|
|
4448
|
+
* console.log('Received trigger:', result.payload.triggerSlug);
|
|
5272
4449
|
* res.status(200).send('OK');
|
|
5273
4450
|
* } catch (error) {
|
|
5274
4451
|
* console.error('Webhook verification failed:', error);
|
|
@@ -5280,45 +4457,190 @@ var Triggers = class {
|
|
|
5280
4457
|
verifyWebhook(params) {
|
|
5281
4458
|
const parsedParams = VerifyWebhookParamsSchema.safeParse(params);
|
|
5282
4459
|
if (!parsedParams.success) throw new ValidationError("Invalid parameters passed to verifyWebhook", { cause: parsedParams.error });
|
|
5283
|
-
const { payload, signature, secret, tolerance } = parsedParams.data;
|
|
5284
|
-
this.
|
|
5285
|
-
|
|
4460
|
+
const { payload, signature, secret, id: webhookId, timestamp: webhookTimestamp, tolerance } = parsedParams.data;
|
|
4461
|
+
if (tolerance > 0) this.validateWebhookTimestamp(webhookTimestamp, tolerance);
|
|
4462
|
+
this.verifyWebhookSignature(webhookId, webhookTimestamp, payload, signature, secret);
|
|
4463
|
+
const { version: version$1, rawPayload, normalizedPayload } = this.parseWebhookPayload(payload);
|
|
4464
|
+
return {
|
|
4465
|
+
version: version$1,
|
|
4466
|
+
payload: normalizedPayload,
|
|
4467
|
+
rawPayload
|
|
4468
|
+
};
|
|
4469
|
+
}
|
|
4470
|
+
/**
|
|
4471
|
+
* Parses the webhook payload and detects its version (V1, V2, or V3)
|
|
4472
|
+
* @private
|
|
4473
|
+
*/
|
|
4474
|
+
parseWebhookPayload(payload) {
|
|
4475
|
+
let jsonPayload;
|
|
5286
4476
|
try {
|
|
5287
|
-
|
|
4477
|
+
jsonPayload = JSON.parse(payload);
|
|
5288
4478
|
} catch (error) {
|
|
5289
4479
|
throw new ComposioWebhookPayloadError("Failed to parse webhook payload as JSON", { cause: error });
|
|
5290
4480
|
}
|
|
5291
|
-
const
|
|
5292
|
-
if (
|
|
5293
|
-
|
|
4481
|
+
const v3Result = WebhookPayloadV3Schema.safeParse(jsonPayload);
|
|
4482
|
+
if (v3Result.success) return {
|
|
4483
|
+
version: WebhookVersions.V3,
|
|
4484
|
+
rawPayload: v3Result.data,
|
|
4485
|
+
normalizedPayload: this.normalizeV3Payload(v3Result.data)
|
|
4486
|
+
};
|
|
4487
|
+
const v2Result = WebhookPayloadV2Schema.safeParse(jsonPayload);
|
|
4488
|
+
if (v2Result.success) return {
|
|
4489
|
+
version: WebhookVersions.V2,
|
|
4490
|
+
rawPayload: v2Result.data,
|
|
4491
|
+
normalizedPayload: this.normalizeV2Payload(v2Result.data)
|
|
4492
|
+
};
|
|
4493
|
+
const v1Result = WebhookPayloadV1Schema.safeParse(jsonPayload);
|
|
4494
|
+
if (v1Result.success) return {
|
|
4495
|
+
version: WebhookVersions.V1,
|
|
4496
|
+
rawPayload: v1Result.data,
|
|
4497
|
+
normalizedPayload: this.normalizeV1Payload(v1Result.data)
|
|
4498
|
+
};
|
|
4499
|
+
throw new ComposioWebhookPayloadError("Webhook payload does not match any known version (V1, V2, or V3). Please ensure you are using a supported webhook payload format.", { cause: {
|
|
4500
|
+
v1Error: v1Result.error?.message,
|
|
4501
|
+
v2Error: v2Result.error?.message,
|
|
4502
|
+
v3Error: v3Result.error?.message
|
|
4503
|
+
} });
|
|
4504
|
+
}
|
|
4505
|
+
/**
|
|
4506
|
+
* Normalizes a V1 webhook payload to IncomingTriggerPayload format
|
|
4507
|
+
* @private
|
|
4508
|
+
*/
|
|
4509
|
+
normalizeV1Payload(payload) {
|
|
4510
|
+
const triggerName = payload.trigger_name;
|
|
4511
|
+
const toolkitSlug = triggerName.split("_")[0]?.toUpperCase() || "UNKNOWN";
|
|
4512
|
+
return {
|
|
4513
|
+
id: payload.trigger_id,
|
|
4514
|
+
uuid: payload.trigger_id,
|
|
4515
|
+
triggerSlug: triggerName,
|
|
4516
|
+
toolkitSlug,
|
|
4517
|
+
userId: "",
|
|
4518
|
+
payload: payload.payload,
|
|
4519
|
+
originalPayload: payload.payload,
|
|
4520
|
+
metadata: {
|
|
4521
|
+
id: payload.trigger_id,
|
|
4522
|
+
uuid: payload.trigger_id,
|
|
4523
|
+
toolkitSlug,
|
|
4524
|
+
triggerSlug: triggerName,
|
|
4525
|
+
triggerConfig: {},
|
|
4526
|
+
connectedAccount: {
|
|
4527
|
+
id: payload.connection_id,
|
|
4528
|
+
uuid: payload.connection_id,
|
|
4529
|
+
authConfigId: "",
|
|
4530
|
+
authConfigUUID: "",
|
|
4531
|
+
userId: "",
|
|
4532
|
+
status: "ACTIVE"
|
|
4533
|
+
}
|
|
4534
|
+
}
|
|
4535
|
+
};
|
|
4536
|
+
}
|
|
4537
|
+
/**
|
|
4538
|
+
* Normalizes a V2 webhook payload to IncomingTriggerPayload format
|
|
4539
|
+
* @private
|
|
4540
|
+
*/
|
|
4541
|
+
normalizeV2Payload(payload) {
|
|
4542
|
+
const triggerSlug = payload.type.toUpperCase();
|
|
4543
|
+
const toolkitSlug = triggerSlug.split("_")[0] || "UNKNOWN";
|
|
4544
|
+
const { connection_id, connection_nano_id, trigger_nano_id, trigger_id, user_id, ...restData } = payload.data;
|
|
4545
|
+
return {
|
|
4546
|
+
id: trigger_nano_id,
|
|
4547
|
+
uuid: trigger_id,
|
|
4548
|
+
triggerSlug,
|
|
4549
|
+
toolkitSlug,
|
|
4550
|
+
userId: user_id,
|
|
4551
|
+
payload: restData,
|
|
4552
|
+
originalPayload: restData,
|
|
4553
|
+
metadata: {
|
|
4554
|
+
id: trigger_nano_id,
|
|
4555
|
+
uuid: trigger_id,
|
|
4556
|
+
toolkitSlug,
|
|
4557
|
+
triggerSlug,
|
|
4558
|
+
triggerConfig: {},
|
|
4559
|
+
connectedAccount: {
|
|
4560
|
+
id: connection_nano_id,
|
|
4561
|
+
uuid: connection_id,
|
|
4562
|
+
authConfigId: "",
|
|
4563
|
+
authConfigUUID: "",
|
|
4564
|
+
userId: user_id,
|
|
4565
|
+
status: "ACTIVE"
|
|
4566
|
+
}
|
|
4567
|
+
}
|
|
4568
|
+
};
|
|
5294
4569
|
}
|
|
5295
4570
|
/**
|
|
5296
|
-
*
|
|
4571
|
+
* Normalizes a V3 webhook payload to IncomingTriggerPayload format
|
|
5297
4572
|
* @private
|
|
5298
4573
|
*/
|
|
5299
|
-
|
|
4574
|
+
normalizeV3Payload(payload) {
|
|
4575
|
+
const triggerSlug = payload.metadata.trigger_slug;
|
|
4576
|
+
const toolkitSlug = triggerSlug.split("_")[0]?.toUpperCase() || "UNKNOWN";
|
|
4577
|
+
return {
|
|
4578
|
+
id: payload.metadata.trigger_id,
|
|
4579
|
+
uuid: payload.metadata.trigger_id,
|
|
4580
|
+
triggerSlug,
|
|
4581
|
+
toolkitSlug,
|
|
4582
|
+
userId: payload.metadata.user_id,
|
|
4583
|
+
payload: payload.data,
|
|
4584
|
+
originalPayload: payload.data,
|
|
4585
|
+
metadata: {
|
|
4586
|
+
id: payload.metadata.trigger_id,
|
|
4587
|
+
uuid: payload.metadata.trigger_id,
|
|
4588
|
+
toolkitSlug,
|
|
4589
|
+
triggerSlug,
|
|
4590
|
+
triggerConfig: {},
|
|
4591
|
+
connectedAccount: {
|
|
4592
|
+
id: payload.metadata.connected_account_id,
|
|
4593
|
+
uuid: payload.metadata.connected_account_id,
|
|
4594
|
+
authConfigId: payload.metadata.auth_config_id,
|
|
4595
|
+
authConfigUUID: payload.metadata.auth_config_id,
|
|
4596
|
+
userId: payload.metadata.user_id,
|
|
4597
|
+
status: "ACTIVE"
|
|
4598
|
+
}
|
|
4599
|
+
}
|
|
4600
|
+
};
|
|
4601
|
+
}
|
|
4602
|
+
/**
|
|
4603
|
+
* Verifies the HMAC-SHA256 signature of a webhook payload.
|
|
4604
|
+
* The signature format used by Composio is: `v1,base64EncodedSignature`
|
|
4605
|
+
* The signing input is: `${msgId}.${timestamp}.${payload}`
|
|
4606
|
+
* @private
|
|
4607
|
+
*/
|
|
4608
|
+
verifyWebhookSignature(webhookId, webhookTimestamp, payload, signature, secret) {
|
|
5300
4609
|
if (payload.length === 0) throw new ComposioWebhookSignatureVerificationError("No webhook payload was provided.");
|
|
5301
|
-
if (signature.length === 0) throw new ComposioWebhookSignatureVerificationError("No signature header value was provided. Please pass the value of the webhook
|
|
4610
|
+
if (signature.length === 0) throw new ComposioWebhookSignatureVerificationError("No signature header value was provided. Please pass the value of the 'webhook-signature' header.");
|
|
5302
4611
|
if (secret.length === 0) throw new ComposioWebhookSignatureVerificationError("No webhook secret was provided. You can find your webhook secret in your Composio dashboard.");
|
|
5303
|
-
|
|
5304
|
-
|
|
5305
|
-
const
|
|
5306
|
-
|
|
4612
|
+
if (webhookId.length === 0) throw new ComposioWebhookSignatureVerificationError("No webhook ID was provided. Please pass the value of the 'webhook-id' header.");
|
|
4613
|
+
if (webhookTimestamp.length === 0) throw new ComposioWebhookSignatureVerificationError("No webhook timestamp was provided. Please pass the value of the 'webhook-timestamp' header.");
|
|
4614
|
+
const signatures = signature.split(" ");
|
|
4615
|
+
const v1Signatures = [];
|
|
4616
|
+
for (const sig of signatures) {
|
|
4617
|
+
const [version$1, value] = sig.split(",");
|
|
4618
|
+
if (version$1 === "v1" && value) v1Signatures.push(value);
|
|
4619
|
+
}
|
|
4620
|
+
if (v1Signatures.length === 0) throw new ComposioWebhookSignatureVerificationError("No valid v1 signature found in the webhook-signature header. Expected format: 'v1,base64EncodedSignature'");
|
|
4621
|
+
const toSign = `${webhookId}.${webhookTimestamp}.${payload}`;
|
|
4622
|
+
const expectedSignature = node_crypto.createHmac("sha256", secret).update(toSign, "utf8").digest("base64");
|
|
4623
|
+
let isValid = false;
|
|
4624
|
+
for (const providedSignature of v1Signatures) {
|
|
4625
|
+
const signatureBuffer = Buffer.from(providedSignature);
|
|
4626
|
+
const expectedBuffer = Buffer.from(expectedSignature);
|
|
4627
|
+
if (signatureBuffer.length === expectedBuffer.length && node_crypto.timingSafeEqual(signatureBuffer, expectedBuffer)) {
|
|
4628
|
+
isValid = true;
|
|
4629
|
+
break;
|
|
4630
|
+
}
|
|
4631
|
+
}
|
|
4632
|
+
if (!isValid) throw new ComposioWebhookSignatureVerificationError("The signature provided is invalid. Please ensure you are using the correct webhook secret.");
|
|
5307
4633
|
}
|
|
5308
4634
|
/**
|
|
5309
4635
|
* Validates that the webhook timestamp is within the allowed tolerance
|
|
5310
4636
|
* @private
|
|
5311
4637
|
*/
|
|
5312
|
-
validateWebhookTimestamp(
|
|
5313
|
-
const
|
|
5314
|
-
if (
|
|
5315
|
-
|
|
5316
|
-
return;
|
|
5317
|
-
}
|
|
5318
|
-
const webhookTime = Date.parse(timestamp);
|
|
5319
|
-
if (Number.isNaN(webhookTime)) throw new ComposioWebhookPayloadError(`Invalid timestamp in webhook payload: ${timestamp}. Expected ISO 8601 format.`);
|
|
4638
|
+
validateWebhookTimestamp(webhookTimestamp, tolerance) {
|
|
4639
|
+
const timestampSeconds = parseInt(webhookTimestamp, 10);
|
|
4640
|
+
if (Number.isNaN(timestampSeconds)) throw new ComposioWebhookPayloadError(`Invalid webhook timestamp: ${webhookTimestamp}. Expected Unix timestamp in seconds.`);
|
|
4641
|
+
const webhookTimeMs = timestampSeconds * 1e3;
|
|
5320
4642
|
const currentTime = Date.now();
|
|
5321
|
-
const timeDifference = Math.abs(currentTime -
|
|
4643
|
+
const timeDifference = Math.abs(currentTime - webhookTimeMs);
|
|
5322
4644
|
if (timeDifference > tolerance * 1e3) throw new ComposioWebhookSignatureVerificationError(`The webhook timestamp is outside the allowed tolerance. The webhook was sent ${Math.round(timeDifference / 1e3)} seconds ago, but the maximum allowed age is ${tolerance} seconds.`);
|
|
5323
4645
|
}
|
|
5324
4646
|
};
|
|
@@ -5423,7 +4745,7 @@ var MCP = class {
|
|
|
5423
4745
|
client;
|
|
5424
4746
|
constructor(client) {
|
|
5425
4747
|
this.client = client;
|
|
5426
|
-
telemetry.instrument(this, "MCP");
|
|
4748
|
+
require_fileUtils.telemetry.instrument(this, "MCP");
|
|
5427
4749
|
}
|
|
5428
4750
|
/**
|
|
5429
4751
|
* Create a new MCP configuration.
|
|
@@ -5737,11 +5059,11 @@ var MCP = class {
|
|
|
5737
5059
|
//#region src/utils/sdk.ts
|
|
5738
5060
|
const userDataPath = () => {
|
|
5739
5061
|
try {
|
|
5740
|
-
const
|
|
5741
|
-
|
|
5742
|
-
return
|
|
5062
|
+
const homeDir = _platform.platform.homedir();
|
|
5063
|
+
if (!homeDir) return null;
|
|
5064
|
+
return _platform.platform.joinPath(homeDir, require_fileUtils.COMPOSIO_DIR, require_fileUtils.USER_DATA_FILE_NAME);
|
|
5743
5065
|
} catch (_error) {
|
|
5744
|
-
logger_default.debug("Environment", `Unable to get user data path`);
|
|
5066
|
+
require_fileUtils.logger_default.debug("Environment", `Unable to get user data path`);
|
|
5745
5067
|
return null;
|
|
5746
5068
|
}
|
|
5747
5069
|
};
|
|
@@ -5752,20 +5074,22 @@ const userDataPath = () => {
|
|
|
5752
5074
|
*/
|
|
5753
5075
|
const getUserDataJson = () => {
|
|
5754
5076
|
try {
|
|
5755
|
-
const
|
|
5077
|
+
const dataPath = userDataPath();
|
|
5078
|
+
if (!dataPath || !_platform.platform.supportsFileSystem) return {};
|
|
5079
|
+
const data = _platform.platform.readFileSync(dataPath, "utf8");
|
|
5756
5080
|
return JSON.parse(data);
|
|
5757
5081
|
} catch (_error) {
|
|
5758
|
-
logger_default.debug("Environment", "No user data file found");
|
|
5082
|
+
require_fileUtils.logger_default.debug("Environment", "No user data file found");
|
|
5759
5083
|
return {};
|
|
5760
5084
|
}
|
|
5761
5085
|
};
|
|
5762
5086
|
function getSDKConfig(baseUrl, apiKey) {
|
|
5763
5087
|
const { api_key: apiKeyFromUserConfig, base_url: baseURLFromUserConfig } = getUserDataJson();
|
|
5764
|
-
const baseURLParsed = baseUrl || getEnvVariable("COMPOSIO_BASE_URL") || baseURLFromUserConfig || DEFAULT_BASE_URL;
|
|
5765
|
-
const apiKeyParsed = apiKey || getEnvVariable("COMPOSIO_API_KEY") || apiKeyFromUserConfig || "";
|
|
5766
|
-
if (!apiKeyParsed) ComposioError.handleAndThrow(new ComposioNoAPIKeyError());
|
|
5767
|
-
logger_default.debug("Environment", `API Key: ${apiKeyParsed}`);
|
|
5768
|
-
logger_default.debug("Environment", `Base URL: ${baseURLParsed}`);
|
|
5088
|
+
const baseURLParsed = baseUrl || require_fileUtils.getEnvVariable("COMPOSIO_BASE_URL") || baseURLFromUserConfig || require_fileUtils.DEFAULT_BASE_URL;
|
|
5089
|
+
const apiKeyParsed = apiKey || require_fileUtils.getEnvVariable("COMPOSIO_API_KEY") || apiKeyFromUserConfig || "";
|
|
5090
|
+
if (!apiKeyParsed) require_fileUtils.ComposioError.handleAndThrow(new ComposioNoAPIKeyError());
|
|
5091
|
+
require_fileUtils.logger_default.debug("Environment", `API Key: ${apiKeyParsed}`);
|
|
5092
|
+
require_fileUtils.logger_default.debug("Environment", `Base URL: ${baseURLParsed}`);
|
|
5769
5093
|
return {
|
|
5770
5094
|
baseURL: baseURLParsed,
|
|
5771
5095
|
apiKey: apiKeyParsed
|
|
@@ -5785,7 +5109,7 @@ function getSDKConfig(baseUrl, apiKey) {
|
|
|
5785
5109
|
*/
|
|
5786
5110
|
function getToolkitVersionsFromEnv(defaultVersions) {
|
|
5787
5111
|
if (defaultVersions && typeof defaultVersions === "string") return defaultVersions;
|
|
5788
|
-
const envPrefixedVersions = getEnvsWithPrefix(`COMPOSIO_TOOLKIT_VERSION_`);
|
|
5112
|
+
const envPrefixedVersions = require_fileUtils.getEnvsWithPrefix(`COMPOSIO_TOOLKIT_VERSION_`);
|
|
5789
5113
|
const toolkitVersionsFromEnv = Object.entries(envPrefixedVersions).reduce((acc, [key, value]) => {
|
|
5790
5114
|
const toolkitName = key.replace("COMPOSIO_TOOLKIT_VERSION_", "");
|
|
5791
5115
|
acc[toolkitName.toLowerCase()] = value;
|
|
@@ -5815,7 +5139,7 @@ async function checkForLatestVersionFromNPM(currentVersion) {
|
|
|
5815
5139
|
const prerelease = semver.default.prerelease(currentVersionFromPackageJson);
|
|
5816
5140
|
if (prerelease && (String(prerelease[0]).includes("alpha") || String(prerelease[0]).includes("beta"))) return;
|
|
5817
5141
|
const latestVersion = (await (await fetch(`https://registry.npmjs.org/${packageName}/latest`)).json()).version;
|
|
5818
|
-
if (semver.default.gt(latestVersion, currentVersionFromPackageJson) && !IS_DEVELOPMENT_OR_CI) logger_default.info(`🚀 Upgrade available! Your composio-core version (${currentVersionFromPackageJson}) is behind. Latest version: ${latestVersion}.`);
|
|
5142
|
+
if (semver.default.gt(latestVersion, currentVersionFromPackageJson) && !require_fileUtils.IS_DEVELOPMENT_OR_CI) require_fileUtils.logger_default.info(`🚀 Upgrade available! Your composio-core version (${currentVersionFromPackageJson}) is behind. Latest version: ${latestVersion}.`);
|
|
5819
5143
|
} catch (_error) {}
|
|
5820
5144
|
}
|
|
5821
5145
|
|
|
@@ -6141,9 +5465,9 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
|
|
|
6141
5465
|
async handleAssistantMessage(userId, run, options, modifiers) {
|
|
6142
5466
|
const tool_calls = run.required_action?.submit_tool_outputs?.tool_calls || [];
|
|
6143
5467
|
return await Promise.all(tool_calls.map(async (tool_call) => {
|
|
6144
|
-
logger_default.debug(`Executing tool call: ${tool_call.id}`);
|
|
5468
|
+
require_fileUtils.logger_default.debug(`Executing tool call: ${tool_call.id}`);
|
|
6145
5469
|
const tool_response = await this.executeToolCall(userId, tool_call, options, modifiers);
|
|
6146
|
-
logger_default.debug(`Tool call ${tool_call.id} executed with response: ${tool_response}`);
|
|
5470
|
+
require_fileUtils.logger_default.debug(`Tool call ${tool_call.id} executed with response: ${tool_response}`);
|
|
6147
5471
|
return {
|
|
6148
5472
|
tool_call_id: tool_call.id,
|
|
6149
5473
|
output: JSON.stringify(tool_response)
|
|
@@ -6302,42 +5626,7 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
|
|
|
6302
5626
|
|
|
6303
5627
|
//#endregion
|
|
6304
5628
|
//#region package.json
|
|
6305
|
-
var version = "0.
|
|
6306
|
-
|
|
6307
|
-
//#endregion
|
|
6308
|
-
//#region src/models/Files.ts
|
|
6309
|
-
var Files = class {
|
|
6310
|
-
constructor(client) {
|
|
6311
|
-
this.client = client;
|
|
6312
|
-
telemetry.instrument(this, "Files");
|
|
6313
|
-
}
|
|
6314
|
-
/**
|
|
6315
|
-
* Upload a file to S3 and return the file data.
|
|
6316
|
-
* @param filePath - The path to the file to upload or a URL of the file to upload.
|
|
6317
|
-
* @param toolSlug - The slug of the tool that is uploading the file.
|
|
6318
|
-
* @param toolkitSlug - The slug of the toolkit that is uploading the file.
|
|
6319
|
-
* @returns The file data.
|
|
6320
|
-
*/
|
|
6321
|
-
async upload({ file, toolSlug, toolkitSlug }) {
|
|
6322
|
-
return await getFileDataAfterUploadingToS3(file, {
|
|
6323
|
-
toolSlug,
|
|
6324
|
-
toolkitSlug,
|
|
6325
|
-
client: this.client
|
|
6326
|
-
});
|
|
6327
|
-
}
|
|
6328
|
-
/**
|
|
6329
|
-
* Download a file from S3 and return the file data.
|
|
6330
|
-
* @param s3key - The S3 key of the file to download.
|
|
6331
|
-
* @returns The file data.
|
|
6332
|
-
*/
|
|
6333
|
-
async download({ toolSlug, s3Url, mimeType }) {
|
|
6334
|
-
return await downloadFileFromS3({
|
|
6335
|
-
toolSlug,
|
|
6336
|
-
s3Url,
|
|
6337
|
-
mimeType
|
|
6338
|
-
});
|
|
6339
|
-
}
|
|
6340
|
-
};
|
|
5629
|
+
var version = "0.5.0";
|
|
6341
5630
|
|
|
6342
5631
|
//#endregion
|
|
6343
5632
|
//#region src/utils/session.ts
|
|
@@ -6555,7 +5844,7 @@ var ToolRouter = class {
|
|
|
6555
5844
|
constructor(client, config) {
|
|
6556
5845
|
this.client = client;
|
|
6557
5846
|
this.config = config;
|
|
6558
|
-
telemetry.instrument(this, "ToolRouter");
|
|
5847
|
+
require_fileUtils.telemetry.instrument(this, "ToolRouter");
|
|
6559
5848
|
}
|
|
6560
5849
|
/**
|
|
6561
5850
|
* Creates a function that authorizes a toolkit for a user.
|
|
@@ -6844,7 +6133,7 @@ var Composio = class Composio {
|
|
|
6844
6133
|
*/
|
|
6845
6134
|
constructor(config) {
|
|
6846
6135
|
const { baseURL: baseURLParsed, apiKey: apiKeyParsed } = getSDKConfig(config?.baseURL, config?.apiKey);
|
|
6847
|
-
if (IS_DEVELOPMENT_OR_CI) logger_default.debug(`Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`);
|
|
6136
|
+
if (require_fileUtils.IS_DEVELOPMENT_OR_CI) require_fileUtils.logger_default.debug(`Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`);
|
|
6848
6137
|
/**
|
|
6849
6138
|
* Set the default provider, if not provided by the user.
|
|
6850
6139
|
*/
|
|
@@ -6866,18 +6155,18 @@ var Composio = class Composio {
|
|
|
6866
6155
|
* Initialize the Composio SDK client.
|
|
6867
6156
|
* The client is used to make API calls to the Composio API.
|
|
6868
6157
|
*/
|
|
6869
|
-
this.client = new
|
|
6158
|
+
this.client = new _composio_client.default({
|
|
6870
6159
|
apiKey: apiKeyParsed,
|
|
6871
6160
|
baseURL: baseURLParsed,
|
|
6872
6161
|
defaultHeaders: getDefaultHeaders(this.config.defaultHeaders, this.provider),
|
|
6873
|
-
logLevel: COMPOSIO_LOG_LEVEL
|
|
6162
|
+
logLevel: require_fileUtils.COMPOSIO_LOG_LEVEL
|
|
6874
6163
|
});
|
|
6875
6164
|
this.tools = new Tools(this.client, this.config);
|
|
6876
6165
|
this.mcp = new MCP(this.client);
|
|
6877
6166
|
this.toolkits = new Toolkits(this.client);
|
|
6878
6167
|
this.triggers = new Triggers(this.client, this.config);
|
|
6879
6168
|
this.authConfigs = new AuthConfigs(this.client);
|
|
6880
|
-
this.files = new Files(this.client);
|
|
6169
|
+
this.files = new _files.Files(this.client);
|
|
6881
6170
|
this.connectedAccounts = new ConnectedAccounts(this.client);
|
|
6882
6171
|
this.toolRouter = new ToolRouter(this.client, this.config);
|
|
6883
6172
|
/**
|
|
@@ -6889,7 +6178,7 @@ var Composio = class Composio {
|
|
|
6889
6178
|
/**
|
|
6890
6179
|
* Initialize the client telemetry.
|
|
6891
6180
|
*/
|
|
6892
|
-
if (this.config.allowTracking) telemetry.setup({
|
|
6181
|
+
if (this.config.allowTracking) require_fileUtils.telemetry.setup({
|
|
6893
6182
|
apiKey: apiKeyParsed ?? "",
|
|
6894
6183
|
baseUrl: baseURLParsed ?? "",
|
|
6895
6184
|
isAgentic: this.provider?._isAgentic || false,
|
|
@@ -6898,8 +6187,8 @@ var Composio = class Composio {
|
|
|
6898
6187
|
provider: this.provider?.name ?? "openai",
|
|
6899
6188
|
host: this.config.host
|
|
6900
6189
|
});
|
|
6901
|
-
telemetry.instrument(this, "Composio");
|
|
6902
|
-
telemetry.instrument(this.provider, this.provider.name ?? this.provider.constructor.name ?? "unknown");
|
|
6190
|
+
require_fileUtils.telemetry.instrument(this, "Composio");
|
|
6191
|
+
require_fileUtils.telemetry.instrument(this.provider, this.provider.name ?? this.provider.constructor.name ?? "unknown");
|
|
6903
6192
|
if (!this.config.disableVersionCheck) checkForLatestVersionFromNPM(version);
|
|
6904
6193
|
}
|
|
6905
6194
|
/**
|
|
@@ -7032,7 +6321,7 @@ function jsonSchemaToZodSchema(jsonSchema, { strict } = { strict: false }) {
|
|
|
7032
6321
|
try {
|
|
7033
6322
|
let schema = jsonSchema;
|
|
7034
6323
|
if (strict && schema) schema = removeNonRequiredProperties(schema);
|
|
7035
|
-
return (0,
|
|
6324
|
+
return (0, _composio_json_schema_to_zod.jsonSchemaToZod)(schema);
|
|
7036
6325
|
} catch (error) {
|
|
7037
6326
|
throw new JsonSchemaToZodError("Failed to convert JSON Schema to Zod Schema", { cause: error });
|
|
7038
6327
|
}
|
|
@@ -7398,7 +6687,7 @@ exports.ComposioAuthConfigNotFoundError = ComposioAuthConfigNotFoundError;
|
|
|
7398
6687
|
exports.ComposioConnectedAccountNotFoundError = ComposioConnectedAccountNotFoundError;
|
|
7399
6688
|
exports.ComposioCustomCreateResponseSchema = ComposioCustomCreateResponseSchema;
|
|
7400
6689
|
exports.ComposioCustomToolsNotInitializedError = ComposioCustomToolsNotInitializedError;
|
|
7401
|
-
exports.ComposioError = ComposioError;
|
|
6690
|
+
exports.ComposioError = require_fileUtils.ComposioError;
|
|
7402
6691
|
exports.ComposioFailedToCreateConnectedAccountLink = ComposioFailedToCreateConnectedAccountLink;
|
|
7403
6692
|
exports.ComposioFailedToCreatePusherClientError = ComposioFailedToCreatePusherClientError;
|
|
7404
6693
|
exports.ComposioFailedToGetSDKRealtimeCredentialsError = ComposioFailedToGetSDKRealtimeCredentialsError;
|
|
@@ -7551,14 +6840,19 @@ exports.TriggersTypeListResponseSchema = TriggersTypeListResponseSchema;
|
|
|
7551
6840
|
exports.ValidationError = ValidationError;
|
|
7552
6841
|
exports.ValidationErrorCodes = ValidationErrorCodes;
|
|
7553
6842
|
exports.VerifyWebhookParamsSchema = VerifyWebhookParamsSchema;
|
|
6843
|
+
exports.WebhookPayloadSchema = WebhookPayloadSchema;
|
|
6844
|
+
exports.WebhookPayloadV1Schema = WebhookPayloadV1Schema;
|
|
6845
|
+
exports.WebhookPayloadV2Schema = WebhookPayloadV2Schema;
|
|
6846
|
+
exports.WebhookPayloadV3Schema = WebhookPayloadV3Schema;
|
|
6847
|
+
exports.WebhookVersions = WebhookVersions;
|
|
7554
6848
|
Object.defineProperty(exports, 'constants', {
|
|
7555
6849
|
enumerable: true,
|
|
7556
6850
|
get: function () {
|
|
7557
|
-
return constants_exports;
|
|
6851
|
+
return require_fileUtils.constants_exports;
|
|
7558
6852
|
}
|
|
7559
6853
|
});
|
|
7560
6854
|
exports.createConnectionRequest = createConnectionRequest;
|
|
7561
6855
|
exports.handleToolExecutionError = handleToolExecutionError;
|
|
7562
6856
|
exports.jsonSchemaToZodSchema = jsonSchemaToZodSchema;
|
|
7563
|
-
exports.logger = logger_default;
|
|
6857
|
+
exports.logger = require_fileUtils.logger_default;
|
|
7564
6858
|
exports.removeNonRequiredProperties = removeNonRequiredProperties;
|