'use strict';

var axios = require('axios');
var uuid = require('uuid');
var z = require('zod');
var clientAxios = require('@hey-api/client-axios');
var zodToJsonSchema = require('zod-to-json-schema');
var crypto = require('crypto');
var pathModule = require('path');
var tools = require('@langchain/core/tools');
var ai = require('ai');

const COMPOSIO_VERSION = `0.5.39`;

const getUUID = () => {
    return uuid.v4();
};

function jsonSchemaPropertiesToTSTypes(value) {
    if (!value.type) {
        return z.object({});
    }
    let zodType;
    switch (value.type) {
        case "string":
            zodType = z
                .string()
                .describe((value.description || "") +
                (value.examples ? `\nExamples: ${value.examples.join(", ")}` : ""));
            break;
        case "number":
            zodType = z
                .number()
                .describe((value.description || "") +
                (value.examples ? `\nExamples: ${value.examples.join(", ")}` : ""));
            break;
        case "integer":
            zodType = z
                .number()
                .int()
                .describe((value.description || "") +
                (value.examples ? `\nExamples: ${value.examples.join(", ")}` : ""));
            break;
        case "boolean":
            zodType = z
                .boolean()
                .describe((value.description || "") +
                (value.examples ? `\nExamples: ${value.examples.join(", ")}` : ""));
            break;
        case "array":
            zodType = z
                .array(jsonSchemaPropertiesToTSTypes(value.items))
                .describe((value.description || "") +
                (value.examples ? `\nExamples: ${value.examples.join(", ")}` : ""));
            break;
        case "object":
            zodType = jsonSchemaToModel(value).describe((value.description || "") +
                (value.examples ? `\nExamples: ${value.examples.join(", ")}` : ""));
            break;
        case "null":
            zodType = z.null().describe(value.description || "");
            break;
        default:
            throw new Error(`Unsupported JSON schema type: ${value.type}`);
    }
    return zodType;
}
function jsonSchemaToModel(jsonSchema) {
    const properties = jsonSchema.properties;
    const requiredFields = jsonSchema.required || [];
    if (!properties) {
        return z.object({});
    }
    const zodSchema = {};
    for (const [key, _] of Object.entries(properties)) {
        const value = _;
        let zodType;
        if (value.anyOf) {
            const anyOfTypes = value.anyOf.map((schema) => jsonSchemaPropertiesToTSTypes(schema));
            zodType = z
                .union(anyOfTypes)
                .describe((value.description || "") +
                (value.examples
                    ? `\nExamples: ${value.examples.join(", ")}`
                    : ""));
        }
        else if (value.allOf) {
            const allOfTypes = value.allOf.map((schema) => jsonSchemaPropertiesToTSTypes(schema));
            zodType = z
                .intersection(allOfTypes[0], allOfTypes
                .slice(1)
                .reduce((acc, schema) => acc.and(schema), allOfTypes[0]))
                .describe((value.description || "") +
                (value.examples
                    ? `\nExamples: ${value.examples.join(", ")}`
                    : ""));
        }
        else {
            if (!value.type) {
                value.type = "string";
            }
            zodType = jsonSchemaPropertiesToTSTypes(value);
        }
        if (value.description) {
            zodType = zodType.describe(value.description);
        }
        if (requiredFields.includes(key)) {
            zodSchema[key] = zodType;
        }
        else {
            zodSchema[key] = zodType.optional();
        }
    }
    return z.object(zodSchema);
}
const getEnvVariable = (name, defaultValue = undefined) => {
    try {
        return process.env[name] || defaultValue;
    }
    catch (_e) {
        return defaultValue;
    }
};

// Define log levels with corresponding priorities
const LOG_LEVELS = {
    silent: -1, // No logs
    error: 0, // Highest priority - critical errors
    warn: 1, // Warning messages
    info: 2, // General information
    debug: 3, // Debug information
};
/**
 * Get the current log level from environment variables.
 * Defaults to 'info' if not set or invalid.
 * @returns {keyof typeof LOG_LEVELS} The current log level
 */
const getLogLevel = () => {
    var _a;
    const envLevel = (_a = getEnvVariable("COMPOSIO_LOGGING_LEVEL", "info")) === null || _a === void 0 ? void 0 : _a.toLowerCase();
    return envLevel && envLevel in LOG_LEVELS
        ? envLevel
        : "info";
};
const addTimestampToMessage = (message) => {
    const timestamp = new Date().toISOString();
    return `${timestamp} - ${message}`;
};
const formatErrorMessage = (args) => {
    return args
        .map((arg) => (typeof arg === "object" ? JSON.stringify(arg) : arg))
        .join(" ");
};
const getLogger = () => {
    const logger = console;
    const loggingLevel = getLogLevel();
    const logLevelValue = LOG_LEVELS[loggingLevel];
    const noop = () => { };
    return {
        error: logLevelValue >= LOG_LEVELS.error
            ? (...args) => logger.error(addTimestampToMessage(formatErrorMessage(args)))
            : noop,
        warn: logLevelValue >= LOG_LEVELS.warn
            ? (...args) => logger.warn(addTimestampToMessage(formatErrorMessage(args)))
            : noop,
        info: logLevelValue >= LOG_LEVELS.info
            ? (...args) => logger.info(addTimestampToMessage(formatErrorMessage(args)))
            : noop,
        debug: logLevelValue >= LOG_LEVELS.debug
            ? (...args) => logger.debug(addTimestampToMessage(formatErrorMessage(args)))
            : noop,
    };
};
var logger = getLogger();

const ZAuthMode = z.z.enum([
    "OAUTH2",
    "OAUTH1",
    "OAUTH1A",
    "API_KEY",
    "BASIC",
    "BEARER_TOKEN",
    "GOOGLE_SERVICE_ACCOUNT",
    "NO_AUTH",
    "BASIC_WITH_JWT",
]);
const ZCreateIntegrationParams = z.z.object({
    name: z.z.string(),
    authScheme: ZAuthMode.optional(),
    appUniqueKey: z.z.string().optional(),
    appId: z.z.string().optional(),
    forceNewIntegration: z.z.boolean().optional(),
    authConfig: z.z
        .union([
        z.z.record(z.z.unknown()),
        z.z.object({
            client_id: z.z.string(),
            client_secret: z.z.string(),
            api_key: z.z.string(),
            consumer_key: z.z.string(),
            consumer_secret: z.z.string(),
            base_url: z.z.string(),
        }),
    ])
        .optional(),
    useComposioAuth: z.z.boolean().optional(),
});
const ZSingleIntegrationParams = z.z.object({
    integrationId: z.z.string(),
});
const ZListIntegrationsParams = z.z.object({
    page: z.z.number().optional(),
    pageSize: z.z.number().optional(),
    appName: z.z.string().optional(),
    appUniqueKey: z.z.string().optional(),
    showDisabled: z.z.boolean().optional(),
});

const ZExecuteActionParams$1 = z.z.object({
    actionName: z.z.string(),
    params: z.z.record(z.z.any()).optional(),
    text: z.z.string().optional(),
    connectedAccountId: z.z.string().optional(),
});
const ZInitiateConnectionParams = z.z.object({
    appName: z.z.string().optional(),
    authConfig: z.z.record(z.z.any()).optional(),
    integrationId: z.z.string().optional(),
    authMode: ZAuthMode.optional(),
    connectionParams: z.z.record(z.z.any()).optional(),
    config: z.z
        .object({
        labels: z.z.array(z.z.string()).optional(),
        redirectUrl: z.z.string().optional(),
    })
        .optional(),
    redirectUri: z.z.string().optional(),
    labels: z.z.array(z.z.string()).optional(),
});
const ZConnectionParams = z.z.object({
    connectedAccountId: z.z.string().optional(),
    app: z.z.string().optional(),
});
const ZTriggerSubscribeParam = z.z.object({
    app: z.z.string().optional(),
    appName: z.z.string().optional(),
    triggerName: z.z.string(),
    config: z.z.record(z.z.any()),
});

// Helper function to stringify objects if needed
const serializeValue = (obj) => {
    return typeof obj === "object" ? JSON.stringify(obj) : obj;
};

// Constants
const COMPOSIO_DIR = ".composio";
const USER_DATA_FILE_NAME = "user_data.json";
const TEMP_FILES_DIRECTORY_NAME = "files";
const DEFAULT_BASE_URL = "https://backend.composio.dev";
const TELEMETRY_URL = "https://app.composio.dev";
const IS_DEVELOPMENT_OR_CI = process.env.DEVELOPMENT || process.env.CI || false;

/**
 * Sends a reporting payload to the telemetry server using a child process.
 * This function is intended for use in Node.js environments.
 *
 * @param {any} reportingPayload - The payload to be sent to the telemetry server.
 */
function sendProcessReq(info) {
    if (IS_DEVELOPMENT_OR_CI) {
        logger.debug(`Hitting ${info.url}[${info.method}] with ${serializeValue(info.data)}`);
        return true;
    }
    try {
        const url = new URL(info.url);
        const protocol = url.protocol === "https:" ? "https" : "http";
        const port = url.port || (url.protocol === "https:" ? 443 : 80);
        const args = [
            "-e",
            `
      const http = require('${protocol}');
      const options = {
        hostname: '${url.hostname}',
        path: '${url.pathname}${url.search}',
        port: ${port},
        method: '${info.method}',
        headers: ${JSON.stringify(info.headers)}
      };

      const req = http.request(options, (res) => {
        res.on('data', () => {});
        res.on('end', () => {
          process.exit(0);
        });
      });

      req.on('error', () => {
        process.exit(0);
      });

      req.write(JSON.stringify(${JSON.stringify(info.data)}));
      req.end();
      `,
        ];
        // Use spawn with detached option instead of spawnSync to make it non-blocking
        const { spawn } = require("child_process");
        spawn("node", args, {
            stdio: "ignore",
            detached: true,
            shell: false,
        }).unref();
        return true;
    }
    catch (error) {
        logger.debug("Error sending error to telemetry", error);
        // DO NOTHING
    }
}
/**
 * Sends a reporting payload to the telemetry server using XMLHttpRequest.
 * This function is intended for use in browser environments.
 *
 * @param {any} reportingPayload - The payload to be sent to the telemetry server.
 */
function sendBrowserReq(info) {
    if (IS_DEVELOPMENT_OR_CI) {
        logger.debug(`Hitting ${info.url}[${info.method}] with ${serializeValue(info.data)}`);
        return true;
    }
    try {
        // Create a new XMLHttpRequest object
        const xhr = new XMLHttpRequest();
        // Open a new POST request to the telemetry server
        xhr.open(info.method, info.url, true);
        // Set the request header to indicate JSON content
        xhr.setRequestHeader("Content-Type", "application/json");
        Object.entries(info.headers || {}).forEach(([key, value]) => {
            xhr.setRequestHeader(key, value);
        });
        // Define the onload event handler
        xhr.onload = function () {
            // Log the response if the request was successful
            if (xhr.status === 200) {
                logger.debug(xhr.response);
            }
        };
        // Send the reporting payload as a JSON string
        xhr.send(JSON.stringify(info.data));
    }
    catch (error) {
        logger.debug("Error sending error to telemetry", error);
        // DO NOTHING
    }
}

/*
    ComposioContext class provides a global context for storing SDK configuration.
    This singleton class maintains essential SDK settings like API key and base URL.
    It is used to store the API key and base URL in a global context so that it can be accessed by other modules without having to pass the configuration around.

    Warning: Can cause problems if there are multiple instances of the SDK running in the same process.
*/
class ComposioSDKContext {
}
ComposioSDKContext.source = "javascript";

async function logError(payload) {
    const isTelemetryDisabled = getEnvVariable("TELEMETRY_DISABLED", "false") === "true";
    if (isTelemetryDisabled) {
        return;
    }
    try {
        const isBrowser = typeof window !== "undefined";
        const reportingPayload = generateReportingPayload(payload);
        const reqPayload = {
            data: reportingPayload,
            url: `${TELEMETRY_URL}/api/sdk_metrics/error`,
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
        };
        if (isBrowser) {
            await sendBrowserReq(reqPayload);
        }
        else {
            await sendProcessReq(reqPayload);
        }
    }
    catch (error) {
        logger.debug("Error sending error to telemetry", error);
        // DO NOTHING
    }
}
function generateReportingPayload(payload) {
    const { apiKey, baseURL, composioVersion, frameworkRuntime, source } = ComposioSDKContext;
    const { error_id, error_code, description, message, possible_fix, original_error, current_stack, } = payload;
    return {
        error_id,
        error_code,
        description,
        error_message: message,
        possible_fix,
        original_error,
        current_stack,
        sdk_meta: {
            platform: process.platform,
            version: composioVersion,
            baseURL,
            apiKey,
            frameworkRuntime,
            source,
        },
    };
}

/**
 * Custom error class for Composio that provides rich error details, tracking, and improved debugging
 */
class ComposioError extends Error {
    constructor(errCode, message, description, possibleFix, metadata, originalError) {
        var _a;
        // Ensure message is never empty
        super(message || "An unknown error occurred");
        // additional metadata about the error
        this.metadata = {};
        // Ensure proper prototype chain for instanceof checks
        Object.setPrototypeOf(this, new.target.prototype);
        this.name = "ComposioError";
        this.errCode = errCode;
        this.description = description;
        this.possibleFix = possibleFix;
        this.timestamp = new Date().toISOString();
        this.metadata = metadata;
        this.errorId = getUUID();
        let originalErrorString = "";
        // Only print original error if COMPOSIO_LOGGING_LEVEL is debug
        if (originalError) {
            try {
                originalErrorString =
                    typeof originalError === "object"
                        ? JSON.parse(JSON.stringify(originalError))
                        : originalError;
            }
            catch (_e) {
                originalErrorString = String(originalError);
            }
            if (getLogLevel() === "debug") {
                this._originalError = originalErrorString;
            }
        }
        // Only in case of info or debug, we will log the error
        if (LOG_LEVELS[getLogLevel()] >= 2) {
            logger.info(`🚀 [Info] Give Feedback / Get Help: https://dub.composio.dev/discord `);
            logger.info(`🐛 [Info] Create a new issue: https://github.com/ComposioHQ/composio/issues `);
            if (getLogLevel() !== "debug") {
                logger.info(`⛔ [Info] If you need to debug this error, set env variable COMPOSIO_LOGGING_LEVEL=debug`);
            }
        }
        logError({
            error_id: this.errorId,
            error_code: this.errCode,
            original_error: originalErrorString,
            description: this.description || "",
            metadata: this.metadata || {},
            message: this.message,
            possible_fix: this.possibleFix || "",
            current_stack: ((_a = this.stack) === null || _a === void 0 ? void 0 : _a.split("\n")) || [],
        });
        // Capture stack trace, excluding constructor call
        Error.captureStackTrace(this, this.constructor);
    }
    get originalError() {
        return this._originalError;
    }
    /**
     * Returns a complete object representation for logging/serialization
     * Includes all error details and metadata
     */
    toJSON() {
        var _a, _b, _c;
        const errorObj = {
            name: this.name,
            errorId: this.errorId,
            code: this.errCode,
            message: this.message,
            description: this.description,
            possibleFix: this.possibleFix,
            timestamp: this.timestamp,
            stack: (_a = this.stack) === null || _a === void 0 ? void 0 : _a.split("\n"),
            originalStack: (_c = (_b = this.originalError) === null || _b === void 0 ? void 0 : _b.stack) === null || _c === void 0 ? void 0 : _c.split("\n"),
        };
        // Remove undefined/null properties
        return Object.entries(errorObj).reduce((acc, [key, value]) => {
            if (value !== undefined && value !== null) {
                acc[key] = value;
            }
            return acc;
        }, {});
    }
}

const COMPOSIO_SDK_ERROR_CODES = {
    BACKEND: {
        NOT_FOUND: "BACKEND::NOT_FOUND",
        RATE_LIMIT: "BACKEND::RATE_LIMIT",
        BAD_REQUEST: "BACKEND::BAD_REQUEST",
        UNAUTHORIZED: "BACKEND::UNAUTHORIZED",
        SERVER_ERROR: "BACKEND::SERVER_ERROR",
        SERVER_UNAVAILABLE: "BACKEND::SERVER_UNAVAILABLE",
        SERVER_UNREACHABLE: "BACKEND::SERVER_UNREACHABLE",
        UNKNOWN: "BACKEND::UNKNOWN",
    },
    COMMON: {
        API_KEY_UNAVAILABLE: "COMMON::API_KEY_INVALID",
        BASE_URL_NOT_REACHABLE: "COMMON::BASE_URL_NOT_REACHABLE",
        UNKNOWN: "COMMON::ERROR_CODE_NOT_DEFINED",
        SERVER_UNAVAILABLE: "COMMON::SERVER_UNAVAILABLE",
        REQUEST_TIMEOUT: "COMMON::REQUEST_TIMEOUT",
        REQUEST_ABORTED: "COMMON::REQUEST_ABORTED",
        INVALID_PARAMS_PASSED: "COMMON::INVALID_PARAMS_PASSED",
    },
    SDK: {
        NO_CONNECTED_ACCOUNT_FOUND: "SDK::NO_CONNECTED_ACCOUNT_FOUND",
        FAILED_TO_INITIATE_CONNECTION: "SDK::FAILED_TO_INITIATE_CONNECTION",
        INVALID_PARAMETER: "SDK::INVALID_PARAMETER",
    },
};
const BASE_ERROR_CODE_INFO = {
    [COMPOSIO_SDK_ERROR_CODES.BACKEND.NOT_FOUND]: {
        message: "🔍 API not found",
        description: "The requested resource is missing",
        possibleFix: "Ensure the resource id or resource identifier is correct and valid as backend returned 404",
    },
    [COMPOSIO_SDK_ERROR_CODES.BACKEND.BAD_REQUEST]: {
        message: "🚫 Bad Request. The request was malformed or incorrect",
        description: null,
        possibleFix: "Check your parameters and request format, as the backend returned a 400 error.",
    },
    [COMPOSIO_SDK_ERROR_CODES.BACKEND.UNAUTHORIZED]: {
        message: "🔑 Access Denied",
        description: "You do not have the necessary credentials.",
        possibleFix: "Ensure your API key is correct and has the required permissions.",
    },
    [COMPOSIO_SDK_ERROR_CODES.COMMON.REQUEST_TIMEOUT]: {
        message: "🕒 Request Timeout",
        description: "The request timed out while waiting for a response.",
        possibleFix: "Please try again later. If the issue persists, contact support or check your network connection.",
    },
    [COMPOSIO_SDK_ERROR_CODES.BACKEND.SERVER_ERROR]: {
        message: "💥 Oops! Internal server error",
        description: "Your request could not be processed due to an internal server error.",
        possibleFix: "Please try again later. If the issue persists, contact support.",
    },
    [COMPOSIO_SDK_ERROR_CODES.BACKEND.RATE_LIMIT]: {
        message: "⏱️ API Rate Limit Exceeded",
        description: "You have exceeded the rate limit for requests.",
        possibleFix: "Please wait a bit before trying your request again.",
    },
    [COMPOSIO_SDK_ERROR_CODES.COMMON.API_KEY_UNAVAILABLE]: {
        message: "🔑 API Key Missing or Invalid",
        description: "The API key provided is missing or incorrect.",
        possibleFix: "Ensure that your API key is passed to client or set in COMPOSIO_API_KEY environment variable.",
    },
    [COMPOSIO_SDK_ERROR_CODES.BACKEND.SERVER_UNAVAILABLE]: {
        message: "🚫 Server Unavailable",
        description: "The server is currently unable to handle the request.",
        possibleFix: "Please try again later. If the issue persists, contact support.",
    },
    [COMPOSIO_SDK_ERROR_CODES.COMMON.BASE_URL_NOT_REACHABLE]: {
        message: "🔗 Base URL is not valid",
        description: "The base URL provided is not valid.",
        possibleFix: "Ensure that the base URL is correct and accessible.",
    },
    [COMPOSIO_SDK_ERROR_CODES.COMMON.INVALID_PARAMS_PASSED]: {
        message: "🕒 Invalid parameters passed",
        description: "The parameters passed are invalid",
        possibleFix: "Please check the error message for more details",
    },
    UNKNOWN: {
        message: null,
        description: null,
        possibleFix: "Contact our support team with the error details for further assistance.",
    },
    [COMPOSIO_SDK_ERROR_CODES.BACKEND.UNKNOWN]: {
        message: null,
        description: null,
        possibleFix: "Contact our support team with the error details for further assistance.",
    },
};
const API_TO_SDK_ERROR_CODE = {
    400: COMPOSIO_SDK_ERROR_CODES.BACKEND.BAD_REQUEST,
    401: COMPOSIO_SDK_ERROR_CODES.BACKEND.UNAUTHORIZED,
    404: COMPOSIO_SDK_ERROR_CODES.BACKEND.NOT_FOUND,
    408: COMPOSIO_SDK_ERROR_CODES.COMMON.REQUEST_TIMEOUT,
    429: COMPOSIO_SDK_ERROR_CODES.BACKEND.RATE_LIMIT,
    500: COMPOSIO_SDK_ERROR_CODES.BACKEND.SERVER_ERROR,
    502: COMPOSIO_SDK_ERROR_CODES.BACKEND.SERVER_UNAVAILABLE,
};

