// src/mem0.ts
import axios from "axios";
// src/telemetry.browser.ts
var version = "1.0.20";
var MEM0_TELEMETRY = process.env.MEM0_TELEMETRY !== "false";
var POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX";
var POSTHOG_HOST = "https://us.i.posthog.com";
async function generateHash(input) {
const msgBuffer = new TextEncoder().encode(input);
const hashBuffer = await window.crypto.subtle.digest("SHA-256", msgBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
}
var BrowserTelemetry = class {
constructor(projectApiKey, host) {
this.client = null;
if (MEM0_TELEMETRY) {
this.initializeClient(projectApiKey, host);
}
}
async initializeClient(projectApiKey, host) {
try {
const posthog = await import("posthog-js").catch(() => null);
if (posthog) {
posthog.init(projectApiKey, { api_host: host });
this.client = posthog;
}
} catch (error) {
this.client = null;
}
}
async captureEvent(distinctId, eventName, properties = {}) {
if (!this.client || !MEM0_TELEMETRY) return;
const eventProperties = {
client_source: "browser",
client_version: getVersion(),
browser: window.navigator.userAgent,
...properties
};
try {
this.client.capture(
eventName,
eventProperties
);
} catch (error) {
}
}
async shutdown() {
}
};
function getVersion() {
return version;
}
var telemetry = new BrowserTelemetry(
POSTHOG_API_KEY,
POSTHOG_HOST
);
async function captureClientEvent(eventName, instance, additionalData = {}) {
const eventData = {
function: `${instance.constructor.name}`,
...additionalData
};
await telemetry.captureEvent(
instance.telemetryId,
`client.${eventName}`,
eventData
);
}
// src/mem0.ts
var APIError = class extends Error {
constructor(message) {
super(message);
this.name = "APIError";
}
};
var MemoryClient = class {
_validateApiKey() {
if (!this.apiKey) {
throw new Error("Mem0 API key is required");
}
if (typeof this.apiKey !== "string") {
throw new Error("Mem0 API key must be a string");
}
if (this.apiKey.trim() === "") {
throw new Error("Mem0 API key cannot be empty");
}
}
_validateOrgProject() {
if (this.organizationName === null && this.projectName !== null || this.organizationName !== null && this.projectName === null) {
console.warn("Warning: Both organizationName and projectName must be provided together when using either. This will be removedfrom the version 1.0.40. Note that organizationName/projectName are being deprecated in favor of organizationId/projectId.");
}
if (this.organizationId === null && this.projectId !== null || this.organizationId !== null && this.projectId === null) {
console.warn("Warning: Both organizationId and projectId must be provided together when using either. This will be removedfrom the version 1.0.40.");
}
}
constructor(options) {
this.apiKey = options.apiKey;
this.host = options.host || "https://api.mem0.ai";
this.organizationName = options.organizationName || null;
this.projectName = options.projectName || null;
this.organizationId = options.organizationId || null;
this.projectId = options.projectId || null;
this.headers = {
"Authorization": `Token ${this.apiKey}`,
"Content-Type": "application/json"
};
this.client = axios.create({
baseURL: this.host,
headers: { Authorization: `Token ${this.apiKey}` },
timeout: 6e4
});
this._validateApiKey();
this._validateOrgProject();
this.telemetryId = "";
this._initializeClient();
}
async _initializeClient() {
try {
this.telemetryId = await generateHash(this.apiKey);
await captureClientEvent("init", this);
this.add = this.wrapMethod("add", this.add);
this.get = this.wrapMethod("get", this.get);
this.getAll = this.wrapMethod("get_all", this.getAll);
this.search = this.wrapMethod("search", this.search);
this.delete = this.wrapMethod("delete", this.delete);
this.deleteAll = this.wrapMethod("delete_all", this.deleteAll);
this.history = this.wrapMethod("history", this.history);
this.users = this.wrapMethod("users", this.users);
this.deleteUser = this.wrapMethod("delete_user", this.deleteUser);
this.deleteUsers = this.wrapMethod("delete_users", this.deleteUsers);
this.batchUpdate = this.wrapMethod("batch_update", this.batchUpdate);
this.batchDelete = this.wrapMethod("batch_delete", this.batchDelete);
this.getProject = this.wrapMethod("get_project", this.getProject);
this.updateProject = this.wrapMethod("update_project", this.updateProject);
this.getWebhooks = this.wrapMethod("get_webhook", this.getWebhooks);
this.createWebhook = this.wrapMethod("create_webhook", this.createWebhook);
this.updateWebhook = this.wrapMethod("update_webhook", this.updateWebhook);
this.deleteWebhook = this.wrapMethod("delete_webhook", this.deleteWebhook);
} catch (error) {
console.error("Failed to initialize client:", error);
}
}
wrapMethod(methodName, method) {
return async function(...args) {
await captureClientEvent(methodName, this);
return method.apply(this, args);
}.bind(this);
}
async _fetchWithErrorHandling(url, options) {
const response = await fetch(url, options);
if (!response.ok) {
const errorData = await response.text();
throw new APIError(`API request failed: ${errorData}`);
}
const jsonResponse = await response.json();
return jsonResponse;
}
_preparePayload(messages, options) {
const payload = {};
if (typeof messages === "string") {
payload.messages = [{ role: "user", content: messages }];
} else if (Array.isArray(messages)) {
payload.messages = messages;
}
return { ...payload, ...options };
}
_prepareParams(options) {
return Object.fromEntries(Object.entries(options).filter(([_, v]) => v != null));
}
async add(messages, options = {}) {
this._validateOrgProject();
if (this.organizationName != null && this.projectName != null) {
options.org_name = this.organizationName;
options.project_name = this.projectName;
}
if (this.organizationId != null && this.projectId != null) {
options.org_id = this.organizationId;
options.project_id = this.projectId;
if (options.org_name) delete options.org_name;
if (options.project_name) delete options.project_name;
}
const payload = this._preparePayload(messages, options);
const response = await this._fetchWithErrorHandling(`${this.host}/v1/memories/`, {
method: "POST",
headers: this.headers,
body: JSON.stringify(payload)
});
return response;
}
async update(memoryId, message) {
this._validateOrgProject();
const payload = {
text: message
};
const response = await this._fetchWithErrorHandling(`${this.host}/v1/memories/${memoryId}/`, {
method: "PUT",
headers: this.headers,
body: JSON.stringify(payload)
});
return response;
}
async get(memoryId) {
return this._fetchWithErrorHandling(`${this.host}/v1/memories/${memoryId}/`, {
headers: this.headers
});
}
async getAll(options) {
this._validateOrgProject();
const { api_version, page, page_size, ...otherOptions } = options;
if (this.organizationName != null && this.projectName != null) {
otherOptions.org_name = this.organizationName;
otherOptions.project_name = this.projectName;
}
let appendedParams = "";
let paginated_response = false;
if (page && page_size) {
appendedParams += `page=${page}&page_size=${page_size}`;
paginated_response = true;
}
if (this.organizationId != null && this.projectId != null) {
otherOptions.org_id = this.organizationId;
otherOptions.project_id = this.projectId;
if (otherOptions.org_name) delete otherOptions.org_name;
if (otherOptions.project_name) delete otherOptions.project_name;
}
if (api_version === "v2") {
let url = paginated_response ? `${this.host}/v2/memories/?${appendedParams}` : `${this.host}/v2/memories/`;
return this._fetchWithErrorHandling(url, {
method: "POST",
headers: this.headers,
body: JSON.stringify(otherOptions)
});
} else {
const params = new URLSearchParams(this._prepareParams(otherOptions));
const url = paginated_response ? `${this.host}/v1/memories/?${params}&${appendedParams}` : `${this.host}/v1/memories/?${params}`;
return this._fetchWithErrorHandling(url, {
headers: this.headers
});
}
}
async search(query, options) {
this._validateOrgProject();
const { api_version, ...otherOptions } = options;
const payload = { query, ...otherOptions };
if (this.organizationName != null && this.projectName != null) {
payload.org_name = this.organizationName;
payload.project_name = this.projectName;
}
if (this.organizationId != null && this.projectId != null) {
payload.org_id = this.organizationId;
payload.project_id = this.projectId;
if (payload.org_name) delete payload.org_name;
if (payload.project_name) delete payload.project_name;
}
const endpoint = api_version === "v2" ? "/v2/memories/search/" : "/v1/memories/search/";
const response = await this._fetchWithErrorHandling(`${this.host}${endpoint}`, {
method: "POST",
headers: this.headers,
body: JSON.stringify(payload)
});
return response;
}
async delete(memoryId) {
return this._fetchWithErrorHandling(`${this.host}/v1/memories/${memoryId}/`, {
method: "DELETE",
headers: this.headers
});
}
async deleteAll(options = {}) {
this._validateOrgProject();
if (this.organizationName != null && this.projectName != null) {
options.org_name = this.organizationName;
options.project_name = this.projectName;
}
if (this.organizationId != null && this.projectId != null) {
options.org_id = this.organizationId;
options.project_id = this.projectId;
if (options.org_name) delete options.org_name;
if (options.project_name) delete options.project_name;
}
const params = new URLSearchParams(this._prepareParams(options));
const response = await this._fetchWithErrorHandling(`${this.host}/v1/memories/?${params}`, {
method: "DELETE",
headers: this.headers
});
return response;
}
async history(memoryId) {
const response = await this._fetchWithErrorHandling(`${this.host}/v1/memories/${memoryId}/history/`, {
headers: this.headers
});
return response;
}
async users() {
this._validateOrgProject();
const options = {};
if (this.organizationName != null && this.projectName != null) {
options.org_name = this.organizationName;
options.project_name = this.projectName;
}
if (this.organizationId != null && this.projectId != null) {
options.org_id = this.organizationId;
options.project_id = this.projectId;
if (options.org_name) delete options.org_name;
if (options.project_name) delete options.project_name;
}
const params = new URLSearchParams(options);
const response = await this._fetchWithErrorHandling(`${this.host}/v1/entities/?${params}`, {
headers: this.headers
});
return response;
}
async deleteUser(entityId, entity = { type: "user" }) {
const response = await this._fetchWithErrorHandling(`${this.host}/v1/entities/${entity.type}/${entityId}/`, {
method: "DELETE",
headers: this.headers
});
return response;
}
async deleteUsers() {
this._validateOrgProject();
const entities = await this.users();
for (const entity of entities.results) {
let options = {};
if (this.organizationName != null && this.projectName != null) {
options.org_name = this.organizationName;
options.project_name = this.projectName;
}
if (this.organizationId != null && this.projectId != null) {
options.org_id = this.organizationId;
options.project_id = this.projectId;
if (options.org_name) delete options.org_name;
if (options.project_name) delete options.project_name;
}
await this.client.delete(`/v1/entities/${entity.type}/${entity.id}/`, { params: options });
}
return { message: "All users, agents, and sessions deleted." };
}
async batchUpdate(memories) {
const memoriesBody = memories.map((memory) => ({
memory_id: memory.memoryId,
text: memory.text
}));
const response = await this._fetchWithErrorHandling(`${this.host}/v1/batch/`, {
method: "PUT",
headers: this.headers,
body: JSON.stringify({ memories: memoriesBody })
});
return response;
}
async batchDelete(memories) {
const memoriesBody = memories.map((memory) => ({
memory_id: memory
}));
const response = await this._fetchWithErrorHandling(`${this.host}/v1/batch/`, {
method: "DELETE",
headers: this.headers,
body: JSON.stringify({ memories: memoriesBody })
});
return response;
}
async getProject(options) {
this._validateOrgProject();
const { fields } = options;
if (!(this.organizationId && this.projectId)) {
throw new Error("organizationId and projectId must be set to access instructions or categories");
}
const params = new URLSearchParams();
fields == null ? void 0 : fields.forEach((field) => params.append("fields", field));
const response = await this._fetchWithErrorHandling(
`${this.host}/api/v1/orgs/organizations/${this.organizationId}/projects/${this.projectId}/?${params.toString()}`,
{
headers: this.headers
}
);
return response;
}
async updateProject(prompts) {
this._validateOrgProject();
if (!(this.organizationId && this.projectId)) {
throw new Error("organizationId and projectId must be set to update instructions or categories");
}
const response = await this._fetchWithErrorHandling(
`${this.host}/api/v1/orgs/organizations/${this.organizationId}/projects/${this.projectId}/`,
{
method: "PATCH",
headers: this.headers,
body: JSON.stringify(prompts)
}
);
return response;
}
// WebHooks
async getWebhooks(data) {
const project_id = (data == null ? void 0 : data.projectId) || this.projectId;
const response = await this._fetchWithErrorHandling(`${this.host}/api/v1/webhooks/projects/${project_id}/`, {
headers: this.headers
});
return response;
}
async createWebhook(webhook) {
const response = await this._fetchWithErrorHandling(`${this.host}/api/v1/webhooks/projects/${this.projectId}/`, {
method: "POST",
headers: this.headers,
body: JSON.stringify(webhook)
});
return response;
}
async updateWebhook(webhook) {
const project_id = webhook.projectId || this.projectId;
const response = await this._fetchWithErrorHandling(`${this.host}/api/v1/webhooks/${webhook.webhookId}/`, {
method: "PUT",
headers: this.headers,
body: JSON.stringify({
...webhook,
projectId: project_id
})
});
return response;
}
async deleteWebhook(data) {
const webhook_id = data.webhookId || data;
const response = await this._fetchWithErrorHandling(`${this.host}/api/v1/webhooks/${webhook_id}/`, {
method: "DELETE",
headers: this.headers
});
return response;
}
};
// src/index.ts
var index_default = MemoryClient;
export {
MemoryClient,
captureClientEvent,
index_default as default,
generateHash,
telemetry
};
//# sourceMappingURL=index.mjs.map