@prass/botpress-native
Version:
A simple and powerful SDK for integrating Botpress Chat API with React Native,
736 lines (733 loc) • 38.7 kB
JavaScript
import { PrepareUrl } from '../utils/prepareUrl.js';
import { handleCreateConversation } from './services/createConversation.js';
import { handleAddParticipant } from './services/addParticipant.js';
import { handleCreateEvent } from './services/createEvent.js';
import { handleCreateMessage } from './services/createMessage.js';
import { handleCreateUser } from './services/createUser.js';
import { handleDeleteConversation } from './services/deleteConversation.js';
import { handleDeleteMessage } from './services/deleteMessage.js';
import { handleDeleteUser } from './services/deleteUser.js';
import { handleGetConversation } from './services/getConversation.js';
import { handleGetEvent } from './services/getEvent.js';
import { handleGetMessage } from './services/getMessage.js';
import { handleGetOrCreateConversation } from './services/getOrCreateConversation.js';
import { handleGetOrCreateUser } from './services/getOrCreateUser.js';
import { handleGetParticipant } from './services/getParticipant.js';
import { handleGetUser } from './services/getUser.js';
import { handleListConversations } from './services/listConversations.js';
import { ListenConversation } from './services/listenConversations.js';
import { handleListMessages } from './services/listMessages.js';
import { handleListParticipants } from './services/listParticipants.js';
import { handleRemoveParticipant } from './services/removeParticipants.js';
import { handleUpdateUser } from './services/updateUser.js';
import AsyncStorage from '@react-native-async-storage/async-storage';
import axiosRetry from 'axios-retry';
import axios from 'axios';
/**
* A third-party SDK for interacting with the Botpress Chat API.
* This class provides a streamlined interface to the Botpress Chat API, enabling developers to integrate Botpress bots into their applications with custom UIs and flows. It abstracts the complexity of direct API calls by offering intuitive methods for all available endpoints, as documented in the official Botpress Chat API reference (https://botpress.com/reference/introduction).
*
* The SDK enhances the raw API experience with features like automatic retry logic, optional caching, and configurable timeouts, reducing the need for manual error handling and boilerplate code. Designed for ease of use, it validates inputs, manages request states, and provides a robust foundation for building chat-based applications.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "user-key", {
* cacheEnabled: true,
* retries: 5,
* timeout: 15000
* });
* ```
*/
class Botpress {
constructor(webhookId, userKey = null, options = {}) {
var _a, _b, _c;
this.errors = {
userNotCreated: "User not created yet or not set.",
invalidWebhookId: "Webhook ID must be a non-empty string.",
};
// ================================= USER HANDLERS ==================================
/**
* Creates a new user in the Botpress Chat API.
* This method facilitates user creation by sending a request to the Botpress API with the specified parameters. It simplifies the process outlined in the official documentation (https://botpress.com/reference/createuser-1) by handling validation, retries, and response parsing under the hood.
*
* @param params - Parameters for creating the user.
* @param params.id - A unique identifier for the new user. If not provided, Botpress auto-generates one. (optional)
* @param params.name - The user’s name (optional).
* @param params.pictureUrl - A URL to the user’s profile picture (optional).
* @param params.profile - A brief description or profile for the user (optional).
* @returns A promise that resolves to a `UserResponse` object containing the created user’s details.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id");
* try {
* const newUser = await botpress.createUser({
* id: "user_123",
* name: "Jane Doe",
* pictureUrl: "https://example.com/jane.jpg",
* profile: "Designer"
* });
* console.log("Created user:", newUser);
* } catch (error) {
* console.error("Failed to create user:", error);
* }
* ```
*/
this.createUser = async ({ id, name, pictureUrl, profile, }) => {
return handleCreateUser.call(this, { id, name, pictureUrl, profile });
};
/**
* Retrieves an existing user or creates a new one in the Botpress Chat API.
* This method simplifies the "Get or Create User" endpoint (https://botpress.com/reference/getorcreateuser-1) by handling the logic to fetch an existing user or create a new one if none exists. It requires a valid user key to be set in the `Botpress` instance beforehand, typically via the constructor or cached configuration.
*
* All parameters are optional, allowing flexibility in defining user details. The response includes the user’s information, such as their ID, name, and profile data, whether retrieved or newly created.
*
* @param params - Parameters for retrieving or creating the user.
* @param params.name - The user’s name (optional).
* @param params.pictureUrl - A URL to the user’s profile picture (optional).
* @param params.profile - A brief description or profile for the user (optional).
* @returns A promise that resolves to a `UserResource` object containing the user’s details.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* const user = await botpress.getOrCreateUser({
* name: "Jane Doe",
* pictureUrl: "https://example.com/jane.jpg",
* profile: "Designer"
* });
* console.log("User details:", user);
* } catch (error) {
* console.error("Failed to get or create user:", error);
* }
* ```
*/
this.getOrCreateUser = async ({ name, pictureUrl, profile, }) => {
return await handleGetOrCreateUser.call(this, {
name,
pictureUrl,
profile,
});
};
/**
* Retrieves details of the currently authenticated user from the Botpress Chat API.
* This method fetches user information using the user key set in the `Botpress` instance, as per the official API endpoint (https://botpress.com/reference/getuser-1). It requires a valid user key, typically provided during instantiation or loaded from cache, and returns details such as the user’s ID, name, and profile data.
*
* When caching is enabled via the `Botpress` configuration, this method first checks for cached user data before making an API request, improving performance for repeated calls. The response is automatically cached for future use if caching is active.
*
* @returns A promise that resolves to a `UserResponse` object containing the authenticated user’s details.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* const user = await botpress.getUser();
* console.log("User details:", user);
* } catch (error) {
* console.error("Failed to get user:", error);
* }
* ```
*/
this.getUser = async () => {
const cacheKey = "botpress_userData";
if (this.config.cacheEnabled) {
try {
const cached = await AsyncStorage.getItem(cacheKey);
if (cached) {
const { value } = JSON.parse(cached);
return value;
}
}
catch (error) {
console.error("Failed to load cached user data:", error);
}
}
const result = await handleGetUser.call(this);
if (this.config.cacheEnabled) {
try {
await AsyncStorage.setItem(cacheKey, JSON.stringify({ value: result }));
}
catch (error) {
console.error("Failed to cache user data:", error);
}
}
return result;
};
/**
* Updates the currently authenticated user’s details in the Botpress Chat API.
* This method modifies the authenticated user’s information by sending a request to the Botpress API, as defined in the official endpoint (https://botpress.com/reference/updateuser-1). It requires a valid user key set in the `Botpress` instance and at least one field to update (name, picture URL, or profile). The response reflects the user’s updated details.
*
* When caching is enabled in the `Botpress` configuration, this method automatically updates the cached user data with the new information, ensuring consistency for subsequent calls.
*
* @param params - Parameters for updating the user’s details.
* @param params.name - The new name for the user (optional).
* @param params.pictureUrl - The new URL to the user’s profile picture (optional).
* @param params.profile - The new profile description for the user (optional).
* @returns A promise that resolves to a `UserResponse` object containing the updated user’s details.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* const updatedUser = await botpress.updateUser({
* name: "John Doe",
* pictureUrl: "https://example.com/john.jpg",
* profile: "Software Engineer"
* });
* console.log("Updated user:", updatedUser);
* } catch (error) {
* console.error("Failed to update user:", error);
* }
* ```
*/
this.updateUser = async ({ name, pictureUrl, profile, }) => {
const cacheKey = "botpress_userData";
const result = await handleUpdateUser.call(this, {
name,
pictureUrl,
profile,
});
if (this.config.cacheEnabled) {
try {
await AsyncStorage.setItem(cacheKey, JSON.stringify({ value: result }));
}
catch (error) {
console.error("Failed to cache user data:", error);
}
}
return result;
};
/**
* Deletes the currently authenticated user from the Botpress.
* This method removes the authenticated user associated with the user key set in the `Botpress` instance, as defined by the official API endpoint (https://botpress.com/reference/deleteuser-1). It requires a valid user key, typically provided during instantiation or loaded from cache. No data is returned upon successful deletion.
*
* If caching is enabled in the `Botpress` configuration, this method clears the cached user data to maintain consistency after deletion.
*
* @returns A promise that resolves to `void` upon successful deletion.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* await botpress.deleteUser();
* console.log("User deleted successfully");
* } catch (error) {
* console.error("Failed to delete user:", error);
* }
* ```
*/
this.deleteUser = async () => {
const cacheKey = "botpress_userData";
await handleDeleteUser.call(this);
if (this.config.cacheEnabled) {
try {
await AsyncStorage.removeItem(cacheKey);
}
catch (error) {
console.error("Failed to remove cached user data:", error);
}
}
};
// ================================== CONVERSATION HANDLERS =================================
/**
* Retrieves a conversation by its ID from the Botpress.
* This method fetches the details of a specific conversation using the provided ID, as defined by the official API endpoint (https://botpress.com/reference/getconversation-1). It requires a valid conversation ID and returns the conversation’s details, such as participants and metadata.
*
* @param params - Parameters for retrieving the conversation.
* @param params.id - The unique identifier of the conversation to fetch.
* @returns A promise that resolves to a `ConversationResource` object containing the conversation’s details.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* const conversation = await botpress.getConversation({ id: "conv_123" });
* console.log("Conversation details:", conversation);
* } catch (error) {
* console.error("Failed to get conversation:", error);
* }
* ```
*/
this.getConversation = async ({ id, }) => {
return await handleGetConversation.call(this, { id });
};
/**
* Deletes a conversation by its ID from the Botpress.
* This method removes a specified conversation from the Botpress system using the provided ID, as defined by the official API endpoint (https://botpress.com/reference/deleteconversation-1). It requires a valid conversation ID and resolves with no data upon successful deletion.
*
* @param params - Parameters for deleting the conversation.
* @param params.id - The unique identifier of the conversation to delete.
* @returns A promise that resolves to `void` upon successful deletion.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* await botpress.deleteConversation({ id: "conv_123" });
* console.log("Conversation deleted successfully");
* } catch (error) {
* console.error("Failed to delete conversation:", error);
* }
* ```
*/
this.deleteConversation = async ({ id, }) => {
return await handleDeleteConversation.call(this, { id });
};
/**
* Creates a new conversation with the specified ID in the Botpress.
* This method initiates a new conversation in the Botpress system using the provided ID, as defined by the official API endpoint (https://botpress.com/reference/createconversation-1). It requires a unique conversation ID and returns the created conversation’s details upon success.
*
* @param params - Parameters for creating the conversation.
* @param params.id - The unique identifier for the new conversation.
* @returns A promise that resolves to a `ConversationResource` object containing the created conversation’s details.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* const conversation = await botpress.createConversation({ id: "conv_123" });
* console.log("Created conversation:", conversation);
* } catch (error) {
* console.error("Failed to create conversation:", error);
* }
* ```
*/
this.createConversation = async ({ id, }) => {
return await handleCreateConversation.call(this, { id });
};
/**
* Retrieves a paginated list of conversations for the authenticated user from the Botpress.
* This method fetches a list of conversations associated with the authenticated user, as defined by the official API endpoint (https://botpress.com/reference/listconversations-1). It supports pagination via an optional `nextToken` parameter and returns conversation details along with pagination metadata.
*
* @param params - Parameters for listing conversations.
* @param params.nextToken - An optional token to fetch the next page of conversations (returned in the previous response’s pagination data).
* @returns A promise that resolves to a `ListConversationsResponse` object containing the list of conversations and pagination information.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* const conversations = await botpress.listConversations({ nextToken: "abc123" });
* console.log("Conversations:", conversations);
* } catch (error) {
* console.error("Failed to list conversations:", error);
* }
* ```
*/
this.listConversations = async ({ nextToken, }) => {
return await handleListConversations.call(this, { nextToken });
};
/**
* Retrieves an existing conversation or creates a new one if it does not exist in the Botpress.
* This method fetches an existing conversation or initiates a new one based on the provided ID, as defined by the official API endpoint (https://botpress.com/reference/getorcreateconversation-1). It requires a unique conversation ID and returns the conversation’s details, whether retrieved or newly created.
*
* @param params - Parameters for retrieving or creating the conversation.
* @param params.id - The unique identifier for the conversation.
* @returns A promise that resolves to a `ConversationResource` object containing the conversation’s details.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* const conversation = await botpress.getOrCreateConversation({
* id: "conv_123",
* autoReconnect: true
* });
* console.log("Conversation details:", conversation);
* } catch (error) {
* console.error("Failed to get or create conversation:", error);
* }
* ```
*/
this.getOrCreateConversation = async ({ id, }) => {
return await handleGetOrCreateConversation.call(this, { id });
};
/**
* Subscribes to real-time events for a conversation using Server-Sent Events (SSE) in the Botpress.
* This method establishes a streaming connection to listen for messages and events in a specified conversation, as defined by the official API endpoint (https://botpress.com/reference/listenconversation). It returns an event listener that emits events for new messages, errors, and connection closure, enabling real-time interaction with the conversation.
*
* The listener supports automatic reconnection if the `autoReconnect` option is enabled, enhancing reliability for long-running streams.
*
* @param params - Parameters for listening to the conversation.
* @param params.id - The unique identifier of the conversation to monitor.
* @param params.autoReconnect - An optional flag to enable automatic reconnection on disconnection (defaults to `false`).
* @returns A promise that resolves to a `ListenConversationType` event listener instance, which emits:
* - `"message"`: Fired when a new message is received, with the message data as the payload.
* - `"error"`: Fired when a stream error occurs, with the error details as the payload.
* - `"close"`: Fired when the stream connection is closed.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* const listener = await botpress.listenConversations({
* id: "conv_123",
* autoReconnect: true
* });
* listener.on("message", (data) => console.log("New message:", data));
* listener.on("error", (err) => console.error("Stream error:", err));
* listener.on("close", () => console.log("Stream closed"));
* // To stop listening: listener.stop();
* } catch (error) {
* console.error("Failed to listen to conversation:", error);
* }
* ```
*/
this.listenConversations = async ({ id, autoReconnect = false, }) => {
const listener = new ListenConversation(this, { id, autoReconnect });
listener.start();
return listener;
};
/**
* Adds a user as a participant to a specified conversation in the Botpress.
* This method adds a user to an existing conversation using the provided conversation and user IDs, as defined by the official API endpoint (https://botpress.com/reference/addparticipant-1). It requires a valid user key set in the `Botpress` instance and returns the participant’s details upon successful addition.
*
* @param params - Parameters for adding a participant.
* @param params.conversationId - The unique identifier of the conversation to which the participant will be added.
* @param params.userId - The unique identifier of the user to add as a participant.
* @returns A promise that resolves to an `ParticipantResource` object containing the added participant’s details.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* const participant = await botpress.addParticipant({
* conversationId: "conv_123",
* userId: "user_456"
* });
* console.log("Added participant:", participant);
* } catch (error) {
* console.error("Failed to add participant:", error);
* }
* ```
*/
this.addParticipant = async ({ conversationId, userId, }) => {
return handleAddParticipant.call(this, { conversationId, userId });
};
/**
* Retrieves a paginated list of participants for a specified conversation in the Botpress.
* This method fetches all participants in a given conversation, as defined by the official API endpoint (https://botpress.com/reference/listparticipants-1). It requires a valid user key set in the `Botpress` instance and a conversation ID, returning participant details along with pagination metadata. The optional `nextToken` enables fetching subsequent pages of results.
*
* @param params - Parameters for listing participants.
* @param params.conversationId - The unique identifier of the conversation to fetch participants from.
* @param params.nextToken - An optional token to fetch the next page of participants.
* @returns A promise that resolves to a `ListParticipantsResponse` object containing an array of participants and pagination metadata.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* const participants = await botpress.listParticipants({
* conversationId: "conv_123",
* nextToken: "xyz789" // Optional, for pagination
* });
* console.log("Conversation participants:", participants);
* } catch (error) {
* console.error("Failed to list participants:", error);
* }
* ```
*/
this.listParticipants = async ({ conversationId, nextToken, }) => {
return handleListParticipants.call(this, { conversationId, nextToken });
};
/**
* Removes a participant from a specified conversation in the Botpress.
* This method removes a user from a conversation using the provided conversation and user IDs, as defined by the official API endpoint (https://botpress.com/reference/removeparticipant-1). It requires a valid user key set in the `Botpress` instance and resolves with no data upon successful removal.
*
* @param params - Parameters for removing a participant.
* @param params.conversationId - The unique identifier of the conversation from which to remove the participant.
* @param params.userId - The unique identifier of the user to remove from the conversation.
* @returns A promise that resolves to `void` upon successful removal.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* await botpress.removeParticipant({
* conversationId: "conv_123",
* userId: "user_456"
* });
* console.log("Participant removed successfully");
* } catch (error) {
* console.error("Failed to remove participant:", error);
* }
* ```
*/
this.removeParticipant = async ({ conversationId, userId, }) => {
return handleRemoveParticipant.call(this, {
conversationId,
userId,
});
};
/**
* Retrieves details of a specific participant in a conversation from the Botpress.
* This method fetches information about a participant using the specified conversation and user IDs, as defined by the official API endpoint (https://botpress.com/reference/getparticipant-1). It requires a valid user key set in the `Botpress` instance and returns the participant’s details, such as their ID, name, and profile information.
*
*
* @param params - Parameters for retrieving the participant.
* @param params.conversationId - The unique identifier of the conversation containing the participant.
* @param params.userId - The unique identifier of the participant to retrieve.
* @returns A promise that resolves to an `ParticipantResource` object containing the participant’s details.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* const participant = await botpress.getParticipant({
* conversationId: "conv_123",
* userId: "user_456"
* });
* console.log("Participant details:", participant);
* } catch (error) {
* console.error("Failed to get participant:", error);
* }
* ```
*/
this.getParticipant = async ({ conversationId, userId, }) => {
return await handleGetParticipant.call(this, { conversationId, userId });
};
// ===================================== MESSAGE HANDLERS ==========================================
/**
* Retrieves a paginated list of messages for a specified conversation from the Botpress.
* This method fetches messages within a conversation using the provided conversation ID, as defined by the official API endpoint (https://botpress.com/reference/listmessages-1). It supports pagination via an optional `nextToken` parameter and returns an array of messages along with metadata.
*
* @param params - Parameters for listing messages.
* @param params.conversationId - The unique identifier of the conversation to fetch messages from.
* @param params.nextToken - An optional token to fetch the next page of messages.
* @returns A promise that resolves to a `ListMessagesResponse` object containing an array of messages and pagination metadata.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* const messages = await botpress.listMessages({
* conversationId: "conv_123",
* nextToken: "msg789" // Optional, for pagination
* });
* console.log("Conversation messages:", messages);
* } catch (error) {
* console.error("Failed to list messages:", error);
* }
* ```
*/
this.listMessages = async ({ conversationId, nextToken, }) => {
return await handleListMessages.call(this, { conversationId, nextToken });
};
/**
* Retrieves details of a specific message from the Botpress.
* This method fetches information about a message using the provided message ID, as defined by the official API endpoint (https://botpress.com/reference/getmessage-1). It requires a valid user key set in the `Botpress` instance and returns the message’s details, such as content, sender, and timestamps.
*
* @param params - Parameters for retrieving the message.
* @param params.id - The unique identifier of the message to fetch.
* @returns A promise that resolves to a `MessageResource` object containing the message’s details.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* const message = await botpress.getMessage({ id: "msg_123" });
* console.log("Message details:", message);
* } catch (error) {
* console.error("Failed to get message:", error);
* }
* ```
*/
this.getMessage = async ({ id }) => {
return await handleGetMessage.call(this, { id });
};
/**
* Deletes a specific message from the Botpress.
* This method removes a message identified by its ID from the Botpress system, as defined by the official API endpoint (https://botpress.com/reference/deletemessage-1). It requires a valid user key set in the `Botpress` instance and resolves with no data upon successful deletion.
*
* @param params - Parameters for deleting the message.
* @param params.id - The unique identifier of the message to delete.
* @returns A promise that resolves to `void` upon successful deletion.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* await botpress.deleteMessage({ id: "msg_123" });
* console.log("Message deleted successfully");
* } catch (error) {
* console.error("Failed to delete message:", error);
* }
* ```
*/
this.deleteMessage = async ({ id }) => {
return await handleDeleteMessage.call(this, { id });
};
/**
* Creates a new message in a specified conversation in the Botpress.
* This method sends a new message to a conversation using the provided conversation ID and payload, as defined by the official API endpoint (https://botpress.com/reference/createmessage-1). It requires a valid user key set in the `Botpress` instance and returns the created message’s details, such as its ID, content, and timestamps.
*
* @param params - Parameters for creating the message.
* @param params.conversationId - The unique identifier of the conversation to send the message to.
* @param params.payload - The message content and metadata (e.g., `{ type: "text", text: "Hello" }`).
* @returns A promise that resolves to a `MessageRaw` object containing the created message’s details.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* const message = await botpress.createMessage({
* conversationId: "conv_123",
* payload: { type: "text", text: "Hello, world!" }
* });
* console.log("Message created:", message);
* } catch (error) {
* console.error("Failed to create message:", error);
* }
* ```
*/
this.createMessage = async ({ conversationId, payload, }) => {
return await handleCreateMessage.call(this, { conversationId, payload });
};
// ===================================== EVENT HANDLERS ==========================================
/**
* Retrieves details of a specific event from the Botpress.
* This method fetches information about an event using the provided event ID, as defined by the official API endpoint (https://botpress.com/reference/getevent-1). It requires a valid user key set in the `Botpress` instance and returns the event’s details, such as its ID, creation timestamp, payload, conversation ID, and user ID.
*
* @param params - Parameters for retrieving the event.
* @param params.id - The unique identifier of the event to fetch.
* @returns A promise that resolves to an `EventResource` object containing the event’s details.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* const event = await botpress.getEvent({ id: "evt_123" });
* console.log("Event details:", event);
* } catch (error) {
* console.error("Failed to get event:", error);
* }
* ```
*/
this.getEvent = async ({ id }) => {
return await handleGetEvent.call(this, { id });
};
/**
* Creates a new event.
*
* https://botpress.com/reference/createevent-1
*
* @param params - Parameters for creating the event.
* @param params.conversationId - The unique identifier of the conversation for the event.
* @param params.payload - The event payload.
* @returns A promise that resolves to an `EventResource` object containing the created event’s details.
*
* @example
* ```typescript
* const botpress = new Botpress("your-webhook-id", "your-user-key");
* try {
* const event = await botpress.createEvent({
* conversationId: "conv_123",
* payload: { "key": "value", "key2": "value2" }
* });
* console.log("Created event:", event);
* } catch (error) {
* console.error("Failed to create event:", error);
* }
* ```
*/
this.createEvent = async ({ conversationId, payload, }) => {
return await handleCreateEvent.call(this, { conversationId, payload });
};
if (!webhookId ||
typeof webhookId !== "string" ||
webhookId.trim() === "") {
throw new Error(this.errors.invalidWebhookId);
}
this.webhookId = webhookId;
this.userKey = userKey;
this.config = {
cacheEnabled: (_a = options.cacheEnabled) !== null && _a !== void 0 ? _a : false,
timeout: (_b = options.timeout) !== null && _b !== void 0 ? _b : 10000,
retries: (_c = options.retries) !== null && _c !== void 0 ? _c : 3,
};
this.ChatApiOrigin =
process.env.CHAT_API_ORIGIN || "https://chat.botpress.cloud/";
this.ChatApiBaseUrl = new PrepareUrl([this.ChatApiOrigin, this.webhookId]);
this.axiosInstance = axios.create();
axiosRetry(this.axiosInstance, {
retries: this.config.retries,
retryDelay: (retryCount) => {
return Math.pow(2, retryCount) * 100;
},
retryCondition: (error) => Boolean(axiosRetry.isNetworkOrIdempotentRequestError(error) ||
(error.response && error.response.status >= 500)),
});
this.loadCachedUserKey();
}
// ================================ CACHE HANDLERS =================================
async loadCachedUserKey() {
if (this.config.cacheEnabled && !this.userKey) {
try {
const cached = await AsyncStorage.getItem("botpress_userKey");
if (cached) {
const { value } = JSON.parse(cached);
this.userKey = value;
return value;
}
}
catch (error) {
console.error("Failed to load cached user key:", error);
}
}
return this.userKey;
}
async cacheUserKey(userKey) {
if (this.config.cacheEnabled && (userKey || this.userKey)) {
try {
await AsyncStorage.setItem("botpress_userKey", JSON.stringify({
value: userKey || this.userKey,
}));
}
catch (error) {
console.error("Failed to cache userKey:", error);
}
}
}
async clearCache() {
try {
await Promise.all([
AsyncStorage.removeItem("botpress_userKey"),
AsyncStorage.removeItem("botpress_userData"),
]);
}
catch (error) {
console.error("Failed to clear cache:", error);
}
}
// ================================= GETTERS ==================================
getUserKey() {
return this.userKey;
}
getWebhookId() {
return this.webhookId;
}
getChatApiBaseUrl() {
return this.ChatApiBaseUrl;
}
getErrors() {
return { ...this.errors };
}
getConfig() {
return this.config;
}
// ================================= SETTERS ==================================
/**
* Sets the user key for the Botpress instance.
* @param key - The user key to set
*/
setUserKey(key) {
if (!key || typeof key !== "string" || key.trim() === "") {
throw new Error("User key must be a non-empty string");
}
this.userKey = key;
this.cacheUserKey(key);
}
}
export { Botpress };
//# sourceMappingURL=Botpress.js.map