const getAPIErrorDetails = (axiosError) => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
    const statusCode = (_a = axiosError.response) === null || _a === void 0 ? void 0 : _a.status;
    const errorCode = statusCode
        ? API_TO_SDK_ERROR_CODE[statusCode]
        : COMPOSIO_SDK_ERROR_CODES.BACKEND.UNKNOWN;
    const predefinedError = BASE_ERROR_CODE_INFO[errorCode];
    const defaultErrorDetails = {
        message: axiosError.message,
        description: ((_c = (_b = axiosError === null || axiosError === void 0 ? void 0 : axiosError.response) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.message) || axiosError.message,
        possibleFix: "Please check the parameters you are passing to the API",
    };
    const metadata = generateMetadataFromAxiosError(axiosError);
    const errorNameFromBE = (_e = (_d = axiosError === null || axiosError === void 0 ? void 0 : axiosError.response) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.name;
    const errorTypeFromBE = (_g = (_f = axiosError === null || axiosError === void 0 ? void 0 : axiosError.response) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.type;
    const errorMessage = (_j = (_h = axiosError === null || axiosError === void 0 ? void 0 : axiosError.response) === null || _h === void 0 ? void 0 : _h.data) === null || _j === void 0 ? void 0 : _j.message;
    let genericMessage = "";
    const hasNotReceivedResponseFromBE = errorCode === COMPOSIO_SDK_ERROR_CODES.BACKEND.UNAUTHORIZED ||
        errorCode === COMPOSIO_SDK_ERROR_CODES.BACKEND.RATE_LIMIT ||
        errorCode === COMPOSIO_SDK_ERROR_CODES.BACKEND.SERVER_UNAVAILABLE ||
        errorCode === COMPOSIO_SDK_ERROR_CODES.BACKEND.SERVER_UNREACHABLE;
    if (hasNotReceivedResponseFromBE) {
        genericMessage = predefinedError.message;
    }
    else if (((_k = axiosError.config) === null || _k === void 0 ? void 0 : _k.baseURL) && ((_l = axiosError.config) === null || _l === void 0 ? void 0 : _l.url)) {
        genericMessage = `${errorNameFromBE || predefinedError.message} ${errorTypeFromBE ? `- ${errorTypeFromBE}` : ""} on ${((_m = axiosError.config) === null || _m === void 0 ? void 0 : _m.baseURL) + ((_o = axiosError.config) === null || _o === void 0 ? void 0 : _o.url)}`;
    }
    switch (errorCode) {
        case COMPOSIO_SDK_ERROR_CODES.BACKEND.BAD_REQUEST:
            const validationErrors = (_q = (_p = axiosError.response) === null || _p === void 0 ? void 0 : _p.data) === null || _q === void 0 ? void 0 : _q.details;
            const formattedErrors = Array.isArray(validationErrors)
                ? validationErrors.map((err) => JSON.stringify(err)).join(", ")
                : JSON.stringify(validationErrors);
            return {
                message: genericMessage,
                description: `Validation Errors: ${formattedErrors}`,
                possibleFix: "Please check the request parameters and ensure they are correct.",
                metadata,
            };
        case COMPOSIO_SDK_ERROR_CODES.BACKEND.NOT_FOUND:
        case COMPOSIO_SDK_ERROR_CODES.BACKEND.UNAUTHORIZED:
        case COMPOSIO_SDK_ERROR_CODES.BACKEND.SERVER_ERROR:
        case COMPOSIO_SDK_ERROR_CODES.BACKEND.SERVER_UNAVAILABLE:
        case COMPOSIO_SDK_ERROR_CODES.BACKEND.RATE_LIMIT:
        case COMPOSIO_SDK_ERROR_CODES.BACKEND.UNKNOWN:
            return {
                message: genericMessage,
                description: errorMessage || predefinedError.description,
                possibleFix: predefinedError.possibleFix ||
                    defaultErrorDetails.possibleFix,
                metadata,
            };
        default:
            const message = genericMessage || axiosError.message;
            const description = errorMessage || predefinedError.description;
            const possibleFix = predefinedError.possibleFix ||
                defaultErrorDetails.possibleFix ||
                "";
            return {
                message,
                description,
                possibleFix,
                metadata,
            };
    }
};
const generateMetadataFromAxiosError = (axiosError) => {
    var _a, _b, _c, _d, _e, _f, _g;
    const { requestId, ...restMetadata } = axiosError.metadata || {};
    return {
        fullUrl: ((_b = (_a = axiosError.config) === null || _a === void 0 ? void 0 : _a.baseURL) !== null && _b !== void 0 ? _b : "") + ((_d = (_c = axiosError.config) === null || _c === void 0 ? void 0 : _c.url) !== null && _d !== void 0 ? _d : ""),
        method: ((_f = (_e = axiosError.config) === null || _e === void 0 ? void 0 : _e.method) !== null && _f !== void 0 ? _f : "").toUpperCase(),
        statusCode: (_g = axiosError.response) === null || _g === void 0 ? void 0 : _g.status,
        requestId: requestId ? `${requestId}` : undefined,
        metadata: restMetadata,
    };
};

class CEG {
    static handleAllError(error, shouldThrow = false) {
        if (error instanceof ComposioError) {
            if (shouldThrow) {
                throw error;
            }
            return error;
        }
        if (!(error instanceof Error)) {
            const error = new Error("Passed error is not an instance of Error");
            if (shouldThrow) {
                throw error;
            }
            return error;
        }
        if (error instanceof z.ZodError) {
            const zodError = this.returnZodError(error);
            if (shouldThrow) {
                throw zodError;
            }
            return zodError;
        }
        const isAxiosError = error.isAxiosError;
        if (!isAxiosError) {
            const customError = this.getCustomError(COMPOSIO_SDK_ERROR_CODES.COMMON.UNKNOWN, {
                message: error.message,
                description: "",
                possibleFix: "Please check error message and stack trace",
                originalError: error,
                metadata: {},
            });
            if (shouldThrow) {
                throw customError;
            }
            return customError;
        }
        else {
            const isResponseNotPresent = !("response" in error);
            if (isResponseNotPresent) {
                const nonResponseError = this.handleNonResponseAxiosError(error);
                if (shouldThrow) {
                    throw nonResponseError;
                }
                return nonResponseError;
            }
            const apiError = this.throwAPIError(error);
            if (shouldThrow) {
                throw apiError;
            }
            return apiError;
        }
    }
    static handleNonResponseAxiosError(error) {
        var _a, _b;
        const fullUrl = (((_a = error.config) === null || _a === void 0 ? void 0 : _a.baseURL) || "") + (((_b = error.config) === null || _b === void 0 ? void 0 : _b.url) || "");
        const metadata = generateMetadataFromAxiosError(error);
        if (error.code === "ECONNREFUSED") {
            throw new ComposioError(COMPOSIO_SDK_ERROR_CODES.COMMON.BASE_URL_NOT_REACHABLE, `ECONNREFUSED for ${fullUrl}`, "", "Make sure:\n1. The base URL is correct and is accessible\n2. Your network connection is stable\n3. There are no firewall rules blocking the connection", metadata, error);
        }
        if (error.code === "ETIMEDOUT") {
            throw new ComposioError(COMPOSIO_SDK_ERROR_CODES.COMMON.REQUEST_TIMEOUT, `ECONNABORTED for ${fullUrl}`, `Request to ${fullUrl} timed out after the configured timeout period. This could be due to slow network conditions, server performance issues, or the request being too large. Error code: ETIMEDOUT`, "Try:\n1. Checking your network speed and stability\n2. Increasing the request timeout setting if needed\n3. Breaking up large requests into smaller chunks\n4. Retrying the request when network conditions improve\n5. Contact tech@composio.dev if the issue persists", metadata, error);
        }
        if (error.code === "ECONNABORTED") {
            throw new ComposioError(COMPOSIO_SDK_ERROR_CODES.COMMON.REQUEST_ABORTED, error.message, "The request was aborted due to a timeout or other network-related issues. This could be due to network instability, server issues, or the request being too large. Error code: ECONNABORTED", "Try:\n1. Checking your network speed and stability\n2. Increasing the request timeout setting if needed\n3. Breaking up large requests into smaller chunks\n4. Retrying the request when network conditions improve\n5. Contact tech@composio.dev if the issue persists", metadata, error);
        }
        throw new ComposioError(COMPOSIO_SDK_ERROR_CODES.BACKEND.SERVER_UNREACHABLE, error.message ||
            "Server is unreachable. Please contact tech@composio.dev with the error details.", "Server is unreachable. Please contact tech@composio.dev with the error details.", "Please contact tech@composio.dev with the error details.", metadata, error);
    }
    static throwAPIError(error) {
        var _a;
        const statusCode = ((_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.status) || null;
        const errorCode = statusCode
            ? API_TO_SDK_ERROR_CODE[statusCode] ||
                COMPOSIO_SDK_ERROR_CODES.BACKEND.UNKNOWN
            : COMPOSIO_SDK_ERROR_CODES.BACKEND.UNKNOWN;
        const errorDetails = getAPIErrorDetails(error);
        const metadata = generateMetadataFromAxiosError(error);
        throw new ComposioError(errorCode, errorDetails.message, errorDetails.description, errorDetails.possibleFix, metadata, error);
    }
    static returnZodError(error) {
        const errorCode = COMPOSIO_SDK_ERROR_CODES.COMMON.INVALID_PARAMS_PASSED;
        const errorMessage = error.message;
        const errorDescription = "The parameters passed are invalid";
        const possibleFix = "Please check error message for more details";
        const metadata = {
            issues: error.issues,
        };
        return new ComposioError(errorCode, errorMessage, errorDescription, possibleFix, metadata, error);
    }
    static getCustomError(messageCode, { message, type, subtype, description, possibleFix, originalError, metadata, }) {
        const finalErrorCode = !!messageCode ? messageCode : `${type}::${subtype}`;
        const errorDetails = BASE_ERROR_CODE_INFO[finalErrorCode] || BASE_ERROR_CODE_INFO.UNKNOWN;
        const finalMessage = message || errorDetails.message || "";
        const finalDescription = description || errorDetails.description || undefined;
        const finalPossibleFix = possibleFix || errorDetails.possibleFix || "";
        throw new ComposioError(messageCode, finalMessage, finalDescription, finalPossibleFix, metadata, originalError);
    }
}

class BatchProcessor {
    constructor(time = 2000, batchSize = 100, processBatchCallback) {
        this.batch = [];
        this.timer = null;
        this.batch = [];
        this.time = time;
        this.batchSize = batchSize;
        this.processBatchCallback = processBatchCallback;
    }
    pushItem(item) {
        this.batch.push(item);
        if (this.batch.length >= this.batchSize) {
            this.processBatch();
        }
        else if (!this.timer) {
            this.timer = setTimeout(() => this.processBatch(), this.time);
        }
    }
    processBatch() {
        if (this.batch.length > 0) {
            this.processBatchCallback(this.batch);
            this.batch = [];
        }
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = null;
        }
    }
}

var _a;
class TELEMETRY_LOGGER {
    static createTelemetryWrapper(method, className) {
        return async (...args) => {
            const payload = {
                eventName: method.name,
                data: { className, args },
                sdk_meta: {
                    apiKey: ComposioSDKContext.apiKey,
                    baseURL: ComposioSDKContext.baseURL,
                    composioVersion: ComposioSDKContext.composioVersion,
                    frameworkRuntime: ComposioSDKContext.frameworkRuntime,
                    source: ComposioSDKContext.source,
                    sessionId: ComposioSDKContext.sessionId,
                    isBrowser: typeof window !== "undefined",
                },
            };
            _a.batchProcessor.pushItem(payload);
            return method(...args);
        };
    }
    static async sendTelemetry(payload) {
        const isTelemetryDisabled = getEnvVariable("TELEMETRY_DISABLED", "false") === "true";
        if (isTelemetryDisabled) {
            return;
        }
        const url = `${TELEMETRY_URL}/api/sdk_metrics/telemetry`;
        const reqPayload = {
            data: payload,
            url,
            method: "POST",
            headers: { "Content-Type": "application/json" },
        };
        const isBrowser = typeof window !== "undefined";
        if (isBrowser) {
            await sendBrowserReq(reqPayload);
        }
        else {
            await sendProcessReq(reqPayload);
        }
    }
    static manualTelemetry(eventName, data) {
        const payload = {
            eventName,
            data,
            sdk_meta: {
                apiKey: ComposioSDKContext.apiKey,
                baseURL: ComposioSDKContext.baseURL,
                composioVersion: ComposioSDKContext.composioVersion,
                frameworkRuntime: ComposioSDKContext.frameworkRuntime,
                source: ComposioSDKContext.source,
                isBrowser: typeof window !== "undefined",
            },
        };
        _a.batchProcessor.pushItem(payload);
    }
    static wrapFunctionForTelemetry(func, className) {
        return _a.createTelemetryWrapper(func, className);
    }
}
_a = TELEMETRY_LOGGER;
TELEMETRY_LOGGER.batchProcessor = new BatchProcessor(100, 10, async (data) => {
    await _a.sendTelemetry(data);
});

var TELEMETRY_EVENTS;
(function (TELEMETRY_EVENTS) {
    TELEMETRY_EVENTS["SDK_INITIALIZED"] = "SDK_INITIALIZED";
    TELEMETRY_EVENTS["SDK_METHOD_INVOKED"] = "SDK_METHOD_INVOKED";
    TELEMETRY_EVENTS["CLI_INVOKED"] = "CLI_INVOKED";
})(TELEMETRY_EVENTS || (TELEMETRY_EVENTS = {}));

// This file is auto-generated by @hey-api/openapi-ts
const client = clientAxios.createClient(clientAxios.createConfig());
class ClientService {
    /**
     * Get user info
     * Get client info
     */
    static getUserInfo(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/client/auth/client_info",
        });
    }
    /**
     * Add new project
     * Add a new project to the client's organization
     */
    static addProject(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v1/client/auth/project/add",
        });
    }
    /**
     * Delete project
     * Delete a project from the client's organization
     */
    static deleteProject(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).delete({
            ...options,
            url: "/api/v1/client/auth/project/delete/{projectId}",
        });
    }
    /**
     * Get projects
     */
    static getProjects(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/client/auth/projects",
        });
    }
    /**
     * Get org api key
     */
    static getOrgApiKey(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/client/auth/org/api_key",
        });
    }
    /**
     * Regenerate org api key
     */
    static regenerateOrgApiKey(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v1/client/auth/org/api_key/regenerate",
        });
    }
}
class ApiKeysService {
    /**
     * Generate api key
     */
    static generateApiKey(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v1/api_keys",
        });
    }
    /**
     * List api keys
     */
    static listApiKeys(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/api_keys",
        });
    }
    /**
     * Delete api key
     */
    static deleteApiKey(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).delete({
            ...options,
            url: "/api/v1/api_keys/{id}",
        });
    }
}
class AppsService {
    /**
     * List app categories
     * List of available app categories, can be used to filter apps.
     */
    static listAppCategories(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/apps/list/categories",
        });
    }
    /**
     * List app enums
     * List app enums
     */
    static listAppEnums(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/apps/list/enums",
        });
    }
    /**
     * List apps
     * List all apps based on the given filters, if any. This will return all available apps if no filters are provided.
     */
    static getApps(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/apps",
        });
    }
    /**
     * Get single app
     * Get app details
     */
    static getApp(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/apps/{appName}",
        });
    }
}
class IntegrationsService {
    /**
     * Create connector
     * Create a new connector
     */
    static createConnector(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v1/integrations",
        });
    }
    /**
     * List all connectors
     * List all connectors
     */
    static listAllConnectors(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/integrations",
        });
    }
    /**
     * Get connector info
     * Get connector info
     */
    static getConnectorInfo(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/integrations/{integrationId}",
        });
    }
    /**
     * Modify connector
     * Modify a connector
     */
    static modifyConnector(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).patch({
            ...options,
            url: "/api/v1/integrations/{integrationId}",
        });
    }
    /**
     * Delete connector
     * Delete a connector
     */
    static deleteConnector(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).delete({
            ...options,
            url: "/api/v1/integrations/{integrationId}",
        });
    }
}
class ActionsService {
    /**
     * List action enums
     * List action enums
     */
    static listActionEnums(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/actions/list/enums",
        });
    }
    /**
     * List action tags
     * List all the action tags available in composio
     */
    static listActionTags(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v2/actions/list/tags",
        });
    }
    /**
     * List action enums
     * List action enums
     */
    static listActionEnums1(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v2/actions/list/enums",
        });
    }
    /**
     * List actions with complete details
     * List and filter all the actions available in composio, with all the details needed for manual action execution or through function-calling.
     */
    static listActionsV2(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v2/actions",
        });
    }
    /**
     * List actions
     * Retrieve a list of all actions based on query parameters.
     */
    static listActionsMinimalV2(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v2/actions/list/all",
        });
    }
    /**
     * Execute an action
     * Execute an action. Support both connected account and no auth auth.
     */
    static executeActionV2(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v2/actions/{actionId}/execute",
        });
    }
    /**
     * Get action inputs
     * Get the inputs for an action with NLA
     */
    static getActionInputsV2(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v2/actions/{actionId}/execute/get.inputs",
        });
    }
    /**
     * Get single action
     * Get action details, including the input and response schema. This is very useful for setting upfunction/tool calling with composio actions.
     */
    static getActionV2(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v2/actions/{actionId}",
        });
    }
    /**
     * Execute with HTTP Client
     * Use composio as a http client to make request to the connected account service on your behalf, without managing authentication on your side.
     */
    static executeWithHttpClient(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v2/actions/proxy",
        });
    }
    /**
     * Advanced use case search
     * Perform use case search.
     */
    static advancedUseCaseSearch(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v2/actions/search/advanced",
        });
    }
    /**
     * List user files
     */
    static v2ListUserFiles(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v2/actions/files/list",
        });
    }
    /**
     * Create file upload url
     * Create file upload URL for action execution.
     */
    static createFileUploadUrl(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v2/actions/files/upload/{fileType}",
        });
    }
}
class ConnectionsService {
    /**
     * List connections
     * Get all connections in the current project.
     */
    static listConnections(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/connectedAccounts",
        });
    }
    /**
     * Initiate connection
     */
    static initiateConnection(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v1/connectedAccounts",
        });
    }
    /**
     * Update connection data
     * Update connection data
     */
    static updateConnectionData(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).patch({
            ...options,
            url: "/api/v1/connectedAccounts/{connectedAccountId}/data",
        });
    }
    /**
     * Reinitiate connection
     * Reinitiate an existing connection to get new credentials
     */
    static reinitiateConnection(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v1/connectedAccounts/{connectedAccountId}/reinitiate",
        });
    }
    /**
     * Get single connection
     */
    static getConnection(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/connectedAccounts/{connectedAccountId}",
        });
    }
    /**
     * Delete connection
     * Delete a connection
     */
    static deleteConnection(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).delete({
            ...options,
            url: "/api/v1/connectedAccounts/{connectedAccountId}",
        });
    }
    /**
     * Get Auth credentials
     * Get authentication crdentials for the connected account, i.e all the headers, query parameters, etc. that are required to make requests to the third-party service directly.
     */
    static getConnectionInfo(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/connectedAccounts/{connectedAccountId}/info",
        });
    }
    /**
     * Disable connection
     * Disable a connection
     */
    static disableConnection(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v1/connectedAccounts/{connectedAccountId}/disable",
        });
    }
    /**
     * Enable connection
     * Enable a connection
     */
    static enableConnection(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v1/connectedAccounts/{connectedAccountId}/enable",
        });
    }
}
class TriggersService {
    /**
     * List triggers
     * List triggers
     */
    static listTriggers(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/triggers",
        });
    }
    /**
     * List trigger enums
     * List trigger enums
     */
    static listTriggerEnums(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/triggers/list/enums",
        });
    }
    /**
     * Update new webhook
     * Update isNewWebhook
     */
    static updateNewWebhook(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v1/triggers/update_webhook_format",
        });
    }
    /**
     * Enable trigger
     * Enables a trigger for a connected account and specific trigger name.
     */
    static enableTrigger(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v1/triggers/enable/{connectedAccountId}/{triggerName}",
        });
    }
    /**
     * Get active triggers
     * Lists active triggers based on query parameters.
     */
    static getActiveTriggers(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/triggers/active_triggers",
        });
    }
    /**
     * Switch trigger instance status
     * Switches the status of a trigger instance.
     */
    static switchTriggerInstanceStatus(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).patch({
            ...options,
            url: "/api/v1/triggers/instance/{triggerId}/status",
        });
    }
    /**
     * Disable trigger
     * Disables a specified trigger instance.
     */
    static disableTrigger(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v1/triggers/disable/{triggerInstanceId}",
        });
    }
    /**
     * Delete trigger
     * Deletes a specified trigger instance.
     */
    static deleteTrigger(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).delete({
            ...options,
            url: "/api/v1/triggers/instance/{triggerInstanceId}",
        });
    }
    /**
     * Set callback url
     * Sets a universal callback URL for the client.
     */
    static setCallbackUrl(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v1/triggers/set_callback_url",
        });
    }
    /**
     * Get webhook url
     * Retrieves the universal callback URL set for the client.
     */
    static getWebhookUrl(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/triggers/callback_url",
        });
    }
    /**
     * Get logs
     * Fetches logs based on connection and integration details.
     */
    static getTriggerLogs(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/triggers/logs",
        });
    }
    /**
     * Get trigger info
     * Get Trigger Info
     */
    static getTriggerInfoV2(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v2/triggers/{triggerName}",
        });
    }
}
class CliService {
    /**
     * Handle cli code exchange
     */
    static generateCliSession(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/cli/generate-cli-session",
        });
    }
    /**
     * Get cli code
     */
    static getCliCode(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/cli/get-cli-code",
        });
    }
    /**
     * Handle cli code verification
     */
    static verifyCliCode(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/cli/verify-cli-code",
        });
    }
}
class LogsService {
    /**
     * Get logs
     * List logs
     */
    static getLogs(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get({
            ...options,
            url: "/api/v1/logs/",
        });
    }
    /**
     * Post logs
     * Add new logs
     */
    static postLogs(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v1/logs/",
        });
    }
}
class IntegrationsV2Service {
    /**
     * Search connector
     * Search for a connector
     */
    static searchConnector(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v2/integrations/search-by-filters",
        });
    }
    /**
     * Create connector
     * Create a new connector
     */
    static createConnectorV2(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v2/integrations/create",
        });
    }
    /**
     * Get or create connector
     * Get or create a connector
     */
    static getOrCreateConnector(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v2/integrations/get-or-create",
        });
    }
}
class Connectionsv2Service {
    /**
     * Initiate connection
     */
    static initiateConnectionV2(options) {
        var _a;
        return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).post({
            ...options,
            url: "/api/v2/connectedAccounts/initiateConnection",
        });
    }
}

var apiClient = {
    logs: LogsService,
    actionsV1: ActionsService,
    actionsV2: ActionsService,
    apiKeys: ApiKeysService,
    clientAuth: ClientService,
    cli: CliService,
    appConnector: IntegrationsService,
    appConnectorV2: IntegrationsV2Service,
    apps: AppsService,
    connections: ConnectionsService,
    connectionsV2: Connectionsv2Service,
    triggers: TriggersService,
};

const ZActionGetParams = z.z.object({
    actionName: z.z.string(),
});
const ZGetListActionsParams = z.z.object({
    apps: z.z.string().optional().describe("Comma separated app names"),
    actions: z.z.string().optional().describe("Comma separated action names"),
    tags: z.z.string().optional().describe("Comma separated tag names"),
    useCase: z.z.string().nullable().optional().describe("Use case name"),
    usecaseLimit: z.z.number().optional().describe("Limit for use case"),
    showAll: z.z.boolean().optional().describe("Show all actions"),
    showEnabledOnly: z.z.boolean().optional().describe("Show enabled actions"),
    filterImportantActions: z.z
        .boolean()
        .optional()
        .describe("Filter important actions"),
    filterByAvailableApps: z.z
        .boolean()
        .optional()
        .describe("Filter actions by available apps"),
});
const ZParameter = z.z.object({
    name: z.z.string(),
    in: z.z.enum(["query", "header"]),
    value: z.z.string(),
});
const ZCustomAuthParams = z.z.object({
    base_url: z.z.string().optional(),
    parameters: z.z.array(ZParameter),
    body: z.z.record(z.z.unknown()).optional(),
});
const ZExecuteParams = z.z.object({
    actionName: z.z.string(),
    requestBody: z.z.object({
        connectedAccountId: z.z.string().optional(),
        input: z.z.record(z.z.unknown()).optional(),
        appName: z.z.string().optional(),
        text: z.z.string().optional(),
        authConfig: ZCustomAuthParams.optional(),
        allowTracing: z.z.boolean().optional(),
        sessionInfo: z.z
            .object({
            sessionId: z.z.string().optional(),
        })
            .optional(),
    }),
});
const ZFindActionEnumsByUseCaseParams = z.z.object({
    apps: z.z.array(z.z.string()),
    useCase: z.z.string(),
    limit: z.z.number().optional(),
    filterByAvailableApps: z.z.boolean().optional(),
});
const ZExecuteRequestParams = z.z.object({
    connectedAccountId: z.z.string(),
    endpoint: z.z.string(),
    method: z.z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]),
    parameters: z.z.array(ZParameter),
    body: z.z.record(z.z.unknown()).optional(),
});

class Actions {
    constructor(backendClient, client) {
        this.fileName = "js/src/sdk/models/actions.ts";
        this.backendClient = backendClient;
        this.client = client;
    }
    /**
     * Retrieves details of a specific action in the Composio platform by providing its action name.
     *
     * The response includes the action's name, display name, description, input parameters, expected response, associated app information, and enabled status.
     *
     * @param {GetActionData} data The data for the request.
     * @returns {Promise<ActionItemGetRes[0]>} A promise that resolves to the details of the action.
     * @throws {ComposioError} If the request fails.
     */
    async get(data) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "get",
            file: this.fileName,
            params: { data },
        });
        try {
            const parsedData = ZActionGetParams.parse(data);
            const actions = await apiClient.actionsV2.getActionV2({
                client: this.client,
                path: {
                    actionId: parsedData.actionName,
                },
            });
            return actions.data;
        }
        catch (e) {
            throw CEG.handleAllError(e);
        }
    }
    /**
     * Retrieves a list of all actions in the Composio platform.
     *
     * This method allows you to fetch a list of all the available actions. It supports pagination to handle large numbers of actions. The response includes an array of action objects, each containing information such as the action's name, display name, description, input parameters, expected response, associated app information, and enabled status.
     *
     * @param {GetListActionsData} data The data for the request.
     * @returns {Promise<ActionsListResponseDTO>} A promise that resolves to the list of all actions.
     * @throws {ComposioError} If the request fails.
     */
    async list(data = {}) {
        var _a;
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "list",
            file: this.fileName,
            params: { data },
        });
        try {
            const parsedData = ZGetListActionsParams.parse(data);
            let apps = parsedData.apps;
            // Throw error if user has provided both filterByAvailableApps and apps
            if ((data === null || data === void 0 ? void 0 : data.filterByAvailableApps) && (data === null || data === void 0 ? void 0 : data.apps)) {
                throw new Error("Both filterByAvailableApps and apps cannot be provided together");
            }
            if (data === null || data === void 0 ? void 0 : data.filterByAvailableApps) {
                // Todo: To create a new API to get all integrated apps for a user instead of fetching all apps
                const integratedApps = await apiClient.appConnector.listAllConnectors();
                apps = (_a = integratedApps.data) === null || _a === void 0 ? void 0 : _a.items.map((app) => app === null || app === void 0 ? void 0 : app.appName).join(",");
            }
            const response = await apiClient.actionsV2.listActionsV2({
                client: this.client,
                query: {
                    actions: data.actions,
                    apps: apps,
                    showAll: data.showAll,
                    tags: data.tags,
                    filterImportantActions: data.filterImportantActions,
                    showEnabledOnly: data.showEnabledOnly,
                    usecaseLimit: data.usecaseLimit || undefined,
                    useCase: data.useCase,
                },
            });
            return response.data;
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Executes a specific action in the Composio platform.
     * This doesn't execute the local action and is wrapper over backend. Try to call this method directly from toolset
     *
     * This method allows you to trigger the execution of an action by providing its name and the necessary input parameters. The request includes the connected account ID to identify the app connection to use for the action, and the input parameters required by the action. The response provides details about the execution status and the response data returned by the action.
     *
     * @param {ExecuteActionData} data The data for the request.
     * @returns {Promise<ActionExecuteResponse>} A promise that resolves to the execution status and response data.
     * @throws {ComposioError} If the request fails.
     */
    async execute(data) {
        var _a, _b, _c;
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "execute",
            file: this.fileName,
            params: { data },
        });
        try {
            const parsedData = ZExecuteParams.parse(data);
            const { data: res } = await apiClient.actionsV2.executeActionV2({
                client: this.client,
                body: {
                    ...parsedData.requestBody,
                    sessionInfo: {
                        ...(((_a = parsedData.requestBody) === null || _a === void 0 ? void 0 : _a.sessionInfo) || {}),
                        sessionId: ((_c = (_b = parsedData.requestBody) === null || _b === void 0 ? void 0 : _b.sessionInfo) === null || _c === void 0 ? void 0 : _c.sessionId) ||
                            ComposioSDKContext.sessionId,
                    },
                    allowTracing: Boolean(ComposioSDKContext === null || ComposioSDKContext === void 0 ? void 0 : ComposioSDKContext.allowTracing),
                },
                path: {
                    actionId: parsedData.actionName,
                },
            });
            return res;
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Finds all action enums by use case.
     *
     * @param {FindActionEnumsByUseCaseParam} data The data for the request.
     * @returns {Promise<ActionFindActionEnumsByUseCaseRes>} A promise that resolves to the list of action enums.
     * @throws {ComposioError} If the request fails.
     */
    async findActionEnumsByUseCase(data) {
        var _a;
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "findActionEnumsByUseCase",
            file: this.fileName,
            params: { data },
        });
        try {
            const parsedData = ZFindActionEnumsByUseCaseParams.parse(data);
            const { data: res } = await apiClient.actionsV2.advancedUseCaseSearch({
                client: this.client,
                query: {
                    apps: (_a = parsedData.apps) === null || _a === void 0 ? void 0 : _a.join(","),
                    limit: parsedData.limit || undefined,
                    filterByAvailableApps: parsedData.filterByAvailableApps,
                },
                body: {
                    useCase: parsedData.useCase,
                },
            });
            return res.items.map((item) => item.actions).flat() || [];
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Executes a action using Composio Proxy
     *
     * This method allows you to trigger the execution of an action by providing its name and the necessary input parameters. The request includes the connected account ID to identify the app connection to use for the action, and the input parameters required by the action. The response provides details about the execution status and the response data returned by the action.
     *
     * @param {ExecuteActionData} data The data for the request.
     * @returns {Promise<ActionExecuteResponse>} A promise that resolves to the execution status and response data.
     * @throws {ComposioError} If the request fails.
     */
    async executeRequest(data) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "executeRequest",
            file: this.fileName,
            params: { data },
        });
        try {
            const parsedData = ZExecuteRequestParams.parse(data);
            const { data: res } = await apiClient.actionsV2.executeWithHttpClient({
                client: this.client,
                body: {
                    connectedAccountId: parsedData.connectedAccountId,
                    endpoint: parsedData.endpoint,
                    method: parsedData.method,
                    parameters: parsedData.parameters,
                    body: parsedData.body,
                },
            });
            return res;
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
}

const ZTriggerItemParam = z.z.object({
    triggerId: z.z.string(),
});
const ZActiveTriggersQuery = z.z.object({
    triggerIds: z.z.string().optional(),
    triggerNames: z.z.string().optional(),
    connectedAccountIds: z.z.string().optional(),
    integrationIds: z.z.string().optional(),
    limit: z.z.number().optional(),
    page: z.z.number().optional(),
    showDisabled: z.z.boolean().optional(),
});
const ZConnection = z.z.object({
    id: z.z.string(),
    integrationId: z.z.string(),
    memberId: z.z.string(),
    clientUniqueUserId: z.z.string(),
    status: z.z.string(),
    data: z.z.record(z.z.unknown()),
    deleted: z.z.boolean().optional(),
    enabled: z.z.boolean(),
    labels: z.z.array(z.z.unknown()),
    createdAt: z.z.string(),
    updatedAt: z.z.string(),
});
z.z.object({
    id: z.z.string(),
    connectionId: z.z.string(),
    triggerName: z.z.string(),
    triggerData: z.z.string(),
    triggerConfig: z.z.record(z.z.unknown()),
    state: z.z.record(z.z.unknown()),
    createdAt: z.z.string(),
    updatedAt: z.z.string(),
    disabledAt: z.z.string().nullable(),
    disabledReason: z.z.string().nullable(),
    connection: ZConnection,
});

class ActiveTriggers {
    constructor(backendClient, client) {
        this.fileName = "js/src/sdk/models/activeTriggers.ts";
        this.backendClient = backendClient;
        this.client = client;
    }
    /** Missing type */
    /**
     * Retrieves details of a specific active trigger in the Composio platform by providing its trigger name.
     *
     * The response includes the trigger's name, description, input parameters, expected response, associated app information, and enabled status.
     *
     * @param {TriggerItemParam} data The data for the request.
     * @returns {Promise<TriggerItemRes>} A promise that resolves to the details of the active trigger.
     * @throws {ComposioError} If the request fails.
     */
    async get({ triggerId }) {
        var _a;
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "get",
            file: this.fileName,
            params: { triggerId },
        });
        try {
            const parsedData = ZTriggerItemParam.parse({ triggerId });
            const { data } = await apiClient.triggers.getActiveTriggers({
                client: this.client,
                query: {
                    triggerIds: `${parsedData.triggerId}`,
                },
            });
            return (_a = data === null || data === void 0 ? void 0 : data.triggers) === null || _a === void 0 ? void 0 : _a[0];
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Retrieves a list of all active triggers in the Composio platform.
     *
     * This method allows you to fetch a list of all the available active triggers. It supports pagination to handle large numbers of triggers. The response includes an array of trigger objects, each containing information such as the trigger's name, description, input parameters, expected response, associated app information, and enabled status.
     *
     * @param {GetActiveTriggersData} data The data for the request.
     * @returns {Promise<ZActiveTriggerItemRes[]>} A promise that resolves to the list of all active triggers.
     * @throws {ComposioError} If the request fails.
     */
    async list(data = {}) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "list",
            file: this.fileName,
            params: { data },
        });
        try {
            const parsedData = ZActiveTriggersQuery.parse(data);
            const { data: response } = await apiClient.triggers.getActiveTriggers({
                client: this.client,
                query: parsedData,
            });
            return response === null || response === void 0 ? void 0 : response.triggers;
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Enables the previously disabled trigger.
     *
     * @param {TriggerItemParam} data The data for the request.
     * @returns {Promise<{status: string}>} A promise that resolves to the response of the enable request.
     * @throws {ComposioError} If the request fails.
     */
    async enable(data) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "enable",
            file: this.fileName,
            params: { data },
        });
        try {
            const parsedData = ZTriggerItemParam.parse(data);
            await apiClient.triggers.switchTriggerInstanceStatus({
                client: this.client,
                path: { triggerId: parsedData.triggerId },
                body: {
                    enabled: true,
                },
            });
            return {
                status: "success",
            };
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Disables the previously enabled trigger.
     *
     * @param {TriggerItemParam} data The data for the request.
     * @returns {Promise<{status: string}>} A promise that resolves to the response of the disable request.
     */
    async disable(data) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "disable",
            file: this.fileName,
            params: { data },
        });
        try {
            const parsedData = ZTriggerItemParam.parse(data);
            await apiClient.triggers.switchTriggerInstanceStatus({
                client: this.client,
                path: parsedData,
                body: {
                    enabled: false,
                },
            });
            return {
                status: "success",
            };
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
}

z.z.object({
    appKey: z.z.string(),
});
const ZGetRequiredParams = z.z.object({
    appId: z.z.string(),
});
const ZGetRequiredParamsForAuthScheme = z.z.object({
    appId: z.z.string(),
    authScheme: z.z.string(),
});
const ZRequiredParamsResponse = z.z.object({
    required_fields: z.z.array(z.z.string()),
    expected_from_user: z.z.array(z.z.string()),
    optional_fields: z.z.array(z.z.string()),
});
z.z.object({
    availableAuthSchemes: z.z.array(z.z.string()),
    authSchemes: z.z.record(z.z.string(), ZRequiredParamsResponse),
});

class Apps {
    constructor(backendClient, client) {
        this.fileName = "js/src/sdk/models/apps.ts";
        this.backendClient = backendClient;
        this.client = client;
    }
    /**
     * Retrieves a list of all available apps in the Composio platform.
     *
     * This method allows clients to explore and discover the supported apps. It returns an array of app objects, each containing essential details such as the app's key, name, description, logo, categories, and unique identifier.
     *
     * @returns {Promise<AppItemListResponse[]>} A promise that resolves to the list of all apps.
     * @throws {ComposioError} If the request fails.
     */
    async list() {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "list",
            file: this.fileName,
            params: {},
        });
        try {
            const { data } = await apiClient.apps.getApps({
                client: this.client,
                query: {
                    additionalFields: "auth_schemes",
                },
            });
            return (data === null || data === void 0 ? void 0 : data.items) || [];
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Retrieves details of a specific app in the Composio platform.
     *
     * This method allows clients to fetch detailed information about a specific app by providing its unique key. The response includes the app's name, key, status, description, logo, categories, authentication schemes, and other metadata.
     *
     * @param {AppGetDataParams} data The data for the request, including the app's unique key.
     * @returns {Promise<AppItemResponse>} A promise that resolves to the details of the app.
     * @throws {ComposioError} If the request fails.
     */
    async get(data) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "get",
            file: this.fileName,
            params: { data },
        });
        try {
            const { data: response } = await apiClient.apps.getApp({
                client: this.client,
                path: {
                    appName: data.appKey,
                },
            });
            if (!response)
                throw new Error("App not found");
            return response;
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Retrieves the required parameters for a specific app in the Composio platform.
     *
     * This method allows clients to fetch the necessary parameters for a specific app by providing its unique key. The response includes the app's name, key, status, description, logo, categories, authentication schemes, and other metadata.
     *
     * @param {string} appId The unique key of the app.
     * @returns {Promise<AppRequiredParamsFullResponse>} A promise that resolves to the required parameters for the app.
     * @throws {ComposioError} If the request fails.
     */
    async getRequiredParams(appId) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "getRequiredParams",
            file: this.fileName,
            params: { appId },
        });
        try {
            ZGetRequiredParams.parse({ appId });
            const appData = await this.get({ appKey: appId });
            if (!appData)
                throw new Error("App not found");
            const authSchemes = appData.auth_schemes;
            const availableAuthSchemes = authSchemes === null || authSchemes === void 0 ? void 0 : authSchemes.map((scheme) => scheme === null || scheme === void 0 ? void 0 : scheme.mode);
            const authSchemesObject = {};
            for (const scheme of authSchemes) {
                const name = scheme.mode;
                authSchemesObject[name] = {
                    required_fields: [],
                    optional_fields: [],
                    expected_from_user: [],
                };
                scheme.fields.forEach((field) => {
                    const isExpectedForIntegrationSetup = field.expected_from_customer === false;
                    const isRequired = field.required;
                    if (isExpectedForIntegrationSetup) {
                        if (isRequired) {
                            authSchemesObject[name].expected_from_user.push(field.name);
                        }
                        else {
                            authSchemesObject[name].optional_fields.push(field.name);
                        }
                    }
                    else {
                        authSchemesObject[name].required_fields.push(field.name);
                    }
                });
            }
            return {
                availableAuthSchemes,
                authSchemes: authSchemesObject,
            };
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Retrieves the required parameters for a specific authentication scheme of an app in the Composio platform.
     *
     * This method allows clients to fetch the necessary parameters for a specific authentication scheme of an app by providing its unique key and the authentication scheme.
     *
     * @param {AppGetRequiredParamsForAuthSchemeParam} data The data for the request, including the app's unique key and the authentication scheme.
     * @returns {Promise<AppRequiredParamsResponse>} A promise that resolves to the required parameters for the authentication scheme.
     * @throws {ComposioError} If the request fails.
     */
    async getRequiredParamsForAuthScheme({ appId, appName, authScheme, }) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "getRequiredParamsForAuthScheme",
            file: this.fileName,
            params: { appId, authScheme },
        });
        try {
            const finalAppId = appName || appId;
            ZGetRequiredParamsForAuthScheme.parse({ appId: finalAppId, authScheme });
            const params = await this.getRequiredParams(finalAppId);
            return params.authSchemes[authScheme];
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
}

const ZConnectionStatus = z.z.enum(["INITIATED", "ACTIVE", "FAILED"]);
const ZListConnectionsData = z.z.object({
    appNames: z.z.string().optional(),
    appUniqueKeys: z.z.string().array().optional(),
    connectionId: z.z.string().optional(),
    entityId: z.z.string().optional(),
    integrationId: z.z.string().optional(),
    labels: z.z.string().optional(),
    page: z.z.number().optional(),
    pageSize: z.z.number().optional(),
    showActiveOnly: z.z.boolean().optional(),
    showDisabled: z.z.boolean().optional(),
    status: ZConnectionStatus.optional(),
    user_uuid: z.z.string().optional(),
});
z.z.object({
    connectionParams: z.z.record(z.z.string(), z.z.unknown()).optional(),
    entityId: z.z.string().optional(),
    labels: z.z.array(z.z.string()).optional(),
    integrationId: z.z.string().optional(),
    redirectUri: z.z.string().optional(),
    authMode: ZAuthMode.optional(),
    authConfig: z.z.record(z.z.string(), z.z.unknown()).optional(),
    appName: z.z.string().optional(),
});
const ZSaveUserAccessDataParam = z.z.object({
    fieldInputs: z.z.record(z.z.string(), z.z.unknown()),
    redirectUrl: z.z.string().optional(),
    entityId: z.z.string().optional(),
});
const ZSingleConnectionParams = z.z.object({
    connectedAccountId: z.z.string(),
});
z.z.object({
    data: z.z.record(z.z.string(), z.z.unknown()),
    integrationId: z.z.string(),
    redirectUri: z.z.string().optional(),
    userUuid: z.z.string().optional(),
    entityId: z.z.string().optional(),
    labels: z.z.string().array().optional(),
});
const ZReinitiateConnectionPayloadDto = z.z.object({
    connectedAccountId: z.z.string(),
    data: z.z.record(z.z.string(), z.z.unknown()),
    redirectUri: z.z.string().optional(),
});

/**
 * Class representing connected accounts in the system.
 */
class ConnectedAccounts {
    /**
     * Initializes a new instance of the ConnectedAccounts class.
     * @param {AxiosBackendClient} backendClient - The backend client instance.
     */
    constructor(backendClient, client) {
        this.fileName = "js/src/sdk/models/connectedAccounts.ts";
        this.backendClient = backendClient;
        this.client = client;
    }
    /**
     * List all connected accounts
     * @param {ConnectedAccountsListData} data - The data for the connected accounts list
     * @returns {Promise<ConnectedAccountListResponse>} - A promise that resolves to a list of connected accounts
     */
    async list(data) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "list",
            file: this.fileName,
            params: { data },
        });
        try {
            const { appNames, appUniqueKeys } = ZListConnectionsData.parse(data);
            const finalAppNames = appNames || (appUniqueKeys === null || appUniqueKeys === void 0 ? void 0 : appUniqueKeys.join(","));
            const res = await apiClient.connections.listConnections({
                client: this.client,
                query: {
                    ...data,
                    appNames: finalAppNames,
                },
            });
            return res.data;
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Get a single connected account
     * @param {SingleConnectionParam} data - The data for the single connection
     * @returns {Promise<SingleConnectedAccountResponse>} - A promise that resolves to a single connected account
     */
    async get(data) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "get",
            file: this.fileName,
            params: { data },
        });
        try {
            ZSingleConnectionParams.parse(data);
            const res = await apiClient.connections.getConnection({
                client: this.client,
                path: data,
                throwOnError: true,
            });
            return res.data;
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Delete a single connected account
     * @param {SingleConnectionParam} data - The data for the single connection
     * @returns {Promise<SingleDeleteResponse>} - A promise that resolves when the connected account is deleted
     */
    async delete(data) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "delete",
            file: this.fileName,
            params: { data },
        });
        try {
            ZSingleConnectionParams.parse(data);
            const res = await apiClient.connections.deleteConnection({
                client: this.client,
                path: data,
                throwOnError: true,
            });
            return res.data;
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Disable a single connected account
     * @param {SingleConnectionParam} data - The data for the single connection
     * @returns {Promise<ConnectionChangeResponse>} - A promise that resolves when the connected account is disabled
     */
    async disable(data) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "disable",
            file: this.fileName,
            params: { data },
        });
        try {
            ZSingleConnectionParams.parse(data);
            const res = await apiClient.connections.disableConnection({
                client: this.client,
                path: data,
                throwOnError: true,
            });
            return {
                status: "success",
                connectedAccountId: data.connectedAccountId,
            };
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Enable a single connected account
     * @param {SingleConnectionParam} data - The data for the single connection
     * @returns {Promise<ConnectionChangeResponse>} - A promise that resolves when the connected account is enabled
     */
    async enable(data) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "enable",
            file: this.fileName,
            params: { data },
        });
        try {
            ZSingleConnectionParams.parse(data);
            await apiClient.connections.enableConnection({
                client: this.client,
                path: {
                    connectedAccountId: data.connectedAccountId,
                },
                throwOnError: true,
            });
            return {
                status: "success",
                connectedAccountId: data.connectedAccountId,
            };
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Initiate a connection
     * @param {InitiateConnectionDataReq} payload - The payload for the connection initiation
     * @returns {Promise<ConnectionRequest>} - A promise that resolves to a connection request
     */
    async initiate(payload) {
        var _a;
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "initiate",
            file: this.fileName,
            params: { payload },
        });
        try {
            const connection = await apiClient.connectionsV2.initiateConnectionV2({
                client: this.client,
                body: {
                    app: {
                        uniqueKey: payload.appName,
                        integrationId: payload.integrationId,
                    },
                    config: {
                        name: payload.appName,
                        useComposioAuth: !!payload.authMode && !!payload.authConfig,
                        authScheme: payload.authMode,
                        integrationSecrets: payload.authConfig,
                    },
                    connection: {
                        entityId: payload.entityId,
                        initiateData: payload.connectionParams || {},
                        extra: {
                            redirectURL: payload.redirectUri,
                            labels: payload.labels || [],
                        },
                    },
                },
            });
            const connectionResponse = (_a = connection === null || connection === void 0 ? void 0 : connection.data) === null || _a === void 0 ? void 0 : _a.connectionResponse;
            return new ConnectionRequest({
                connectionStatus: connectionResponse === null || connectionResponse === void 0 ? void 0 : connectionResponse.connectionStatus,
                connectedAccountId: connectionResponse === null || connectionResponse === void 0 ? void 0 : connectionResponse.connectedAccountId,
                redirectUri: connectionResponse === null || connectionResponse === void 0 ? void 0 : connectionResponse.redirectUrl,
                client: this.client,
            });
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Reinitiate a connection
     * @param {ReinitiateConnectionPayload} data - The payload for the connection reinitialization
     * @returns {Promise<ConnectionRequest>} - A promise that resolves to a connection request
     */
    async reinitiateConnection(data) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "reinitiateConnection",
            file: this.fileName,
            params: { data },
        });
        try {
            ZReinitiateConnectionPayloadDto.parse(data);
            const connection = await apiClient.connections.reinitiateConnection({
                client: this.client,
                path: {
                    connectedAccountId: data.connectedAccountId,
                },
                body: {
                    data: data.data,
                    redirectUri: data.redirectUri,
                },
            });
            const res = connection.data;
            return new ConnectionRequest({
                connectionStatus: res === null || res === void 0 ? void 0 : res.connectionStatus,
                connectedAccountId: res === null || res === void 0 ? void 0 : res.connectedAccountId,
                redirectUri: res === null || res === void 0 ? void 0 : res.redirectUrl,
                client: this.client,
            });
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
}
class ConnectionRequest {
    constructor({ connectionStatus, connectedAccountId, redirectUri, client, }) {
        this.connectionStatus = connectionStatus;
        this.connectedAccountId = connectedAccountId;
        this.redirectUrl = redirectUri;
        this.client = client;
    }
    async saveUserAccessData(data) {
        try {
            ZSaveUserAccessDataParam.parse(data);
            const { data: connectedAccount } = await apiClient.connections.getConnection({
                client: this.client,
                path: { connectedAccountId: this.connectedAccountId },
            });
            if (!connectedAccount)
                throw new Error("Connected account not found");
            return await apiClient.connections.initiateConnection({
                client: this.client,
                body: {
                    integrationId: connectedAccount.integrationId,
                    //@ts-ignore
                    data: data.fieldInputs,
                    redirectUri: data.redirectUrl,
                    userUuid: data.entityId,
                    entityId: data.entityId,
                },
            });
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Wait until the connection becomes active
     * @param {number} timeout - The timeout for the connection to become active
     * @returns {Promise<Connection>} - A promise that resolves to the connection
     */
    async waitUntilActive(timeout = 60) {
        try {
            const startTime = Date.now();
            while (Date.now() - startTime < timeout * 1000) {
                const connection = await apiClient.connections
                    .getConnection({
                    client: this.client,
                    path: { connectedAccountId: this.connectedAccountId },
                })
                    .then((res) => res.data);
                if (!connection)
                    throw new Error("Connected account not found");
                if (connection.status === "ACTIVE") {
                    return connection;
                }
                await new Promise((resolve) => setTimeout(resolve, 1000));
            }
            throw new Error("Connection did not become active within the timeout period.");
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
}

class Integrations {
    constructor(backendClient, client) {
        this.fileName = "js/src/sdk/models/integrations.ts";
        this.backendClient = backendClient;
        this.client = client;
    }
    /**
     * Retrieves a list of all available integrations in the Composio platform.
     *
     * This method allows clients to explore and discover the supported integrations. It returns an array of integration objects, each containing essential details such as the integration's key, name, description, logo, categories, and unique identifier.
     *
     * @returns {Promise<IntegrationListRes>} A promise that resolves to the list of all integrations.
     * @throws {ComposioError} If the request fails.
     */
    async list(data = {}) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "list",
            file: this.fileName,
            params: { data },
        });
        try {
            const { appName, appUniqueKey, ...rest } = ZListIntegrationsParams.parse(data);
            const finalAppName = appName && appName.length > 0 ? appName : appUniqueKey;
            const response = await apiClient.appConnector.listAllConnectors({
                client: this.client,
                query: { ...rest, appName: finalAppName },
                throwOnError: true,
            });
            return response.data;
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Retrieves details of a specific integration in the Composio platform by providing its integration name.
     *
     * The response includes the integration's name, display name, description, input parameters, expected response, associated app information, and enabled status.
     *
     * @param {IntegrationGetParam} data The data for the request.
     * @returns {Promise<IntegrationGetResponse>} A promise that resolves to the details of the integration.
     * @throws {ComposioError} If the request fails.
     */
    async get(data) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "get",
            file: this.fileName,
            params: { data },
        });
        try {
            const response = await apiClient.appConnector.getConnectorInfo({
                client: this.client,
                path: data,
                throwOnError: true,
            });
            return response.data;
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Retrieves the required parameters for a specific integration's authentication scheme.
     *
     * This method is used to get the necessary input fields for a specific integration's authentication scheme.
     *
     * @param {IntegrationGetParam} data The data for the request.
     * @returns {Promise<IntegrationRequiredParamsRes>} A promise that resolves to the required parameters for the integration's authentication scheme.
     * @throws {ComposioError} If the request fails.
     */
    async getRequiredParams(data) {
        var _a;
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "getRequiredParams",
            file: this.fileName,
            params: { data },
        });
        try {
            ZSingleIntegrationParams.parse(data);
            const response = await apiClient.appConnector.getConnectorInfo({
                client: this.client,
                path: {
                    integrationId: data.integrationId,
                },
                throwOnError: true,
            });
            return (_a = response.data) === null || _a === void 0 ? void 0 : _a.expectedInputFields;
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Creates a new integration in the Composio platform.
     *
     * This method allows clients to create a new integration by providing the necessary details such as app ID, name, authentication mode, and configuration.
     *
     * @param {IntegrationCreateParams} data The data for the request.
     * @returns {Promise<IntegrationGetResponse>} A promise that resolves to the created integration model.
     * @throws {ComposioError} If the request fails.
     */
    async create(data) {
        var _a;
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "create",
            file: this.fileName,
            params: { data },
        });
        try {
            ZCreateIntegrationParams.parse(data);
            let uniqueKey = data.appUniqueKey;
            if (!uniqueKey) {
                const apps = await apiClient.apps.getApps({ client: this.client });
                const app = (_a = apps.data) === null || _a === void 0 ? void 0 : _a.items.find((app) => app.appId === data.appId);
                uniqueKey = app.key;
                if (!uniqueKey) {
                    throw CEG.getCustomError(COMPOSIO_SDK_ERROR_CODES.COMMON.INVALID_PARAMS_PASSED, {
                        message: `No app was found with the provided appId`,
                        description: `Please provide an app unique key`,
                    });
                }
            }
            const response = await apiClient.appConnectorV2.createConnectorV2({
                client: this.client,
                body: {
                    app: {
                        uniqueKey: uniqueKey,
                    },
                    config: {
                        useComposioAuth: data.useComposioAuth,
                        name: data.name,
                        authScheme: data.authScheme,
                        integrationSecrets: data.authConfig,
                    },
                },
                throwOnError: true,
            });
            const integrationId = response.data.integrationId;
            return this.get({ integrationId });
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    async getOrCreateIntegration(data) {
        var _a;
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "getOrCreateIntegration",
            file: this.fileName,
            params: { data },
        });
        try {
            ZCreateIntegrationParams.parse(data);
            let uniqueKey = data.appUniqueKey;
            if (!uniqueKey) {
                const apps = await apiClient.apps.getApps({ client: this.client });
                const app = (_a = apps.data) === null || _a === void 0 ? void 0 : _a.items.find((app) => app.appId === data.appId);
                uniqueKey = app.key;
                throw CEG.getCustomError(COMPOSIO_SDK_ERROR_CODES.COMMON.INVALID_PARAMS_PASSED, {
                    message: `No app was found with the provided appId`,
                    description: `Please provide an app unique key`,
                });
            }
            const response = await apiClient.appConnectorV2.getOrCreateConnector({
                client: this.client,
                body: {
                    app: {
                        uniqueKey,
                    },
                    config: {
                        useComposioAuth: data.useComposioAuth,
                        name: data.name,
                        authScheme: data.authScheme,
                        integrationSecrets: data.authConfig,
                    },
                },
                throwOnError: true,
            });
            const integrationId = response.data.integrationId;
            return this.get({ integrationId });
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Deletes an existing integration in the Composio platform.
     *
     * This method allows clients to delete an existing integration by providing its integration ID.
     *
     * @param {IntegrationListData} data The data for the request.
     * @returns {Promise<IntegrationDeleteResponse>} A promise that resolves to the deleted integration model.
     * @throws {ComposioError} If the request fails.
     */
    async delete(data) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "delete",
            file: this.fileName,
            params: { data },
        });
        try {
            ZSingleIntegrationParams.parse(data);
            const response = await apiClient.appConnector.deleteConnector({
                client: this.client,
                path: {
                    integrationId: data.integrationId,
                },
                throwOnError: true,
            });
            return response.data;
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
}

const PUSHER_KEY = process.env.CLIENT_PUSHER_KEY || "8e1b8c92b7f8b2151c15";
const PUSHER_CLUSTER = "mt1";
class PusherUtils {
    static getPusherClient(baseURL, apiKey) {
        if (!PusherUtils.pusherClient) {
            // Dynamic import not available, using require for now
            // TODO: Update to use dynamic import when available
            // eslint-disable-next-line @typescript-eslint/no-require-imports
            const PusherClient = require("pusher-js");
            PusherUtils.pusherClient = new PusherClient(PUSHER_KEY, {
                cluster: PUSHER_CLUSTER,
                channelAuthorization: {
                    endpoint: `${baseURL}/api/v1/client/auth/pusher_auth`,
                    headers: {
                        "x-api-key": apiKey,
                    },
                    transport: "ajax",
                },
            });
        }
        return PusherUtils.pusherClient;
    }
    /**
     * Subscribes to a Pusher channel and binds an event to a callback function.
     * @param {string} channelName - The name of the channel to subscribe to.
     * @param {string} event - The event to bind to the channel.
     * @param {(data: Record<string, unknown>) => void} fn - The callback function to execute when the event is triggered.
     * @returns {PusherClient} The Pusher client instance.
     */
    static async subscribe(channelName, event, fn) {
        try {
            await PusherUtils.pusherClient.subscribe(channelName).bind(event, fn);
        }
        catch (error) {
            logger.error(`Error subscribing to ${channelName} with event ${event}: ${error}`);
        }
    }
    /**
     * Unsubscribes from a Pusher channel.
     * @param {string} channelName - The name of the channel to unsubscribe from.
     * @returns {void}
     */
    static async unsubscribe(channelName) {
        PusherUtils.pusherClient.unsubscribe(channelName);
    }
    /**
     * Binds an event to a channel with support for chunked messages.
     * @param {PusherClient} channel - The Pusher channel to bind the event to.
     * @param {string} event - The event to bind to the channel.
     * @param {(data: unknown) => void} callback - The callback function to execute when the event is triggered.
     */
    static bindWithChunking(channel, event, callback) {
        channel.bind(event, callback); // Allow normal unchunked events.
        // Now the chunked variation. Allows arbitrarily long messages.
        const events = {};
        channel.bind("chunked-" + event, (data) => {
            const typedData = data;
            if (!events.hasOwnProperty(typedData.id)) {
                events[typedData.id] = { chunks: [], receivedFinal: false };
            }
            const ev = events[typedData.id];
            ev.chunks[typedData.index] = typedData.chunk;
            if (typedData.final)
                ev.receivedFinal = true;
            if (ev.receivedFinal &&
                ev.chunks.length === Object.keys(ev.chunks).length) {
                callback(JSON.parse(ev.chunks.join("")));
                delete events[typedData.id];
            }
        });
    }
    /**
     * Subscribes to a trigger channel for a client and handles chunked data.
     * @param {string} clientId - The unique identifier for the client subscribing to the events.
     * @param {(data: TriggerData) => void} fn - The callback function to execute when trigger data is received.
     */
    static triggerSubscribe(clientId, fn) {
        const channel = PusherUtils.pusherClient.subscribe(`private-${clientId}_triggers`);
        PusherUtils.bindWithChunking(channel, "trigger_to_client", fn);
        logger.info(`Subscribed to triggers. You should start receiving events now.`);
    }
    static triggerUnsubscribe(clientId) {
        PusherUtils.pusherClient.unsubscribe(`${clientId}_triggers`);
    }
}

const ZTriggerQuery = z.z.object({
    triggerIds: z.z.array(z.z.string()).optional().describe("Trigger Instance IDs"),
    triggerInstanceIds: z.z
        .array(z.z.string())
        .optional()
        .describe("Trigger Instance IDs"),
    appNames: z.z.array(z.z.string()).optional().describe("App Names in lowercase"),
    appUniqueKeys: z.z.array(z.z.string()).optional().describe("App Unique Keys"),
    connectedAccountIds: z.z
        .array(z.z.string())
        .optional()
        .describe("Connected Account UUIDs"),
    integrationIds: z.z.array(z.z.string()).optional().describe("Integration IDs"),
    showEnabledOnly: z.z
        .boolean()
        .optional()
        .describe("Show Enabled triggers only"),
});
const ZTriggerInstanceItems = z.z.object({
    triggerInstanceId: z.z.string(),
});
const ZTriggerSetupParam = z.z.object({
    connectedAccountId: z.z.string(),
    triggerName: z.z.string(),
    config: z.z.record(z.z.unknown()).optional(),
});
z.z.object({
    appName: z.z.string().optional(),
    triggerId: z.z.string().optional(),
    connectionId: z.z.string().optional(),
    integrationId: z.z.string().optional(),
    triggerName: z.z.string().optional(),
    triggerData: z.z.string().optional(),
    entityId: z.z.string().optional(),
});
const ZSingleTriggerParam = z.z.object({
    triggerId: z.z.string().optional(),
    triggerName: z.z.string().optional(),
});
z.z.object({
    triggerInstanceId: z.z.string().optional(),
    triggerId: z.z.string().optional(),
});
z.z.object({
    name: z.z.string(),
    displayName: z.z.string(),
    description: z.z.string(),
    type: z.z.string(),
    appId: z.z.string(),
    appName: z.z.string(),
    instructions: z.z.string().optional(),
    payload: z.z.record(z.z.unknown()),
    config: z.z.record(z.z.unknown()),
});

class Triggers {
    constructor(backendClient, client) {
        this.trigger_to_client_event = "trigger_to_client";
        this.fileName = "js/src/sdk/models/triggers.ts";
        this.backendClient = backendClient;
        this.client = client;
    }
    /**
     * Retrieves a list of all triggers in the Composio platform.
     *
     * This method allows you to fetch a list of all the available triggers. It supports pagination to handle large numbers of triggers. The response includes an array of trigger objects, each containing information such as the trigger's name, description, input parameters, expected response, associated app information, and enabled status.
     *
     * @param {ListTriggersData} data The data for the request.
     * @returns {Promise<ListTriggersResponse>} A promise that resolves to the list of all triggers.
     * @throws {ComposioError} If the request fails.
     */
    async list(data = {}) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "list",
            file: this.fileName,
            params: { data },
        });
        try {
            const { appNames, triggerIds, connectedAccountIds, integrationIds, showEnabledOnly, triggerInstanceIds, appUniqueKeys, } = ZTriggerQuery.parse(data);
            const finalTriggerInstanceIds = triggerIds && triggerIds.length > 0 ? triggerIds : triggerInstanceIds;
            const finalAppNames = appNames && appNames.length > 0 ? appNames : appUniqueKeys;
            const { data: response } = await apiClient.triggers.listTriggers({
                client: this.client,
                query: {
                    appNames: finalAppNames === null || finalAppNames === void 0 ? void 0 : finalAppNames.join(","),
                    triggerIds: finalTriggerInstanceIds === null || finalTriggerInstanceIds === void 0 ? void 0 : finalTriggerInstanceIds.join(","),
                    connectedAccountIds: connectedAccountIds === null || connectedAccountIds === void 0 ? void 0 : connectedAccountIds.join(","),
                    integrationIds: integrationIds === null || integrationIds === void 0 ? void 0 : integrationIds.join(","),
                    showEnabledOnly: showEnabledOnly || false,
                },
            });
            if (!response || response.length === 0) {
                throw CEG.getCustomError(COMPOSIO_SDK_ERROR_CODES.BACKEND.NOT_FOUND, {
                    message: "Trigger not found with the given params",
                    description: "Trigger not found with the given params",
                    possibleFix: "Pass a check if filter params are correct",
                });
            }
            return response;
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Retrieves the configuration of a single trigger.
     *
     * @param {TriggerSingleParam} data The data for the request.
     * @returns {Promise<TriggerSingleConfig>} A promise that resolves to the trigger configuration.
     * @throws {ComposioError} If the request fails.
     */
    async get(data) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            client: this.client,
            method: "get",
            file: this.fileName,
            params: { data },
        });
        return this.getTriggerInfo(data);
    }
    /**
     * @deprecated use trigger.get instead
     * Retrieves the configuration of a single trigger.
     *
     * @param {TriggerSingleParam} data The data for the request.
     * @returns {Promise<TriggerSingleConfig>} A promise that resolves to the trigger configuration.
     * @throws {ComposioError} If the request fails.
     */
    async getTriggerConfig(data) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "getSingleTriggerConfig",
            file: this.fileName,
            params: { data },
        });
        try {
            const parsedData = ZSingleTriggerParam.parse(data);
            if (!parsedData.triggerName && !parsedData.triggerId) {
                throw CEG.getCustomError(COMPOSIO_SDK_ERROR_CODES.COMMON.INVALID_PARAMS_PASSED, {
                    message: "Trigger name or trigger id is required",
                    description: "Trigger name or trigger id is required",
                    possibleFix: "Pass either triggerName or triggerId",
                });
            }
            const res = await apiClient.triggers.getTriggerInfoV2({
                client: this.client,
                path: {
                    triggerName: parsedData.triggerName || parsedData.triggerId || "",
                },
            });
            // Bad type inference
            const triggerInfo = res.data;
            if (!triggerInfo) {
                throw CEG.getCustomError(COMPOSIO_SDK_ERROR_CODES.BACKEND.NOT_FOUND, {
                    message: "Trigger info not found",
                    description: "Trigger info not found",
                    possibleFix: "Pass a check if trigger exists",
                });
            }
            return { config: triggerInfo.config };
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Retrieves information about a single trigger.
     *
     * @param {TriggerSingleParam} data The data for the request.
     * @returns {Promise<SingleTriggerRes>} A promise that resolves to the trigger information.
     * @throws {ComposioError} If the request fails.
     */
    async getTriggerInfo(data) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "getTriggerInfo",
            file: this.fileName,
            params: { data },
        });
        try {
            const parsedData = ZSingleTriggerParam.parse(data);
            const res = await apiClient.triggers.getTriggerInfoV2({
                client: this.client,
                path: {
                    triggerName: parsedData.triggerName || parsedData.triggerId || "",
                },
            });
            // Bad type inference
            const trigger = res.data;
            if (!trigger) {
                throw CEG.getCustomError(COMPOSIO_SDK_ERROR_CODES.BACKEND.NOT_FOUND, {
                    message: "Trigger info not found",
                    description: "Trigger info not found",
                    possibleFix: "Pass a check if trigger exists",
                });
            }
            return trigger;
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Setup a trigger for a connected account.
     *
     * @param {SetupTriggerData} data The data for the request.
     * @returns {Promise<SetupTriggerResponse>} A promise that resolves to the setup trigger response.
     * @throws {ComposioError} If the request fails.
     */
    async setup(params) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "setup",
            file: this.fileName,
            params: params,
        });
        try {
            const parsedData = ZTriggerSetupParam.parse(params);
            const response = await apiClient.triggers.enableTrigger({
                client: this.client,
                path: {
                    connectedAccountId: parsedData.connectedAccountId,
                    triggerName: parsedData.triggerName,
                },
                body: {
                    triggerConfig: parsedData.config || {},
                },
                throwOnError: true,
            });
            const { triggerId, status } = response.data;
            return {
                triggerId: triggerId,
                triggerName: parsedData.triggerName,
                status,
                triggerInstanceId: triggerId,
            };
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Enables a trigger for a connected account.
     *
     * @param {triggerId,triggerInstanceId} data The data for the request.
     * @returns {Promise<boolean>} A promise that resolves to the response of the enable request.
     * @throws {ComposioError} If the request fails.
     */
    async enable(data) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "enable",
            file: this.fileName,
            params: { data },
        });
        try {
            const finalTriggerId = data.triggerId || data.triggerInstanceId;
            if (!finalTriggerId) {
                throw CEG.getCustomError(COMPOSIO_SDK_ERROR_CODES.COMMON.INVALID_PARAMS_PASSED, {
                    message: "Trigger ID is required",
                    description: "Trigger ID is required",
                    possibleFix: "Pass either triggerId or triggerInstanceId",
                });
            }
            await apiClient.triggers.switchTriggerInstanceStatus({
                client: this.client,
                path: {
                    triggerId: finalTriggerId,
                },
                body: {
                    enabled: true,
                },
            });
            return {
                status: "success",
            };
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Disables a trigger for a connected account.
     *
     * @param {triggerId,triggerInstanceId} data The data for the request.
     * @returns {Promise<boolean>} A promise that resolves to the response of the disable request.
     * @throws {ComposioError} If the request fails.
     */
    async disable(data) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "disable",
            file: this.fileName,
            params: { data },
        });
        try {
            const finalTriggerId = data.triggerId || data.triggerInstanceId;
            if (!finalTriggerId) {
                throw CEG.getCustomError(COMPOSIO_SDK_ERROR_CODES.COMMON.INVALID_PARAMS_PASSED, {
                    message: "Trigger ID is required",
                    description: "Trigger ID is required",
                    possibleFix: "Pass either triggerId or triggerInstanceId",
                });
            }
            await apiClient.triggers.switchTriggerInstanceStatus({
                client: this.client,
                path: {
                    triggerId: finalTriggerId,
                },
                body: {
                    enabled: false,
                },
            });
            return {
                status: "success",
            };
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Deletes a trigger for a connected account.
     *
     * @param {TriggerInstanceItems} data The data for the request.
     * @returns {Promise<boolean>} A promise that resolves to the response of the delete request.
     * @throws {ComposioError} If the request fails.
     */
    async delete(data) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "delete",
            file: this.fileName,
            params: { data },
        });
        try {
            const parsedData = ZTriggerInstanceItems.parse(data);
            await apiClient.triggers.deleteTrigger({
                client: this.client,
                path: {
                    triggerInstanceId: parsedData.triggerInstanceId,
                },
            });
            return {
                status: "success",
            };
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    async subscribe(fn, filters = {}) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "subscribe",
            file: this.fileName,
            params: { filters },
        });
        if (!fn)
            throw new Error("Function is required for trigger subscription");
        const clientId = await this.backendClient.getClientId();
        await PusherUtils.getPusherClient(this.backendClient.baseUrl, this.backendClient.apiKey);
        const shouldSendTrigger = (data) => {
            if (Object.keys(filters).length === 0)
                return true;
            else {
                return ((!filters.appName ||
                    data.appName.toLowerCase() === filters.appName.toLowerCase()) &&
                    (!filters.triggerId ||
                        data.metadata.id.toLowerCase() ===
                            filters.triggerId.toLowerCase()) &&
                    (!filters.connectionId ||
                        data.metadata.connectionId.toLowerCase() ===
                            filters.connectionId.toLowerCase()) &&
                    (!filters.triggerName ||
                        data.metadata.triggerName.toLowerCase() ===
                            filters.triggerName.toLowerCase()) &&
                    (!filters.entityId ||
                        data.metadata.connection.clientUniqueUserId.toLowerCase() ===
                            filters.entityId.toLowerCase()) &&
                    (!filters.integrationId ||
                        data.metadata.connection.integrationId.toLowerCase() ===
                            filters.integrationId.toLowerCase()));
            }
        };
        logger.debug("Subscribing to triggers", filters);
        PusherUtils.triggerSubscribe(clientId, (data) => {
            if (shouldSendTrigger(data)) {
                fn(data);
            }
        });
    }
    async unsubscribe() {
        const clientId = await this.backendClient.getClientId();
        PusherUtils.triggerUnsubscribe(clientId);
    }
}

const LABELS = {
    PRIMARY: "primary",
};
class Entity {
    constructor(backendClient, id = "default") {
        this.fileName = "js/src/sdk/models/Entity.ts";
        this.backendClient = backendClient;
        this.id = id;
        this.triggerModel = new Triggers(this.backendClient, this.backendClient.instance);
        this.actionsModel = new Actions(this.backendClient, this.backendClient.instance);
        this.apps = new Apps(this.backendClient, this.backendClient.instance);
        this.connectedAccounts = new ConnectedAccounts(this.backendClient, this.backendClient.instance);
        this.integrations = new Integrations(this.backendClient, this.backendClient.instance);
        this.activeTriggers = new ActiveTriggers(this.backendClient, this.backendClient.instance);
    }
    /**
     * Executes an action for an entity.
     *
     * @param {string} actionName The name of the action to execute.
     * @param {Record<string, unknown>} params The parameters for the action.
     * @param {string} text The text to pass to the action. This can be to perform NLA execution
     * @param {string} connectedAccountId The ID of the connected account to use for the action.
     * @returns {Promise<ActionExecuteResponse>} A promise that resolves to the response from the action execution.
     * @throws {ComposioError} If the request fails.
     */
    async execute({ actionName, params, text, connectedAccountId, }) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "execute",
            file: this.fileName,
            params: { actionName, params, text, connectedAccountId },
        });
        try {
            ZExecuteActionParams$1.parse({
                actionName,
                params,
                text,
                connectedAccountId,
            });
            const action = await this.actionsModel.get({
                actionName: actionName,
            });
            if (!action) {
                throw new Error(`Could not find action: ${actionName}`);
            }
            const app = await this.apps.get({
                appKey: action.appKey,
            });
            if (app.no_auth) {
                return this.actionsModel.execute({
                    actionName: actionName,
                    requestBody: {
                        input: params,
                        appName: action.appKey,
                    },
                });
            }
            const connectedAccount = await this.getConnection({
                app: action.appKey,
                connectedAccountId,
            });
            if (!connectedAccount) {
                throw CEG.getCustomError(COMPOSIO_SDK_ERROR_CODES.SDK.NO_CONNECTED_ACCOUNT_FOUND, {
                    message: `Could not find a connection with app='${action.appKey}' and entity='${this.id}'`,
                    description: `Could not find a connection with app='${action.appKey}' and entity='${this.id}'`,
                });
            }
            return this.actionsModel.execute({
                actionName: actionName,
                requestBody: {
                    // @ts-ignore
                    connectedAccountId: connectedAccount === null || connectedAccount === void 0 ? void 0 : connectedAccount.id,
                    input: params,
                    appName: action.appKey,
                    text: text,
                },
            });
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Retrieves the required parameters for a specific authentication scheme of an app in the Composio platform.
     *
     * This method allows clients to fetch the necessary parameters for a specific authentication scheme of an app by providing its unique key and the authentication scheme.
     *
     * @param {ConnectionParams} data The data for the request, including the app's unique key and the authentication scheme.
     * @returns {Promise<RequiredParamsResponse>} A promise that resolves to the required parameters for the authentication scheme.
     * @throws {ComposioError} If the request fails.
     */
    async getConnection({ app, appName, connectedAccountId }) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "getConnection",
            file: this.fileName,
            params: { app, appName, connectedAccountId },
        });
        try {
            const finalApp = appName || app;
            ZConnectionParams.parse({ app: finalApp, connectedAccountId });
            if (!finalApp && !connectedAccountId) {
                throw CEG.getCustomError(COMPOSIO_SDK_ERROR_CODES.COMMON.INVALID_PARAMS_PASSED, {
                    message: "App or connectedAccountId is required",
                    description: "App or connectedAccountId is required",
                });
            }
            if (connectedAccountId) {
                return await this.connectedAccounts.get({
                    connectedAccountId,
                });
            }
            let latestAccount = null;
            let latestCreationDate = null;
            const connectedAccounts = await this.connectedAccounts.list({
                user_uuid: this.id,
            });
            for (const account of connectedAccounts.items) {
                if ((account === null || account === void 0 ? void 0 : account.labels) && (account === null || account === void 0 ? void 0 : account.labels.includes(LABELS.PRIMARY))) {
                    latestAccount = account;
                    break;
                }
            }
            if (!latestAccount) {
                for (const connectedAccount of connectedAccounts.items) {
                    if ((finalApp === null || finalApp === void 0 ? void 0 : finalApp.toLocaleLowerCase()) ===
                        connectedAccount.appName.toLocaleLowerCase()) {
                        const creationDate = new Date(connectedAccount.createdAt);
                        if ((!latestAccount ||
                            (latestCreationDate && creationDate > latestCreationDate)) &&
                            connectedAccount.status === "ACTIVE") {
                            latestCreationDate = creationDate;
                            latestAccount = connectedAccount;
                        }
                    }
                }
            }
            if (!latestAccount) {
                throw CEG.getCustomError(COMPOSIO_SDK_ERROR_CODES.SDK.NO_CONNECTED_ACCOUNT_FOUND, {
                    message: `Could not find a connection with app='${finalApp}' and entity='${this.id}'`,
                    description: `Could not find a connection with app='${finalApp}' and entity='${this.id}'`,
                });
            }
            const connectedAccount = await this.connectedAccounts.get({
                connectedAccountId: latestAccount.id,
            });
            if (!connectedAccount) {
                throw CEG.getCustomError(COMPOSIO_SDK_ERROR_CODES.SDK.NO_CONNECTED_ACCOUNT_FOUND, {
                    message: `Could not find a connection with app='${finalApp}' and entity='${this.id}'`,
                    description: `Could not find a connection with app='${finalApp}' and entity='${this.id}'`,
                });
            }
            return connectedAccount;
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Retrieves the required parameters for a specific authentication scheme of an app in the Composio platform.
     *
     * This method allows clients to setup a trigger for an app by providing its unique key and the trigger name.
     *
     * @param {TriggerSubscribeParam} data The data for the request, including the app's unique key and the trigger name.
     * @returns {Promise<RequiredParamsResponse>} A promise that resolves to the required parameters for the authentication scheme.
     * @throws {ComposioError} If the request fails.
     */
    async setupTrigger({ app, appName, triggerName, config, }) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "setupTrigger",
            file: this.fileName,
            params: { app, appName, triggerName, config },
        });
        try {
            const finalApp = appName || app;
            ZTriggerSubscribeParam.parse({ app: finalApp, triggerName, config });
            const connectedAccount = await this.getConnection({ app: finalApp });
            if (!connectedAccount) {
                throw CEG.getCustomError(COMPOSIO_SDK_ERROR_CODES.SDK.NO_CONNECTED_ACCOUNT_FOUND, {
                    message: `Could not find a connection with app='${finalApp}' and entity='${this.id}'`,
                    description: `Could not find a connection with app='${finalApp}' and entity='${this.id}'`,
                });
            }
            const trigger = await this.triggerModel.setup({
                connectedAccountId: connectedAccount.id,
                triggerName,
                config,
            });
            return trigger;
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Retrieves the required parameters for a specific authentication scheme of an app in the Composio platform.
     *
     * This method allows clients to disable a trigger by providing its trigger ID.
     *
     * @param {string} triggerId The ID of the trigger to disable.
     * @returns {Promise<{ status: string }>} A promise that resolves to the status of the trigger disablement.
     * @throws {ComposioError} If the request fails.
     */
    async disableTrigger(triggerId) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "disableTrigger",
            file: this.fileName,
            params: { triggerId },
        });
        try {
            await this.activeTriggers.disable({ triggerId: triggerId });
            return { status: "success" };
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Retrieves all connections for an entity.
     *
     * @returns {Promise<ConnectionItem[]>} A promise that resolves to an array of connection items.
     * @throws {ComposioError} If the request fails.
     */
    async getConnections() {
        /**
         * Get all connections for an entity.
         */
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "getConnections",
            file: this.fileName,
            params: {},
        });
        try {
            const connectedAccounts = await this.connectedAccounts.list({
                user_uuid: this.id,
            });
            return connectedAccounts.items;
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Retrieves all active triggers for an entity.
     *
     * @returns {Promise<ActiveTrigger[]>} A promise that resolves to an array of active triggers.
     * @throws {ComposioError} If the request fails.
     */
    async getActiveTriggers() {
        /**
         * Get all active triggers for an entity.
         */
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "getActiveTriggers",
            file: this.fileName,
            params: {},
        });
        try {
            const connectedAccounts = await this.getConnections();
            const activeTriggers = await this.activeTriggers.list({
                // @ts-ignore
                connectedAccountIds: connectedAccounts
                    .map((account) => account.id)
                    .join(","),
            });
            return activeTriggers;
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Initiate a connection for an entity.
     * @param {InitiateConnectionParams} data The data for the request, including the app's unique key and the authentication scheme.
     * @returns {Promise<ConnectionRequest>} A promise that resolves to the connection request.
     * @throws {ComposioError} If the request fails.
     */
    async initiateConnection(data) {
        var _a, _b;
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "initiateConnection",
            file: this.fileName,
            params: { data },
        });
        try {
            const { appName, authMode, authConfig, integrationId, connectionParams, redirectUri, labels, } = ZInitiateConnectionParams.parse(data);
            // Initiate the connection process
            return this.connectedAccounts.initiate({
                authMode: authMode,
                authConfig: authConfig,
                integrationId: integrationId,
                appName: appName,
                entityId: this.id,
                redirectUri: redirectUri || ((_a = data.config) === null || _a === void 0 ? void 0 : _a.redirectUrl) || "",
                connectionParams: connectionParams,
                labels: labels || ((_b = data.config) === null || _b === void 0 ? void 0 : _b.labels) || [],
            });
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
}

const removeTrailingSlashIfExists = (str) => str.replace(/\/+$/, "");

/**
 * Class representing the details required to initialize and configure the API client.
 */
class AxiosBackendClient {
    /**
     * Creates an instance of apiClientDetails.
     * @param {string} apiKey - The API key for client initialization.
     * @param {string} baseUrl - The base URL for the API client.
     * @param {string} runtime - The runtime environment identifier.
     * @throws Will throw an error if the API key is not provided.
     */
    constructor(apiKey, baseUrl, runtime) {
        this.runtime = runtime || "";
        this.apiKey = apiKey;
        this.baseUrl = removeTrailingSlashIfExists(baseUrl);
        this.instance = clientAxios.createClient(clientAxios.createConfig({
            baseURL: this.baseUrl,
            headers: {
                // common: {
                "X-API-KEY": `${this.apiKey}`,
                "X-SOURCE": "js_sdk",
                "X-RUNTIME": this.runtime,
                // }
            },
        }));
        if (!apiKey) {
            throw CEG.getCustomError(COMPOSIO_SDK_ERROR_CODES.COMMON.API_KEY_UNAVAILABLE, {
                message: "API key is not available",
                description: "The API key required for authentication is not provided. You can get the API key from the Composio dashboard.",
                possibleFix: "Please provide the API key in the constructor",
            });
        }
        // Validate baseUrl
        if (!baseUrl.startsWith("http://") && !baseUrl.startsWith("https://")) {
            throw CEG.getCustomError(COMPOSIO_SDK_ERROR_CODES.COMMON.BASE_URL_NOT_REACHABLE, {
                message: `🔗 Base URL ${baseUrl} is not valid`,
                description: "The composio backend URL provided is not valid",
            });
        }
        this.initializeApiClient();
    }
    /**
     * Retrieves the client ID from the user's information.
     * @returns {Promise<string>} A promise that resolves to the client ID.
     * @throws Will throw an error if the HTTP request fails.
     */
    async getClientId() {
        var _a;
        try {
            const { data } = await apiClient.clientAuth.getUserInfo({
                client: this.instance,
            });
            return ((_a = data === null || data === void 0 ? void 0 : data.client) === null || _a === void 0 ? void 0 : _a.id) || "";
        }
        catch (error) {
            throw CEG.handleAllError(error);
        }
    }
    /**
     * Initializes the API client with the provided configuration.
     * @private
     */
    initializeApiClient() {
        this.instance.setConfig({
            baseURL: removeTrailingSlashIfExists(this.baseUrl),
            headers: {
                common: {
                    "X-API-KEY": `${this.apiKey}`,
                    "X-SOURCE": "js_sdk",
                    "X-RUNTIME": this.runtime,
                },
            },
            throwOnError: true,
        });
        // setAxiosClientConfig(this.instance.instance);
    }
    getAxiosInstance() {
        return this.instance.instance;
    }
}

// File path helpers
const userDataPath = () => {
    try {
        // eslint-disable-next-line @typescript-eslint/no-require-imports
        const path = require("path");
        // eslint-disable-next-line @typescript-eslint/no-require-imports
        const os = require("os");
        return path.join(os.homedir(), COMPOSIO_DIR, USER_DATA_FILE_NAME);
    }
    catch (_error) {
        return null;
    }
};
const getUserDataJson = () => {
    try {
        // eslint-disable-next-line @typescript-eslint/no-require-imports
        const fs = require("fs");
        const data = fs.readFileSync(userDataPath(), "utf8");
        return JSON.parse(data);
    }
    catch (_error) {
        return {};
    }
};
// Axios configuration
const setAxiosClientConfig = (axiosClientInstance) => {
    axiosClientInstance.interceptors.request.use((request) => {
        var _a;
        const body = request.data ? JSON.stringify(request.data) : "";
        // set x-request-id header
        const requestId = getUUID();
        request.headers["x-request-id"] = requestId;
        request.metadata = {
            startTime: Date.now(),
            requestId,
        };
        logger.debug(`API Req [${(_a = request.method) === null || _a === void 0 ? void 0 : _a.toUpperCase()}] ${request.url}, x-request-id: ${requestId}`, {
            ...(body && { body }),
            query: request.params,
        });
        return request;
    });
    axiosClientInstance.interceptors.response.use((response) => {
        var _a, _b, _c;
        const method = (_a = response.config.method) === null || _a === void 0 ? void 0 : _a.toUpperCase();
        const responseSize = Math.round(JSON.stringify(response.data).length / 1024);
        const requestStartTime = (_b = response.config
            .metadata) === null || _b === void 0 ? void 0 : _b.startTime;
        const responseTime = requestStartTime ? Date.now() - requestStartTime : 0;
        const status = response.status;
        const requestId = response.headers["x-request-id"] ||
            ((_c = response.config.metadata) === null || _c === void 0 ? void 0 : _c.requestId);
        // @ts-expect-error Error with metadata type
        response["metadata"] = {
            responseTime,
            responseSize,
            requestId,
        };
        logger.debug(`API Res [${method}] ${response.config.url} - ${status} - ${responseSize} KB ${responseTime}ms`);
        return response;
    }, (error) => {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
        const requestStartTime = (_b = (_a = error.config) === null || _a === void 0 ? void 0 : _a.metadata) === null || _b === void 0 ? void 0 : _b.startTime;
        const requestStartTimeId = (_d = (_c = error.config) === null || _c === void 0 ? void 0 : _c.metadata) === null || _d === void 0 ? void 0 : _d.requestId;
        const responseTime = requestStartTime ? Date.now() - requestStartTime : 0;
        const status = ((_e = error.response) === null || _e === void 0 ? void 0 : _e.status) || "Unknown";
        const length = ((_g = JSON.stringify((_f = error.response) === null || _f === void 0 ? void 0 : _f.data)) === null || _g === void 0 ? void 0 : _g.length) || 0;
        const responseSize = Math.round(length / 1024);
        const requestId = ((_j = (_h = error.response) === null || _h === void 0 ? void 0 : _h.headers) === null || _j === void 0 ? void 0 : _j["x-request-id"]) || requestStartTimeId;
        const metadata = {
            responseTime,
            responseSize,
            requestId,
        };
        // @ts-expect-error Error with metadata type
        error.metadata = metadata;
        logger.debug(`API Error [${status}] ${(_l = (_k = error.config) === null || _k === void 0 ? void 0 : _k.method) === null || _l === void 0 ? void 0 : _l.toUpperCase()} ${(_m = error.config) === null || _m === void 0 ? void 0 : _m.url} - ${status} - ${responseTime}ms, x-request-id: ${requestId}`, {
            headers: (_o = error.response) === null || _o === void 0 ? void 0 : _o.headers,
            data: (_p = error.response) === null || _p === void 0 ? void 0 : _p.data,
            error: error.message,
            responseTime,
        });
        return Promise.reject(error);
    });
};
// Client configuration functions
function getSDKConfig(baseUrl, apiKey) {
    const userData = getUserDataJson();
    const { api_key: apiKeyFromUserConfig, base_url: baseURLFromUserConfig } = userData;
    const baseURLParsed = baseUrl ||
        getEnvVariable("COMPOSIO_BASE_URL") ||
        baseURLFromUserConfig ||
        DEFAULT_BASE_URL;
    const apiKeyParsed = apiKey || getEnvVariable("COMPOSIO_API_KEY") || apiKeyFromUserConfig || "";
    return { baseURL: baseURLParsed, apiKey: apiKeyParsed };
}

const isNewerVersion = (v1, v2) => {
    const parts1 = v1.split(".").map(Number);
    const parts2 = v2.split(".").map(Number);
    for (let i = 0; i < 3; i++) {
        if (parts1[i] > parts2[i])
            return true;
        if (parts1[i] < parts2[i])
            return false;
    }
    return false;
};

class Composio {
    /**
     * Initializes a new instance of the Composio class.
     *
     * @param {Object} config - Configuration object for the Composio SDK
     * @param {string} [config.apiKey] - The API key for authenticating with the Composio backend. Can also be set locally in an environment variable.
     * @param {string} [config.baseUrl] - The base URL for the Composio backend. By default, it is set to the production URL.
     * @param {string} [config.runtime] - The runtime environment for the SDK.
     * @param {boolean} [config.allowTracing] - Whether to allow tracing for the SDK.
     */
    constructor(config = {}) {
        this.fileName = "js/src/sdk/index.ts";
        // Parse the base URL and API key, falling back to environment variables or defaults if not provided
        const { baseURL: baseURLParsed, apiKey: apiKeyParsed } = getSDKConfig(config === null || config === void 0 ? void 0 : config.baseUrl, config === null || config === void 0 ? void 0 : config.apiKey);
        if (IS_DEVELOPMENT_OR_CI) {
            logger.info(`Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`);
        }
        ComposioSDKContext.apiKey = apiKeyParsed;
        ComposioSDKContext.baseURL = baseURLParsed;
        ComposioSDKContext.frameworkRuntime = config === null || config === void 0 ? void 0 : config.runtime;
        ComposioSDKContext.composioVersion = COMPOSIO_VERSION;
        ComposioSDKContext.allowTracing = config === null || config === void 0 ? void 0 : config.allowTracing;
        // by default, generate a sessionId unless allowTracing is explicitly set to false
        ComposioSDKContext.sessionId =
            (config === null || config === void 0 ? void 0 : config.allowTracing) !== false ? getUUID() : undefined;
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_INITIALIZED, {});
        if (!apiKeyParsed) {
            throw CEG.getCustomError(COMPOSIO_SDK_ERROR_CODES.COMMON.API_KEY_UNAVAILABLE, {
                message: "🔑 API Key is not provided",
                description: "You need to provide it in the constructor or as an environment variable COMPOSIO_API_KEY",
                possibleFix: "Please provide a valid API Key. You can get it from https://app.composio.dev/settings OR Check if you are passing it as an object in the constructor like - { apiKey: 'your-api-key' }",
            });
        }
        logger.info(`Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`);
        // Initialize the BackendClient with the parsed API key and base URL.
        this.backendClient = new AxiosBackendClient(apiKeyParsed, baseURLParsed, config === null || config === void 0 ? void 0 : config.runtime);
        setAxiosClientConfig(this.backendClient.getAxiosInstance());
        // Instantiate models with dependencies as needed.
        this.connectedAccounts = new ConnectedAccounts(this.backendClient, this.backendClient.instance);
        this.triggers = new Triggers(this.backendClient, this.backendClient.instance);
        this.apps = new Apps(this.backendClient, this.backendClient.instance);
        this.actions = new Actions(this.backendClient, this.backendClient.instance);
        this.integrations = new Integrations(this.backendClient, this.backendClient.instance);
        this.activeTriggers = new ActiveTriggers(this.backendClient, this.backendClient.instance);
        this.checkForLatestVersionFromNPM();
    }
    /**
     * Checks for the latest version of the Composio SDK from NPM.
     * If a newer version is available, it logs a warning to the console.
     */
    async checkForLatestVersionFromNPM() {
        try {
            const packageName = "composio-core";
            const currentVersionFromPackageJson = COMPOSIO_VERSION;
            const response = await axios.get(`https://registry.npmjs.org/${packageName}/latest`);
            const latestVersion = response.data.version;
            if (isNewerVersion(latestVersion, currentVersionFromPackageJson) &&
                !IS_DEVELOPMENT_OR_CI) {
                logger.info(`🚀 Upgrade available! Your composio-core version (${currentVersionFromPackageJson}) is behind. Latest version: ${latestVersion}.`);
            }
        }
        catch (_error) {
            // Ignore and do nothing
        }
    }
    /**
     * Retrieves an Entity instance associated with a given ID.
     *
     * @param {string} [id='default'] - The ID of the entity to retrieve.
     * @returns {Entity} An instance of the Entity class.
     */
    getEntity(id = "default") {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "getEntity",
            file: this.fileName,
            params: { id },
        });
        return new Entity(this.backendClient, id);
    }
    async getExpectedParamsForUser(params) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "getExpectedParamsForUser",
            file: this.fileName,
            params: params,
        });
        const { app } = params;
        let { integrationId } = params;
        if (integrationId === null && app === null) {
            throw new Error("Both `integration_id` and `app` cannot be None");
        }
        if (!integrationId) {
            try {
                const integrations = await this.integrations.list({
                    appName: app,
                    showDisabled: false,
                });
                if (params.authScheme && integrations) {
                    integrations.items = integrations.items.filter((integration) => integration.authScheme === params.authScheme);
                }
                integrationId = (_a = integrations === null || integrations === void 0 ? void 0 : integrations.items[0]) === null || _a === void 0 ? void 0 : _a.id;
            }
            catch (_) {
                // do nothing
            }
        }
        let integration = integrationId
            ? await this.integrations.get({
                integrationId: integrationId,
            })
            : undefined;
        if (integration) {
            return {
                expectedInputFields: integration.expectedInputFields,
                integrationId: integration.id,
                authScheme: integration.authScheme,
            };
        }
        const appInfo = await this.apps.get({
            appKey: app.toLocaleLowerCase(),
        });
        const preferredAuthScheme = [
            "OAUTH2",
            "OAUTH1",
            "API_KEY",
            "BASIC",
            "BEARER_TOKEN",
            "BASIC_WITH_JWT",
        ];
        let schema = params.authScheme;
        if (!schema) {
            for (const scheme of preferredAuthScheme) {
                if ((_b = appInfo.auth_schemes) === null || _b === void 0 ? void 0 : _b.map((_authScheme) => _authScheme.mode).includes(scheme)) {
                    schema = scheme;
                    break;
                }
            }
        }
        const hasTestConnectors = ((_d = (_c = appInfo.testConnectors) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0) > 0;
        const authSchemeFields = (_f = (_e = appInfo.auth_schemes) === null || _e === void 0 ? void 0 : _e.find((_authScheme) => _authScheme.mode === schema)) === null || _f === void 0 ? void 0 : _f.fields;
        const requiredCustomerFields = (_h = (_g = authSchemeFields === null || authSchemeFields === void 0 ? void 0 : authSchemeFields.filter((field) => !field.expected_from_customer)) === null || _g === void 0 ? void 0 : _g.length) !== null && _h !== void 0 ? _h : 0;
        const areNoFieldsRequiredForIntegration = hasTestConnectors || requiredCustomerFields === 0;
        if (!areNoFieldsRequiredForIntegration) {
            throw new Error(`No default credentials available for this app, please create new integration by going to app.composio.dev or through CLI - composio add ${appInfo.key}`);
        }
        const timestamp = new Date().toISOString().replace(/[-:.]/g, "");
        const hasRelevantTestConnectors = params.authScheme
            ? ((_k = (_j = appInfo.testConnectors) === null || _j === void 0 ? void 0 : _j.filter((connector) => connector.authScheme === params.authScheme)) === null || _k === void 0 ? void 0 : _k.length) > 0
            : ((_l = appInfo.testConnectors) === null || _l === void 0 ? void 0 : _l.length) > 0;
        if (hasRelevantTestConnectors) {
            integration = await this.integrations.create({
                appId: appInfo.appId,
                name: `integration_${timestamp}`,
                authScheme: schema,
                authConfig: {},
                useComposioAuth: true,
            });
            return {
                expectedInputFields: integration === null || integration === void 0 ? void 0 : integration.expectedInputFields,
                integrationId: integration === null || integration === void 0 ? void 0 : integration.id,
                authScheme: integration === null || integration === void 0 ? void 0 : integration.authScheme,
            };
        }
        if (!schema) {
            throw new Error(`No supported auth scheme found for \`${String(app)}\`, ` +
                "Please create an integration and use the ID to " +
                "get the expected parameters.");
        }
        integration = await this.integrations.create({
            appId: appInfo.appId,
            name: `integration_${timestamp}`,
            authScheme: schema,
            authConfig: {},
            useComposioAuth: false,
        });
        if (!integration) {
            throw new Error("An unexpected error occurred while creating the integration, please create an integration manually and use its ID to get the expected parameters");
        }
        return {
            expectedInputFields: integration.expectedInputFields,
            integrationId: integration.id,
            authScheme: integration.authScheme,
        };
    }
}

/*
    This is the schema for the raw action to be stored locally
    Also returned by the API
*/
z.z.object({
    name: z.z.string(),
    display_name: z.z.string(),
    description: z.z.string(),
    appKey: z.z.string(),
    appId: z.z.string(),
    appName: z.z.string(),
    logo: z.z.string(),
    enabled: z.z.boolean(),
    tags: z.z.array(z.z.string()),
    parameters: z.z.object({
        type: z.z.string(),
        title: z.z.string(),
        description: z.z.string(),
        required: z.z.array(z.z.string()),
        properties: z.z.record(z.z.any()),
    }),
    response: z.z.record(z.z.any()),
    metadata: z.z.object({
        name: z.z.string(),
        toolName: z.z.string().optional(),
    }),
});
/*
    This is the schema for the params object in the ExecuteAction function
*/
const ZExecuteActionParams = z.z.object({
    action: z.z.string(),
    params: z.z.record(z.z.any()).optional(),
    entityId: z.z.string().optional(),
    nlaText: z.z.string().optional(),
    connectedAccountId: z.z.string().optional(),
    config: z.z
        .object({
        labels: z.z.array(z.z.string()).optional(),
    })
        .optional(),
});
const ZToolSchemaFilter = z.z.object({
    actions: z.z.array(z.z.string()).optional(),
    apps: z.z.array(z.z.string()).optional(),
    tags: z.z.array(z.z.string()).optional(),
    useCase: z.z.string().optional(),
    useCaseLimit: z.z.number().optional(),
    filterByAvailableApps: z.z.boolean().optional(),
    integrationId: z.z.string().optional(),
});

class ActionRegistry {
    constructor(client) {
        this.client = client;
        this.customActions = new Map();
    }
    async createAction(options) {
        var _a;
        const { callback } = options;
        if (typeof callback !== "function") {
            throw new Error("Callback must be a function");
        }
        if (!options.actionName) {
            throw new Error("You must provide actionName for this action");
        }
        if (!options.inputParams) {
            options.inputParams = z.z.object({});
        }
        const params = options.inputParams;
        const actionName = options.actionName || callback.name || "";
        const paramsSchema = (await zodToJsonSchema.zodToJsonSchema(params, {
            name: "input",
        }));
        const _params = paramsSchema.definitions.input.properties;
        const composioSchema = {
            name: actionName,
            description: options.description,
            parameters: {
                title: actionName,
                type: "object",
                description: options.description,
                required: paramsSchema.definitions.input.required || [],
                properties: _params,
            },
            response: {
                type: "object",
                title: "Response for " + actionName,
                properties: [],
            },
        };
        this.customActions.set(((_a = options.actionName) === null || _a === void 0 ? void 0 : _a.toLocaleLowerCase()) || "", {
            metadata: options,
            schema: composioSchema,
        });
        return composioSchema;
    }
    async getActions({ actions, }) {
        const actionsArr = [];
        for (const name of actions) {
            const lowerCaseName = name.toLowerCase();
            if (this.customActions.has(lowerCaseName)) {
                const action = this.customActions.get(lowerCaseName);
                actionsArr.push(action.schema);
            }
        }
        return actionsArr;
    }
    async getAllActions() {
        return Array.from(this.customActions.values()).map((action) => action.schema);
    }
    async getToolName({ action, }) {
        var _a;
        if (!action) {
            throw CEG.getCustomError(COMPOSIO_SDK_ERROR_CODES.COMMON.INVALID_PARAMS_PASSED, {
                message: "Action name is required",
                description: "Please provide an action name to get its tool name",
            });
        }
        const lowerCaseName = action.toLowerCase();
        return (_a = this.customActions.get(lowerCaseName)) === null || _a === void 0 ? void 0 : _a.metadata.toolName;
    }
    async executeAction(name, inputParams, metadata) {
        const lowerCaseName = name.toLocaleLowerCase();
        if (!this.customActions.has(lowerCaseName)) {
            throw new Error(`Action with name ${name} does not exist`);
        }
        const action = this.customActions.get(lowerCaseName);
        if (!action) {
            throw new Error(`Action with name ${name} could not be retrieved`);
        }
        const { callback, toolName } = action.metadata || {};
        let authCredentials = {};
        if (toolName) {
            const entity = await this.client.getEntity(metadata.entityId);
            const connection = await entity.getConnection({
                app: toolName,
                connectedAccountId: metadata.connectionId,
            });
            if (!connection) {
                throw new Error(`Connection with app name ${toolName} and entityId ${metadata.entityId} not found`);
            }
            const connectionParams = connection.connectionParams;
            authCredentials = {
                headers: connectionParams === null || connectionParams === void 0 ? void 0 : connectionParams.headers,
                queryParams: connectionParams === null || connectionParams === void 0 ? void 0 : connectionParams.queryParams,
                baseUrl: (connectionParams === null || connectionParams === void 0 ? void 0 : connectionParams.baseUrl) || (connectionParams === null || connectionParams === void 0 ? void 0 : connectionParams.base_url),
            };
        }
        if (typeof callback !== "function") {
            throw CEG.getCustomError(COMPOSIO_SDK_ERROR_CODES.COMMON.INVALID_PARAMS_PASSED, {
                message: "Callback must be a function",
                description: "Please provide a valid callback function",
            });
        }
        const executeRequest = async (data) => {
            try {
                const { data: res } = await apiClient.actionsV2.executeWithHttpClient({
                    client: this.client.backendClient.instance,
                    body: {
                        ...data,
                        connectedAccountId: metadata === null || metadata === void 0 ? void 0 : metadata.connectionId,
                    },
                });
                return res;
            }
            catch (error) {
                throw CEG.handleAllError(error);
            }
        };
        return await callback(inputParams, authCredentials, (data) => executeRequest(data));
    }
}

/**
 * Gets the Composio directory.
 * @param createDirIfNotExists - Whether to create the directory if it doesn't exist.
 * @returns The path to the Composio directory.
 */
const getComposioDir = (createDirIfNotExists = false) => {
    try {
        // eslint-disable-next-line @typescript-eslint/no-require-imports
        const os = require("os");
        // eslint-disable-next-line @typescript-eslint/no-require-imports
        const path = require("path");
        // eslint-disable-next-line @typescript-eslint/no-require-imports
        const fs = require("fs");
        const composioDir = path.join(os.homedir(), COMPOSIO_DIR);
        if (createDirIfNotExists && !fs.existsSync(composioDir)) {
            fs.mkdirSync(composioDir, { recursive: true });
        }
        return composioDir;
    }
    catch (_error) {
        return null;
    }
};
/**
 * Gets the Composio temporary files directory.
 * @param createDirIfNotExists - Whether to create the directory if it doesn't exist.
 * @returns The path to the Composio temporary files directory.
 */
const getComposioTempFilesDir = (createDirIfNotExists = false) => {
    try {
        // eslint-disable-next-line @typescript-eslint/no-require-imports
        const os = require("os");
        // eslint-disable-next-line @typescript-eslint/no-require-imports
        const path = require("path");
        // eslint-disable-next-line @typescript-eslint/no-require-imports
        const fs = require("fs");
        const composioFilesDir = path.join(os.homedir(), COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME);
        if (createDirIfNotExists && !fs.existsSync(composioFilesDir)) {
            fs.mkdirSync(composioFilesDir, { recursive: true });
        }
        return composioFilesDir;
    }
    catch (_error) {
        return null;
    }
};
/**
 * Saves a file to the Composio directory.
 * @param file - The name of the file to save.
 * @param content - The content of the file to save. Should be a string.
 * @param isTempFile - Whether the file is a temporary file.
 * @returns The path to the saved file.
 */
const saveFile = (file, content, isTempFile = false) => {
    try {
        const path = require("path");
        // eslint-disable-next-line @typescript-eslint/no-require-imports
        const fs = require("fs");
        const composioFilesDir = isTempFile
            ? getComposioTempFilesDir(true)
            : getComposioDir(true);
        const filePath = path.join(composioFilesDir, path.basename(file));
        if (Buffer.isBuffer(content)) {
            fs.writeFileSync(filePath, content);
        }
        else {
            fs.writeFileSync(filePath, content, "utf8");
        }
        return filePath;
    }
    catch (_error) {
        return null;
    }
};

const readFileContent = async (path) => {
    try {
        const content = require("fs").readFileSync(path);
        return {
            content: content.toString("base64"),
            mimeType: "application/octet-stream",
        };
    }
    catch (error) {
        throw new Error(`Error reading file at ${path}: ${error}`);
    }
};
const readFileContentFromURL = async (path) => {
    const response = await axios.get(path, {
        responseType: "arraybuffer",
    });
    const content = Buffer.from(response.data);
    const mimeType = response.headers["content-type"] || "application/octet-stream";
    return {
        content: content.toString("base64"),
        mimeType,
    };
};
const uploadFileToS3 = async (content, actionName, appName, mimeType, client) => {
    var _a;
    const extension = mimeType.split("/")[1] || "bin";
    const response = await apiClient.actionsV2.createFileUploadUrl({
        client: client,
        body: {
            action: actionName,
            app: appName,
            filename: `${actionName}_${Date.now()}.${extension}`,
            mimetype: mimeType,
            md5: crypto
                .createHash("md5")
                .update(Buffer.from(content, "base64"))
                .digest("hex"),
        },
        path: {
            fileType: "request",
        },
    });
    const data = response.data;
    const signedURL = data.url;
    const s3key = data.key;
    try {
        const buffer = Buffer.from(content, "base64");
        await axios.put(signedURL, buffer, {
            headers: {
                "Content-Type": mimeType,
                "Content-Length": buffer.length,
            },
        });
    }
    catch (e) {
        const error = e;
        if (error instanceof axios.AxiosError && ((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) === 403) {
            return signedURL;
        }
        throw new Error(`Error uploading file to S3: ${error}`);
    }
    return s3key;
};
const getFileDataAfterUploadingToS3 = async (path, actionName, client) => {
    const isURL = path.startsWith("http");
    const fileData = isURL
        ? await readFileContentFromURL(path)
        : await readFileContent(path);
    const s3key = await uploadFileToS3(fileData.content, actionName, actionName, fileData.mimeType, client);
    return {
        name: pathModule.basename(path) || `${actionName}_${Date.now()}`,
        mimetype: fileData.mimeType,
        s3key: s3key,
    };
};
const downloadFileFromS3 = async ({ actionName, s3Url, mimeType, }) => {
    const response = await axios.get(s3Url, {
        responseType: "arraybuffer",
    });
    const extension = mimeType.split("/")[1] || "txt";
    const fileName = `${actionName}_${Date.now()}.${extension}`;
    const filePath = saveFile(fileName, response.data, true);
    return {
        name: fileName,
        mimeType: mimeType,
        s3Key: s3Url,
        filePath: filePath,
    };
};

const FILE_SUFFIX = "_schema_parsed_file";
const convertFileSchemaProperty = (key, property) => {
    if (!property.file_uploadable) {
        return property;
    }
    return {
        keyName: `${key}${FILE_SUFFIX}`,
        type: "string",
        description: property.description,
    };
};
const processFileUpload = async (params, actionName, client) => {
    const result = { ...params };
    for (const [key, value] of Object.entries(result)) {
        if (!key.endsWith(FILE_SUFFIX))
            continue;
        const originalKey = key.replace(FILE_SUFFIX, "");
        const fileData = await getFileDataAfterUploadingToS3(value, actionName, client);
        result[originalKey] = fileData;
        delete result[key];
    }
    return result;
};
const FILE_INPUT_PROCESSOR = async ({ params, actionName, client, }) => {
    return processFileUpload(params, actionName, client);
};
const FILE_DOWNLOADABLE_PROCESSOR = async ({ actionName, toolResponse, }) => {
    const result = JSON.parse(JSON.stringify(toolResponse));
    for (const [key, value] of Object.entries(toolResponse.data)) {
        const fileData = value;
        if (!(fileData === null || fileData === void 0 ? void 0 : fileData.s3url))
            continue;
        const downloadedFile = await downloadFileFromS3({
            actionName,
            s3Url: fileData.s3url,
            mimeType: fileData.mimetype || "application/txt",
        });
        result.data[key] = {
            uri: downloadedFile.filePath,
            s3url: fileData.s3url,
            mimeType: downloadedFile.mimeType,
        };
    }
    return result;
};
const FILE_SCHEMA_PROCESSOR = ({ toolSchema }) => {
    const { properties, required: requiredProps = [] } = toolSchema.parameters;
    const newProperties = { ...properties };
    const newRequired = [...requiredProps];
    for (const [key, property] of Object.entries(newProperties)) {
        if (!property.file_uploadable)
            continue;
        const { type, keyName, description } = convertFileSchemaProperty(key, property);
        newProperties[keyName] = {
            title: property.title,
            type,
            description,
        };
        if (requiredProps.includes(key)) {
            newRequired[newRequired.indexOf(key)] = keyName;
        }
        delete newProperties[key];
    }
    return {
        ...toolSchema,
        parameters: {
            ...toolSchema.parameters,
            properties: newProperties,
            required: newRequired,
        },
    };
};

class ComposioToolSet {
    /**
     * Creates a new instance of ComposioToolSet
     * @param {Object} config - Configuration object
     * @param {string|null} config.apiKey - API key for authentication
     * @param {string|null} config.baseUrl - Base URL for API requests
     * @param {string|null} config.runtime - Runtime environment
     * @param {string} config.entityId - Entity ID for operations
     * @param {Record<string, string>} config.connectedAccountIds - Map of app names to their connected account IDs
     * @param {boolean} config.allowTracing - Whether to allow tracing for the SDK
     */
    constructor({ apiKey, baseUrl, runtime, entityId, connectedAccountIds, allowTracing, } = {}) {
        this.entityId = "default";
        this.connectedAccountIds = {};
        this.internalProcessors = {
            pre: [FILE_INPUT_PROCESSOR],
            post: [FILE_DOWNLOADABLE_PROCESSOR],
            schema: [FILE_SCHEMA_PROCESSOR],
        };
        this.userDefinedProcessors = {};
        const clientApiKey = apiKey ||
            getEnvVariable("COMPOSIO_API_KEY") ||
            getUserDataJson().api_key;
        this.apiKey = clientApiKey;
        this.client = new Composio({
            apiKey: this.apiKey,
            baseUrl: baseUrl || undefined,
            runtime: runtime,
            allowTracing: allowTracing || false,
        });
        this.runtime = runtime || null;
        this.backendClient = this.client.backendClient;
        this.connectedAccounts = this.client.connectedAccounts;
        this.apps = this.client.apps;
        this.actions = this.client.actions;
        this.triggers = this.client.triggers;
        this.integrations = this.client.integrations;
        this.activeTriggers = this.client.activeTriggers;
        this.connectedAccountIds = connectedAccountIds || {};
        this.userActionRegistry = new ActionRegistry(this.client);
        if (entityId && connectedAccountIds) {
            logger.warn("When both entity and connectedAccountIds are provided, preference will be given to connectedAccountIds");
        }
        if (connectedAccountIds) {
            this.connectedAccountIds = connectedAccountIds;
        }
        if (entityId) {
            this.entityId = entityId;
        }
    }
    async getActionsSchema(filters = {}, _entityId) {
        return this.getToolsSchema({
            actions: filters.actions || [],
        }, _entityId);
    }
    async getToolsSchema(filters, _entityId, _integrationId) {
        var _a, _b;
        const parsedFilters = ZToolSchemaFilter.parse(filters);
        let actions = parsedFilters.actions;
        if (_integrationId) {
            const integration = await this.integrations.get({
                integrationId: _integrationId,
            });
            if (integration === null || integration === void 0 ? void 0 : integration.limitedActions) {
                if (!actions) {
                    actions = [...integration.limitedActions];
                }
                else {
                    const limitedActionsUppercase = integration.limitedActions.map((action) => action.toUpperCase());
                    actions = actions.filter((action) => limitedActionsUppercase.includes(action.toUpperCase()));
                }
            }
        }
        const appActions = await this.client.actions.list({
            apps: (_a = parsedFilters.apps) === null || _a === void 0 ? void 0 : _a.join(","),
            tags: (_b = parsedFilters.tags) === null || _b === void 0 ? void 0 : _b.join(","),
            useCase: parsedFilters.useCase,
            actions: actions === null || actions === void 0 ? void 0 : actions.join(","),
            usecaseLimit: parsedFilters.useCaseLimit,
            filterByAvailableApps: parsedFilters.filterByAvailableApps,
        });
        const customActions = await this.userActionRegistry.getAllActions();
        const toolsWithCustomActions = customActions.filter((action) => {
            const { name: actionName } = action || {};
            return ((!filters.actions ||
                filters.actions.some((name) => name.toLowerCase() === (actionName === null || actionName === void 0 ? void 0 : actionName.toLowerCase()))) &&
                (!filters.tags ||
                    filters.tags.some((tag) => tag.toLowerCase() === "custom")));
        });
        const toolsActions = [
            ...((appActions === null || appActions === void 0 ? void 0 : appActions.items) || []),
            ...toolsWithCustomActions,
        ];
        const allSchemaProcessor = [
            ...this.internalProcessors.schema,
            ...(this.userDefinedProcessors.schema
                ? [this.userDefinedProcessors.schema]
                : []),
        ];
        const processedTools = [];
        // Iterate over the tools and process them
        for (const tool of toolsActions) {
            let schema = tool;
            // Process the schema with all the processors
            for (const processor of allSchemaProcessor) {
                schema = await processor({
                    actionName: schema === null || schema === void 0 ? void 0 : schema.name,
                    toolSchema: schema,
                });
            }
            processedTools.push(schema);
        }
        return processedTools;
    }
    async createAction(options) {
        return this.userActionRegistry.createAction(options);
    }
    isCustomAction(action) {
        return this.userActionRegistry
            .getActions({ actions: [action] })
            .then((actions) => actions.length > 0);
    }
    async getEntity(entityId) {
        return this.client.getEntity(entityId);
    }
    async executeAction(functionParams) {
        var _a;
        const { action, params: inputParams = {}, entityId = this.entityId, nlaText = "", connectedAccountId, } = ZExecuteActionParams.parse({
            action: functionParams.actionName || functionParams.action,
            params: functionParams.params,
            entityId: functionParams.entityId,
            nlaText: functionParams.nlaText,
            connectedAccountId: functionParams.connectedAccountId,
        });
        if (!entityId && !connectedAccountId) {
            throw CEG.getCustomError(COMPOSIO_SDK_ERROR_CODES.SDK.NO_CONNECTED_ACCOUNT_FOUND, {
                message: `No entityId or connectedAccountId provided`,
                description: `Please provide either entityId or connectedAccountId`,
            });
        }
        let params = inputParams || {};
        const allInputProcessor = [
            ...this.internalProcessors.pre,
            ...(this.userDefinedProcessors.pre
                ? [this.userDefinedProcessors.pre]
                : []),
        ];
        for (const processor of allInputProcessor) {
            params = await processor({
                params: params,
                actionName: action,
                client: this.client.backendClient.instance,
            });
        }
        // Custom actions are always executed in the host/local environment for JS SDK
        let accountId = connectedAccountId;
        if (await this.isCustomAction(action)) {
            if (!accountId) {
                const toolName = await this.userActionRegistry.getToolName({ action });
                const connectedAccounts = await this.client.connectedAccounts.list({
                    appNames: toolName,
                    user_uuid: entityId,
                    status: "ACTIVE",
                    showActiveOnly: true,
                });
                accountId = (_a = connectedAccounts === null || connectedAccounts === void 0 ? void 0 : connectedAccounts.items[0]) === null || _a === void 0 ? void 0 : _a.id;
            }
            // allows the user to use custom actions and tools without a connected account
            if (!accountId) {
                logger.warn("No connected account found for the user. If your custom action requires a connected account, please double check if you have active accounts connected to it.");
            }
            return this.userActionRegistry.executeAction(action, params, {
                entityId: entityId,
                connectionId: accountId,
            });
        }
        const connectedAccountKeys = Object.keys(this.connectedAccountIds);
        if (connectedAccountKeys.length > 0) {
            const actionDetails = await this.actions.get({ actionName: action });
            const appNameKey = connectedAccountKeys.find((key) => key.toLowerCase() === actionDetails.appName);
            if (appNameKey) {
                accountId = this.connectedAccountIds[appNameKey];
            }
        }
        const data = await this.client.getEntity(entityId).execute({
            actionName: action,
            params: params,
            text: nlaText,
            connectedAccountId: accountId,
        });
        return this.processResponse(data, {
            action: action,
            entityId: entityId,
        });
    }
    async processResponse(data, meta) {
        const allOutputProcessor = [
            ...this.internalProcessors.post,
            ...(this.userDefinedProcessors.post
                ? [this.userDefinedProcessors.post]
                : []),
        ];
        // Dirty way to avoid copy
        let dataToReturn = JSON.parse(JSON.stringify(data));
        for (const processor of allOutputProcessor) {
            dataToReturn = await processor({
                actionName: meta.action,
                toolResponse: dataToReturn,
            });
        }
        return dataToReturn;
    }
    async addSchemaProcessor(processor) {
        if (typeof processor === "function") {
            this.userDefinedProcessors.schema = processor;
        }
        else {
            throw new Error("Invalid processor type");
        }
        return this;
    }
    async addPreProcessor(processor) {
        if (typeof processor === "function") {
            this.userDefinedProcessors.pre = processor;
        }
        else {
            throw new Error("Invalid processor type");
        }
        return this;
    }
    async addPostProcessor(processor) {
        if (typeof processor === "function") {
            this.userDefinedProcessors.post = processor;
        }
        else {
            throw new Error("Invalid processor type");
        }
        return this;
    }
    async removePreProcessor() {
        delete this.userDefinedProcessors.pre;
    }
    async removePostProcessor() {
        delete this.userDefinedProcessors.post;
    }
    async removeSchemaProcessor() {
        delete this.userDefinedProcessors.schema;
    }
}

const COMPOSIO_BASE_URL = "https://backend.composio.dev";

/**
 * CloudflareToolSet provides integration with Cloudflare Workers AI
 * for executing AI tool calls and handling responses
 */
class CloudflareToolSet extends ComposioToolSet {
    /**
     * Initialize a new CloudflareToolSet instance
     *
     * @param config Configuration options including API key, base URL, entity ID and workspace config
     */
    constructor(config = {}) {
        super({
            apiKey: config.apiKey || null,
            baseUrl: config.baseUrl || COMPOSIO_BASE_URL,
            runtime: null,
            entityId: config.entityId || CloudflareToolSet.DEFAULT_ENTITY_ID,
            connectedAccountIds: config.connectedAccountIds,
            allowTracing: config.allowTracing || false,
        });
        this.fileName = "js/src/frameworks/cloudflare.ts";
    }
    /**
     * Retrieve available tools based on provided filters
     *
     * @param filters Optional filters for actions, apps, tags and use cases
     * @returns Promise resolving to array of AI text generation tools
     */
    async getTools(filters) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "getTools",
            file: this.fileName,
            params: filters,
        });
        const actions = await this.getToolsSchema(filters);
        return (actions.map((action) => {
            // Format the action schema for Cloudflare Workers AI
            const formattedSchema = {
                name: action.name,
                description: action.description,
                parameters: action.parameters,
            };
            const tool = {
                type: "function",
                function: formattedSchema,
            };
            return tool;
        }) || []);
    }
    /**
     * Execute a single tool call
     *
     * @param tool The tool to execute with name and arguments
     * @param entityId Optional entity ID to execute the tool for
     * @returns Promise resolving to stringified tool execution result
     */
    async executeToolCall(tool, entityId = null) {
        var _a, _b, _c;
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "executeToolCall",
            file: this.fileName,
            params: { tool, entityId },
        });
        const toolSchema = await this.getToolsSchema({
            actions: [tool.name],
        });
        const appName = (_b = (_a = toolSchema[0]) === null || _a === void 0 ? void 0 : _a.appName) === null || _b === void 0 ? void 0 : _b.toLowerCase();
        const connectedAccountId = appName && ((_c = this.connectedAccountIds) === null || _c === void 0 ? void 0 : _c[appName]);
        return JSON.stringify(await this.executeAction({
            action: tool.name,
            params: typeof tool.arguments === "string"
                ? JSON.parse(tool.arguments)
                : tool.arguments,
            entityId: entityId || this.entityId,
            connectedAccountId: connectedAccountId,
        }));
    }
    /**
     * Handle tool calls from AI text generation output
     *
     * @param result The AI text generation output containing tool calls
     * @param entityId Optional entity ID to execute the tools for
     * @returns Promise resolving to array of tool execution results
     */
    async handleToolCall(result, entityId = null) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "handleToolCall",
            file: this.fileName,
            params: { result, entityId },
        });
        const outputs = [];
        if ("tool_calls" in result && Array.isArray(result.tool_calls)) {
            for (const tool_call of result.tool_calls) {
                if (tool_call.name) {
                    outputs.push(await this.executeToolCall(tool_call, entityId));
                }
            }
        }
        return outputs;
    }
}
// Class constants
CloudflareToolSet.FRAMEWORK_NAME = "cloudflare";
CloudflareToolSet.DEFAULT_ENTITY_ID = "default";

class LangchainToolSet extends ComposioToolSet {
    constructor(config = {}) {
        super({
            apiKey: config.apiKey || null,
            baseUrl: config.baseUrl || COMPOSIO_BASE_URL,
            runtime: (config === null || config === void 0 ? void 0 : config.runtime) || LangchainToolSet.FRAMEWORK_NAME,
            entityId: config.entityId || LangchainToolSet.DEFAULT_ENTITY_ID,
            connectedAccountIds: config.connectedAccountIds,
            allowTracing: config.allowTracing || false,
        });
        this.fileName = "js/src/frameworks/langchain.ts";
    }
    _wrapTool(schema, entityId = null) {
        var _a;
        const action = schema["name"];
        const description = schema["description"];
        const appName = (_a = schema["appName"]) === null || _a === void 0 ? void 0 : _a.toLowerCase();
        const func = async (...kwargs) => {
            var _a;
            const connectedAccountId = appName && ((_a = this.connectedAccountIds) === null || _a === void 0 ? void 0 : _a[appName]);
            return JSON.stringify(await this.executeAction({
                action,
                params: kwargs[0],
                entityId: entityId || this.entityId,
                connectedAccountId: connectedAccountId,
            }));
        };
        const parameters = jsonSchemaToModel(schema["parameters"]);
        // @TODO: Add escriiption an other stuff here
        return new tools.DynamicStructuredTool({
            name: action,
            description,
            schema: parameters,
            func: func,
        });
    }
    async getTools(filters = {}, entityId = null) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "getTools",
            file: this.fileName,
            params: { filters, entityId },
        });
        const tools = await this.getToolsSchema(filters, entityId, filters.integrationId);
        return tools.map((tool) => this._wrapTool(tool, entityId || this.entityId));
    }
}
/**
 * Composio toolset for Langchain framework.
 *
 */
LangchainToolSet.FRAMEWORK_NAME = "langchain";
LangchainToolSet.DEFAULT_ENTITY_ID = "default";

class LangGraphToolSet extends LangchainToolSet {
    constructor(config = {}) {
        super({
            apiKey: config.apiKey || null,
            baseUrl: config.baseUrl || COMPOSIO_BASE_URL,
            entityId: config.entityId || LangGraphToolSet.DEFAULT_ENTITY_ID,
            runtime: LangGraphToolSet.FRAMEWORK_NAME,
            connectedAccountIds: config.connectedAccountIds,
            allowTracing: config.allowTracing || false,
        });
    }
}
/**
 * Composio toolset for Langgraph framework.
 *
 */
LangGraphToolSet.FRAMEWORK_NAME = "langGraph";
LangGraphToolSet.DEFAULT_ENTITY_ID = "default";

class OpenAIToolSet extends ComposioToolSet {
    /**
     * Composio toolset for OpenAI framework.
     *
     * Example:
     * ```typescript
     *
     * ```
     */
    constructor(config = {}) {
        super({
            apiKey: config.apiKey || null,
            baseUrl: config.baseUrl || COMPOSIO_BASE_URL,
            runtime: OpenAIToolSet.FRAMEWORK_NAME,
            entityId: config.entityId || OpenAIToolSet.DEFAULT_ENTITY_ID,
            connectedAccountIds: config.connectedAccountIds,
            allowTracing: config.allowTracing || false,
        });
        this.fileName = "js/src/frameworks/openai.ts";
    }
    async getTools(filters, entityId) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "getTools",
            file: this.fileName,
            params: filters,
        });
        const mainActions = await this.getToolsSchema(filters, entityId, filters.integrationId);
        return (mainActions.map((action) => {
            const formattedSchema = {
                name: action.name,
                description: action.description,
                parameters: action.parameters,
            };
            const tool = {
                type: "function",
                function: formattedSchema,
            };
            return tool;
        }) || []);
    }
    async executeToolCall(tool, entityId = null) {
        var _a, _b, _c;
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "executeToolCall",
            file: this.fileName,
            params: { tool, entityId },
        });
        const toolSchema = await this.getToolsSchema({
            actions: [tool.function.name],
        });
        const appName = (_b = (_a = toolSchema[0]) === null || _a === void 0 ? void 0 : _a.appName) === null || _b === void 0 ? void 0 : _b.toLowerCase();
        const connectedAccountId = appName && ((_c = this.connectedAccountIds) === null || _c === void 0 ? void 0 : _c[appName]);
        return JSON.stringify(await this.executeAction({
            action: tool.function.name,
            params: JSON.parse(tool.function.arguments),
            entityId: entityId || this.entityId,
            connectedAccountId: connectedAccountId,
        }));
    }
    async handleToolCall(chatCompletion, entityId = null) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "handleToolCall",
            file: this.fileName,
            params: { chatCompletion, entityId },
        });
        const outputs = [];
        for (const message of chatCompletion.choices) {
            if (message.message.tool_calls) {
                outputs.push(await this.executeToolCall(message.message.tool_calls[0], entityId));
            }
        }
        return outputs;
    }
    async handleAssistantMessage(run, entityId = null) {
        var _a, _b;
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "handleAssistantMessage",
            file: this.fileName,
            params: { run, entityId },
        });
        const tool_calls = ((_b = (_a = run.required_action) === null || _a === void 0 ? void 0 : _a.submit_tool_outputs) === null || _b === void 0 ? void 0 : _b.tool_calls) || [];
        const tool_outputs = await Promise.all(tool_calls.map(async (tool_call) => {
            logger.debug(`Executing tool call with ID: ${tool_call.function.name} and parameters: ${JSON.stringify(tool_call.function.arguments)}`);
            const tool_response = await this.executeToolCall(tool_call, entityId || this.entityId);
            logger.debug(`Received tool response: ${JSON.stringify(tool_response)}`);
            return {
                tool_call_id: tool_call.id,
                output: JSON.stringify(tool_response),
            };
        }));
        return tool_outputs;
    }
    async *waitAndHandleAssistantStreamToolCalls(client, runStream, thread, entityId = null) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "waitAndHandleAssistantStreamToolCalls",
            file: this.fileName,
            params: { client, runStream, thread, entityId },
        });
        let runId = null;
        // Start processing the runStream events
        for await (const event of runStream) {
            yield event; // Yield each event from the stream as it arrives
            if (event.event === "thread.run.created") {
                const { id } = event.data;
                runId = id;
            }
            if (!runId) {
                continue;
            }
            // Handle the 'requires_action' event
            if (event.event === "thread.run.requires_action") {
                const toolOutputs = await this.handleAssistantMessage(event.data, entityId);
                // Submit the tool outputs
                await client.beta.threads.runs.submitToolOutputs(thread.id, runId, {
                    tool_outputs: toolOutputs,
                });
            }
            // Break if the run status becomes inactive
            if ([
                "thread.run.completed",
                "thread.run.failed",
                "thread.run.cancelled",
                "thread.run.expired",
            ].includes(event.event)) {
                break;
            }
        }
        if (!runId) {
            throw new Error("No run ID found");
        }
        // Handle any final actions after the stream ends
        let finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);
        while (["queued", "in_progress", "requires_action"].includes(finalRun.status)) {
            if (finalRun.status === "requires_action") {
                const toolOutputs = await this.handleAssistantMessage(finalRun, entityId);
                // Submit tool outputs
                finalRun = await client.beta.threads.runs.submitToolOutputs(thread.id, runId, {
                    tool_outputs: toolOutputs,
                });
            }
            else {
                // Update the run status
                finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);
                await new Promise((resolve) => setTimeout(resolve, 500)); // Wait before rechecking
            }
        }
    }
    async waitAndHandleAssistantToolCalls(client, run, thread, entityId = null) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "waitAndHandleAssistantToolCalls",
            file: this.fileName,
            params: { client, run, thread, entityId },
        });
        while (["queued", "in_progress", "requires_action"].includes(run.status)) {
            logger.debug(`Current run status: ${run.status}`);
            const tool_outputs = await this.handleAssistantMessage(run, entityId || this.entityId);
            if (run.status === "requires_action") {
                logger.debug(`Submitting tool outputs for run ID: ${run.id} in thread ID: ${thread.id}`);
                run = await client.beta.threads.runs.submitToolOutputs(thread.id, run.id, {
                    tool_outputs: tool_outputs,
                });
            }
            else {
                run = await client.beta.threads.runs.retrieve(thread.id, run.id);
                await new Promise((resolve) => setTimeout(resolve, 500));
            }
        }
        return run;
    }
}
OpenAIToolSet.FRAMEWORK_NAME = "openai";
OpenAIToolSet.DEFAULT_ENTITY_ID = "default";

const ZExecuteToolCallParams = z.z.object({
    actions: z.z.array(z.z.string()).optional(),
    apps: z.z.array(z.z.string()).optional(),
    params: z.z.record(z.z.any()).optional(),
    entityId: z.z.string().optional(),
    useCase: z.z.string().optional(),
    usecaseLimit: z.z.number().optional(),
    connectedAccountId: z.z.string().optional(),
    tags: z.z.array(z.z.string()).optional(),
    filterByAvailableApps: z.z.boolean().optional().default(false),
});
class VercelAIToolSet extends ComposioToolSet {
    constructor(config = {}) {
        super({
            apiKey: config.apiKey || null,
            baseUrl: config.baseUrl || null,
            runtime: "vercel-ai",
            entityId: config.entityId || "default",
            connectedAccountIds: config.connectedAccountIds,
            allowTracing: config.allowTracing || false,
        });
        this.fileName = "js/src/frameworks/vercel.ts";
    }
    generateVercelTool(schema, entityId = null) {
        return ai.tool({
            description: schema.description,
            // @ts-ignore the type are JSONSchemV7. Internally it's resolved
            parameters: ai.jsonSchema(schema.parameters),
            execute: async (params) => {
                return await this.executeToolCall({
                    name: schema.name,
                    arguments: JSON.stringify(params),
                }, entityId || this.entityId);
            },
        });
    }
    // change this implementation
    async getTools(filters, entityId = null) {
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "getTools",
            file: this.fileName,
            params: filters,
        });
        const { apps, tags, useCase, usecaseLimit, filterByAvailableApps, actions, } = ZExecuteToolCallParams.parse(filters);
        const actionsList = await this.getToolsSchema({
            apps,
            actions,
            tags,
            useCase,
            useCaseLimit: usecaseLimit,
            filterByAvailableApps,
        }, entityId, filters.integrationId);
        const tools = {};
        actionsList.forEach((actionSchema) => {
            tools[actionSchema.name] = this.generateVercelTool(actionSchema, entityId);
        });
        return tools;
    }
    async executeToolCall(tool, entityId = null) {
        var _a, _b, _c;
        TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
            method: "executeToolCall",
            file: this.fileName,
            params: { tool, entityId },
        });
        const toolSchema = await this.getToolsSchema({
            actions: [tool.name],
        });
        const appName = (_b = (_a = toolSchema[0]) === null || _a === void 0 ? void 0 : _a.appName) === null || _b === void 0 ? void 0 : _b.toLowerCase();
        const connectedAccountId = appName && ((_c = this.connectedAccountIds) === null || _c === void 0 ? void 0 : _c[appName]);
        return JSON.stringify(await this.executeAction({
            action: tool.name,
            params: typeof tool.arguments === "string"
                ? JSON.parse(tool.arguments)
                : tool.arguments,
            entityId: entityId || this.entityId,
            connectedAccountId: connectedAccountId,
        }));
    }
}

// eslint-disable-next-line @typescript-eslint/no-require-imports
const { APPS, ACTIONS } = require("./constants");

exports.ACTIONS = ACTIONS;
exports.APPS = APPS;
exports.COMPOSIO_SDK_ERROR_CODES = COMPOSIO_SDK_ERROR_CODES;
exports.CloudflareToolSet = CloudflareToolSet;
exports.Composio = Composio;
exports.ComposioError = ComposioError;
exports.ComposioToolSet = ComposioToolSet;
exports.ConnectionRequest = ConnectionRequest;
exports.LangGraphToolSet = LangGraphToolSet;
exports.LangchainToolSet = LangchainToolSet;
exports.OpenAIToolSet = OpenAIToolSet;
exports.VercelAIToolSet = VercelAIToolSet;
