@solufy/evolution-sdk
Version:
Unofficial SDK for the Evolution Whatsapp API v2
1,109 lines (1,075 loc) • 35.9 kB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
// src/index.ts
var index_exports = {};
__export(index_exports, {
ChatId: () => ChatId,
EvolutionApiError: () => EvolutionApiError,
EvolutionClient: () => EvolutionClient,
GroupJid: () => GroupJid,
Jid: () => Jid,
MessageId: () => MessageId,
phoneNumberFromJid: () => phoneNumberFromJid
});
module.exports = __toCommonJS(index_exports);
// src/api/errors.ts
var import_zod = require("zod");
var EvolutionApiError = class _EvolutionApiError extends Error {
constructor(message, cause) {
const error = getErrorMessage(cause);
super(message, error ? void 0 : { cause });
this.name = _EvolutionApiError.name;
this.message = error ?? message;
}
};
var ErrorMessages = [
ErrorMessage(
import_zod.z.object({
message: import_zod.z.array(
import_zod.z.object({
exists: import_zod.z.literal(false),
jid: import_zod.z.string(),
number: import_zod.z.string()
})
)
}),
"Provided number is not a valid WhatsApp number"
),
ErrorMessage(
import_zod.z.object({
message: import_zod.z.array(import_zod.z.string().includes("Media upload failed on all hosts"))
}),
"Media upload failed on all hosts"
),
ErrorMessage(
import_zod.z.object({
message: import_zod.z.array(import_zod.z.string().includes("AxiosError"))
}),
(response) => response.message[0]
),
ErrorMessage(
import_zod.z.object({
message: import_zod.z.array(import_zod.z.string().includes("No session"))
}),
"No session found, try restarting your instance"
),
ErrorMessage(
import_zod.z.object({
message: import_zod.z.array(import_zod.z.string().includes("AggregateError"))
}),
"AggregateError"
)
];
function getErrorMessage(response) {
const error = ErrorMessages.find(
(message) => message.schema.safeParse(response).success
);
return error ? typeof error.message === "string" ? error.message : (
// biome-ignore lint/suspicious/noExplicitAny: Generic
error.message(response)
) : void 0;
}
function ErrorMessage(schema, message) {
return { schema, message };
}
// src/api/service.ts
var ApiService = class {
constructor(options) {
this.options = options;
}
async get(path, options = {}) {
return this.request(path, { ...options, method: "GET" });
}
async post(path, options = {}) {
return this.request(path, { ...options, method: "POST" });
}
async put(path, options = {}) {
return this.request(path, { ...options, method: "PUT" });
}
async patch(path, options = {}) {
return this.request(path, { ...options, method: "PATCH" });
}
async delete(path, options = {}) {
return this.request(path, { ...options, method: "DELETE" });
}
async request(path, options = {}) {
const { init, params } = this.makeInit(options);
const url = new URL(
`/${path}/${this.options.instance}/?${params}`,
this.options.serverUrl
);
const response = await fetch(url, init);
const data = await response.json();
if (!response.ok || "error" in data) {
throw new EvolutionApiError(
`${this.options.instance} ${data.error || "Unknown Error"}`,
data.response
);
}
return data;
}
makeInit(options) {
const { params: _, headers, body, ...rest } = options;
const paramsInit = options.params && Object.entries(options.params).filter(([, value]) => Boolean(value)).map(([key, value]) => [key, String(value)]);
const params = new URLSearchParams(paramsInit);
const init = {
...rest,
headers: { ...headers || {}, apikey: this.options.token }
};
if (body) {
init.headers["Content-Type"] = body instanceof FormData ? "multipart/form-data" : "application/json";
init.body = body instanceof FormData ? body : JSON.stringify(body);
}
return { init, params };
}
};
// src/api/routes.ts
var Routes = {
Message: {
SendText: "message/sendText",
SendMedia: "message/sendMedia",
SendVoice: "message/sendWhatsAppAudio",
SendSticker: "message/sendSticker",
SendLocation: "message/sendLocation",
SendContact: "message/sendContact",
SendPoll: "message/sendPoll"
},
Chats: {
Check: "chat/whatsappNumbers",
FindAll: "chat/findChats",
SendPresence: "chat/sendPresence"
},
Groups: {
FindAll: "group/fetchAllGroups",
FindByJid: "group/findGroupInfos",
FindByInviteCode: "group/inviteInfo"
}
};
// src/modules/chats/schemas/check.ts
var import_libphonenumber_js2 = require("libphonenumber-js");
var import_zod3 = require("zod");
// src/schemas/common.ts
var import_libphonenumber_js = require("libphonenumber-js");
var import_zod2 = require("zod");
var PhoneNumberSchema = import_zod2.z.custom((value) => (0, import_libphonenumber_js.isValidPhoneNumber)(value), "Invalid phone number").transform((phoneNumber) => (0, import_libphonenumber_js.parsePhoneNumber)(phoneNumber).number);
var JidSchema = import_zod2.z.string().endsWith(
"@s.whatsapp.net",
"Invalid remote JID, should end with @s.whatsapp.net"
);
var GroupJidSchema = import_zod2.z.string().endsWith(
"@g.us",
"Invalid group JID, should end with @g.us"
);
var GroupInviteCodeSchema = import_zod2.z.string().length(22).regex(
/^[a-zA-Z0-9]{22}$/,
"Invalid group invite code"
);
var ApiNumberSchema = import_zod2.z.union([
PhoneNumberSchema,
JidSchema,
GroupJidSchema
]);
var mediaSchema = import_zod2.z.union([import_zod2.z.string().url(), import_zod2.z.string().base64()]);
// src/types/tags.ts
var Jid = (jid) => jid;
var GroupJid = (jid) => jid;
var MessageId = (id) => id;
var ChatId = (id) => id;
// src/modules/chats/schemas/check.ts
var CheckOptionsSchema = import_zod3.z.array(PhoneNumberSchema);
var CheckBodySchema = CheckOptionsSchema.transform((data) => ({
numbers: Array.isArray(data) ? data : [data]
}));
var CheckResponseSchema = import_zod3.z.array(
import_zod3.z.object({
exists: import_zod3.z.boolean(),
jid: import_zod3.z.string(),
number: import_zod3.z.string()
})
).transform(
(numbers) => numbers.map((number) => ({
exists: number.exists,
jid: Jid(number.jid),
number: (0, import_libphonenumber_js2.parsePhoneNumber)(number.number).number
}))
);
// src/modules/chats/schemas/find-all.ts
var import_zod4 = require("zod");
// src/utils/phone-numer-from-jid.ts
var import_libphonenumber_js3 = require("libphonenumber-js");
function phoneNumberFromJid(jid) {
return (0, import_libphonenumber_js3.parsePhoneNumber)(`+${jid.split("@")[0]}`).number;
}
// src/modules/chats/schemas/find-all.ts
var FindAllChatsResponseSchema = import_zod4.z.array(
import_zod4.z.object({
id: import_zod4.z.string(),
remoteJid: import_zod4.z.string(),
name: import_zod4.z.string().nullish(),
labels: import_zod4.z.array(import_zod4.z.string()).nullish(),
createdAt: import_zod4.z.coerce.date(),
updatedAt: import_zod4.z.coerce.date(),
pushName: import_zod4.z.string().nullish(),
profilePicUrl: import_zod4.z.string().url().nullish()
})
).transform(
(chats) => chats.map((chat) => ({
id: ChatId(chat.id),
jid: chat.remoteJid.endsWith("@g.us") ? GroupJid(chat.remoteJid) : Jid(chat.remoteJid),
phoneNumber: phoneNumberFromJid(chat.remoteJid),
name: chat.name || void 0,
labels: chat.labels || void 0,
createdAt: chat.createdAt,
updatedAt: chat.updatedAt,
pushName: chat.pushName || void 0,
pictureUrl: chat.profilePicUrl || void 0
}))
);
// src/modules/chats/schemas/presence.ts
var import_zod5 = require("zod");
var PresenceOptionsSchema = import_zod5.z.object({
/**
* Chat number or JID to receve the presence
*/
number: ApiNumberSchema,
/**
* Duration of the presence in millisseconds
*/
duration: import_zod5.z.number(),
/**
* Presence state
* - `composing`: typing a message
* - `recording`: recording an audio
*/
presence: import_zod5.z.enum(["composing", "recording"]),
/**
* Whether to wait until the presence is finished (duration)
*/
waitUntilFinish: import_zod5.z.boolean().optional()
});
var PresenceBodySchema = PresenceOptionsSchema.transform(
({ waitUntilFinish, duration, ...data }) => ({ ...data, delay: duration })
);
// src/modules/chats/index.ts
var ChatsModule = class {
constructor(api) {
this.api = api;
}
/**
* Checks if a number has WhatsApp
* @param numbers - Number(s) (with country code) to check
*/
async check(...numbers) {
const body = CheckBodySchema.parse(numbers.flat());
const response = await this.api.post(Routes.Chats.Check, { body });
return CheckResponseSchema.parse(response);
}
/**
* Gets all chats
*/
async findAll() {
const response = await this.api.post(Routes.Chats.FindAll);
return FindAllChatsResponseSchema.parse(response);
}
/**
* Sends a presence to a certain chat
* @param options - Presence options
*/
async sendPresence(options) {
const body = PresenceBodySchema.parse(options);
if (options.waitUntilFinish) {
await this.api.post(Routes.Chats.SendPresence, { body });
} else {
this.api.post(Routes.Chats.SendPresence, { body });
}
}
};
// src/modules/groups/index.ts
var import_zod9 = require("zod");
// src/modules/groups/schemas/find-all.ts
var import_zod7 = require("zod");
// src/modules/groups/schemas/common.ts
var import_zod6 = require("zod");
var GroupResponseSchema = import_zod6.z.object({
id: import_zod6.z.string(),
subject: import_zod6.z.string(),
subjectOwner: import_zod6.z.string(),
subjectTime: import_zod6.z.coerce.date(),
pictureUrl: import_zod6.z.string().url().nullish(),
size: import_zod6.z.number(),
creation: import_zod6.z.coerce.date(),
owner: import_zod6.z.string(),
restrict: import_zod6.z.boolean(),
announce: import_zod6.z.boolean()
});
var ParticipantResponseSchema = import_zod6.z.object({
id: import_zod6.z.string(),
admin: import_zod6.z.enum(["admin", "superadmin"]).nullish()
});
var GroupWithParticipantsResponseSchema = GroupResponseSchema.extend({
participants: import_zod6.z.array(ParticipantResponseSchema)
});
var GroupResponseSchemaTransform = (group) => ({
jid: GroupJid(group.id),
name: group.subject,
pictureUrl: group.pictureUrl || void 0,
size: group.size,
subject: {
owner: Jid(group.subjectOwner),
time: group.subjectTime
},
owner: {
jid: Jid(group.owner),
phoneNumber: phoneNumberFromJid(group.owner)
},
createdAt: group.creation,
restrict: group.restrict,
announce: group.announce
});
var ParticipantResponseSchemaTransform = (participant) => ({
id: participant.id,
role: participant.admin || "member"
});
var GroupWithParticipantsResponseSchemaTransform = (group) => ({
...GroupResponseSchemaTransform(group),
participants: group.participants.map(ParticipantResponseSchemaTransform)
});
// src/modules/groups/schemas/find-all.ts
var FindAllGroupsResponseSchema = import_zod7.z.array(GroupResponseSchema).transform(
(groups) => groups.map((group) => GroupResponseSchemaTransform(group))
);
var FindAllGroupsWithParticipantsResponseSchema = import_zod7.z.array(GroupWithParticipantsResponseSchema).transform(
(groups) => groups.map((group) => GroupWithParticipantsResponseSchemaTransform(group))
);
// src/modules/groups/schemas/find-by-invite-code.ts
var import_zod8 = require("zod");
var FindGroupByInviteCodeResponseSchema = GroupWithParticipantsResponseSchema.extend({
isCommunity: import_zod8.z.boolean(),
isCommunityAnnounce: import_zod8.z.boolean(),
joinApprovalMode: import_zod8.z.boolean(),
memberAddMode: import_zod8.z.boolean()
}).omit({ pictureUrl: true }).transform((group) => ({
...GroupWithParticipantsResponseSchemaTransform({
...group,
pictureUrl: null
}),
isCommunity: group.isCommunity,
isCommunityAnnounce: group.isCommunityAnnounce,
joinApprovalMode: group.joinApprovalMode,
memberAddMode: group.memberAddMode
}));
// src/modules/groups/schemas/find-by-jid.ts
var FindGroupByJidResponseSchema = GroupWithParticipantsResponseSchema.transform(
GroupWithParticipantsResponseSchemaTransform
);
// src/modules/groups/index.ts
var GroupsModule = class {
constructor(api) {
this.api = api;
}
async findAll(getParticipants = false) {
const response = await this.api.get(Routes.Groups.FindAll, {
params: { getParticipants: import_zod9.z.boolean().parse(getParticipants) }
});
if (getParticipants) {
return FindAllGroupsWithParticipantsResponseSchema.parse(response);
}
return FindAllGroupsResponseSchema.parse(response);
}
/**
* Gets a group by invite code
* @param inviteCode - The group invite code (not the URL)
*/
async findByInviteCode(inviteCode) {
const response = await this.api.get(Routes.Groups.FindByInviteCode, {
params: { inviteCode: GroupInviteCodeSchema.parse(inviteCode) }
});
return FindGroupByInviteCodeResponseSchema.parse(response);
}
/**
* Gets a group by JID
* @param groupJid - The group JID terminated with \@g.us
*/
async findByJid(groupJid) {
const response = await this.api.get(Routes.Groups.FindByJid, {
params: { groupJid: GroupJidSchema.parse(groupJid) }
});
return FindGroupByJidResponseSchema.parse(response);
}
};
// src/modules/messages/schemas/audio.ts
var import_zod11 = require("zod");
// src/modules/messages/schemas/base.ts
var import_zod10 = require("zod");
var BaseMessageOptionsSchema = import_zod10.z.object({
/**
* Number (with country code) or JID to receive the message
*/
number: ApiNumberSchema,
/**
* Time in milliseconds before sending message
*/
delay: import_zod10.z.number().optional()
});
// src/modules/messages/schemas/audio.ts
var AudioMessageOptionsSchema = BaseMessageOptionsSchema.extend({
/**
* Audio URL or file in base64
*/
audio: mediaSchema,
/**
* Audio mimetype
*/
mimetype: import_zod11.z.string().optional()
});
var AudioMessageBodySchema = AudioMessageOptionsSchema.transform(
({ audio, ...data }) => ({ ...data, media: audio, mediatype: "audio" })
);
var AudioMessageResponseSchema = import_zod11.z.object({
key: import_zod11.z.object({
remoteJid: import_zod11.z.string(),
id: import_zod11.z.string()
}),
message: import_zod11.z.object({
audioMessage: import_zod11.z.object({
url: import_zod11.z.string().url(),
mimetype: import_zod11.z.string().optional(),
fileSha256: import_zod11.z.string().base64(),
fileLength: import_zod11.z.coerce.number(),
seconds: import_zod11.z.number(),
mediaKey: import_zod11.z.string().base64(),
fileEncSha256: import_zod11.z.string().base64(),
directPath: import_zod11.z.string(),
mediaKeyTimestamp: import_zod11.z.coerce.number().transform((value) => new Date(value))
})
}),
messageTimestamp: import_zod11.z.coerce.date()
}).transform((data) => ({
receiver: {
phoneNumber: phoneNumberFromJid(data.key.remoteJid),
jid: Jid(data.key.remoteJid)
},
media: {
url: data.message.audioMessage.url,
mimetype: data.message.audioMessage.mimetype,
length: data.message.audioMessage.fileLength,
durationInSeconds: data.message.audioMessage.seconds,
sha256: data.message.audioMessage.fileSha256,
encryptedSha256: data.message.audioMessage.fileEncSha256,
directPath: data.message.audioMessage.directPath,
key: data.message.audioMessage.mediaKey,
keyTimestamp: data.message.audioMessage.mediaKeyTimestamp
},
id: MessageId(data.key.id),
timestamp: data.messageTimestamp
}));
// src/modules/messages/schemas/contact.ts
var import_libphonenumber_js4 = require("libphonenumber-js");
var import_zod12 = require("zod");
var ContactMessageOptionsSchema = BaseMessageOptionsSchema.extend({
/**
* Contact list
*/
contacts: import_zod12.z.array(
import_zod12.z.object({
/**
* Contact display name
*/
fullName: import_zod12.z.string(),
/**
* Contact phone number
*/
phoneNumber: PhoneNumberSchema,
/**
* Contact organization
*/
organization: import_zod12.z.string().optional(),
/**
* Contact email
*/
email: import_zod12.z.string().email().optional(),
/**
* Contact website url
*/
url: import_zod12.z.string().url().optional()
})
)
});
var ContactMessageBodySchema = ContactMessageOptionsSchema.transform(
({ contacts, ...data }) => ({
...data,
contact: contacts.map((contact) => ({
...contact,
phoneNumber: (0, import_libphonenumber_js4.parsePhoneNumber)(contact.phoneNumber).formatInternational(),
wuid: contact.phoneNumber.replace(/\D/g, "")
}))
})
);
var ContactMessageResponseSchema = import_zod12.z.object({
key: import_zod12.z.object({
remoteJid: import_zod12.z.string(),
id: import_zod12.z.string()
}),
message: import_zod12.z.union([
import_zod12.z.object({
contactMessage: import_zod12.z.object({
displayName: import_zod12.z.string(),
vcard: import_zod12.z.string()
})
}),
import_zod12.z.object({
contactsArrayMessage: import_zod12.z.object({
contacts: import_zod12.z.array(
import_zod12.z.object({
displayName: import_zod12.z.string(),
vcard: import_zod12.z.string()
})
)
})
})
]),
messageTimestamp: import_zod12.z.coerce.date()
}).transform((data) => ({
receiver: {
phoneNumber: phoneNumberFromJid(data.key.remoteJid),
jid: Jid(data.key.remoteJid)
},
contacts: "contactMessage" in data.message ? [data.message.contactMessage] : data.message.contactsArrayMessage.contacts,
id: MessageId(data.key.id),
timestamp: data.messageTimestamp
}));
// src/modules/messages/schemas/document.ts
var import_zod13 = require("zod");
var DocumentMessageOptionsSchema = BaseMessageOptionsSchema.extend({
/**
* Document URL or file in base64
*/
document: mediaSchema,
/**
* Caption to send with document
*/
caption: import_zod13.z.string().optional(),
/**
* Document mimetype
*/
mimetype: import_zod13.z.string().optional(),
/**
* Name of the file
*/
fileName: import_zod13.z.string().optional()
}).refine(
(data) => URL.canParse(data.document) ? true : Boolean(data.fileName),
{
message: "fileName must be provided when document is not an URL",
path: ["fileName"]
}
);
var DocumentMessageBodySchema = DocumentMessageOptionsSchema.transform(
({ document, ...data }) => ({
...data,
media: document,
mediatype: "document"
})
);
var DocumentMessageResponseSchema = import_zod13.z.object({
key: import_zod13.z.object({
remoteJid: import_zod13.z.string(),
id: import_zod13.z.string()
}),
message: import_zod13.z.object({
documentMessage: import_zod13.z.object({
url: import_zod13.z.string().url(),
mimetype: import_zod13.z.string().optional(),
fileSha256: import_zod13.z.string().base64(),
fileLength: import_zod13.z.coerce.number(),
mediaKey: import_zod13.z.string().base64(),
caption: import_zod13.z.string().optional(),
fileName: import_zod13.z.string(),
fileEncSha256: import_zod13.z.string().base64(),
directPath: import_zod13.z.string(),
mediaKeyTimestamp: import_zod13.z.coerce.number().transform((value) => new Date(value))
})
}),
messageTimestamp: import_zod13.z.coerce.date()
}).transform((data) => ({
receiver: {
phoneNumber: phoneNumberFromJid(data.key.remoteJid),
jid: Jid(data.key.remoteJid)
},
media: {
url: data.message.documentMessage.url,
caption: data.message.documentMessage.caption,
mimetype: data.message.documentMessage.mimetype,
length: data.message.documentMessage.fileLength,
sha256: data.message.documentMessage.fileSha256,
fileName: data.message.documentMessage.fileName,
encryptedSha256: data.message.documentMessage.fileEncSha256,
directPath: data.message.documentMessage.directPath,
key: data.message.documentMessage.mediaKey,
keyTimestamp: data.message.documentMessage.mediaKeyTimestamp
},
id: MessageId(data.key.id),
timestamp: data.messageTimestamp
}));
// src/modules/messages/schemas/image.ts
var import_zod14 = require("zod");
var ImageMessageOptionsSchema = BaseMessageOptionsSchema.extend({
/**
* Image URL or file in base64
*/
image: mediaSchema,
/**
* Caption to send with image
*/
caption: import_zod14.z.string().optional(),
/**
* Image mimetype
*/
mimetype: import_zod14.z.string().optional()
});
var ImageMessageBodySchema = ImageMessageOptionsSchema.transform(
({ image, ...data }) => ({ ...data, media: image, mediatype: "image" })
);
var ImageMessageResponseSchema = import_zod14.z.object({
key: import_zod14.z.object({
remoteJid: import_zod14.z.string(),
id: import_zod14.z.string()
}),
message: import_zod14.z.object({
imageMessage: import_zod14.z.object({
url: import_zod14.z.string().url(),
mimetype: import_zod14.z.string().optional(),
fileSha256: import_zod14.z.string().base64(),
fileLength: import_zod14.z.coerce.number(),
height: import_zod14.z.number(),
width: import_zod14.z.number(),
mediaKey: import_zod14.z.string().base64(),
caption: import_zod14.z.string().optional(),
fileEncSha256: import_zod14.z.string().base64(),
directPath: import_zod14.z.string(),
mediaKeyTimestamp: import_zod14.z.coerce.number().transform((value) => new Date(value))
})
}),
messageTimestamp: import_zod14.z.coerce.date()
}).transform((data) => ({
receiver: {
phoneNumber: phoneNumberFromJid(data.key.remoteJid),
jid: Jid(data.key.remoteJid)
},
media: {
url: data.message.imageMessage.url,
caption: data.message.imageMessage.caption,
mimetype: data.message.imageMessage.mimetype,
length: data.message.imageMessage.fileLength,
height: data.message.imageMessage.height,
width: data.message.imageMessage.width,
sha256: data.message.imageMessage.fileSha256,
encryptedSha256: data.message.imageMessage.fileEncSha256,
directPath: data.message.imageMessage.directPath,
key: data.message.imageMessage.mediaKey,
keyTimestamp: data.message.imageMessage.mediaKeyTimestamp
},
id: MessageId(data.key.id),
timestamp: data.messageTimestamp
}));
// src/modules/messages/schemas/location.ts
var import_zod15 = require("zod");
var LocationMessageOptionsSchema = BaseMessageOptionsSchema.extend({
/**
* Location name
*/
name: import_zod15.z.string(),
/**
* Location address
*/
address: import_zod15.z.string(),
/**
* Location latitude
*/
latitude: import_zod15.z.number(),
/**
* Location longitude
*/
longitude: import_zod15.z.number()
});
var LocationMessageBodySchema = LocationMessageOptionsSchema;
var LocationMessageResponseSchema = import_zod15.z.object({
key: import_zod15.z.object({
remoteJid: import_zod15.z.string(),
id: import_zod15.z.string()
}),
message: import_zod15.z.object({
locationMessage: import_zod15.z.object({
degreesLatitude: import_zod15.z.number(),
degreesLongitude: import_zod15.z.number(),
name: import_zod15.z.string(),
address: import_zod15.z.string()
})
}),
messageTimestamp: import_zod15.z.coerce.date()
}).transform((data) => ({
receiver: {
phoneNumber: phoneNumberFromJid(data.key.remoteJid),
jid: Jid(data.key.remoteJid)
},
location: {
latitude: data.message.locationMessage.degreesLatitude,
longitude: data.message.locationMessage.degreesLongitude,
name: data.message.locationMessage.name,
address: data.message.locationMessage.address
},
id: MessageId(data.key.id),
timestamp: data.messageTimestamp
}));
// src/modules/messages/schemas/sticker.ts
var import_zod16 = require("zod");
var StickerMessageOptionsSchema = BaseMessageOptionsSchema.extend({
/**
* Image URL or file in base64
*/
sticker: mediaSchema
});
var StickerMessageBodySchema = StickerMessageOptionsSchema;
var StickerMessageResponseSchema = import_zod16.z.object({
key: import_zod16.z.object({
remoteJid: import_zod16.z.string(),
id: import_zod16.z.string()
}),
message: import_zod16.z.object({
stickerMessage: import_zod16.z.object({
url: import_zod16.z.string().url(),
fileSha256: import_zod16.z.string().base64(),
fileEncSha256: import_zod16.z.string().base64(),
mediaKey: import_zod16.z.string().base64(),
mimetype: import_zod16.z.string().optional(),
directPath: import_zod16.z.string(),
fileLength: import_zod16.z.coerce.number(),
mediaKeyTimestamp: import_zod16.z.coerce.number().transform((value) => new Date(value))
})
}),
messageTimestamp: import_zod16.z.coerce.date()
}).transform((data) => ({
receiver: {
phoneNumber: phoneNumberFromJid(data.key.remoteJid),
jid: Jid(data.key.remoteJid)
},
media: {
url: data.message.stickerMessage.url,
mimetype: data.message.stickerMessage.mimetype,
length: data.message.stickerMessage.fileLength,
sha256: data.message.stickerMessage.fileSha256,
encryptedSha256: data.message.stickerMessage.fileEncSha256,
directPath: data.message.stickerMessage.directPath,
key: data.message.stickerMessage.mediaKey,
keyTimestamp: data.message.stickerMessage.mediaKeyTimestamp
},
id: MessageId(data.key.id),
timestamp: data.messageTimestamp
}));
// src/modules/messages/schemas/text.ts
var import_zod17 = require("zod");
var TextMessageOptionsSchema = BaseMessageOptionsSchema.extend({
/**
* Message text content
*/
text: import_zod17.z.string(),
/**
* Whether link preview should be shown
*/
linkPreview: import_zod17.z.boolean().optional()
});
var TextMessageBodySchema = TextMessageOptionsSchema;
var TextMessageResponseSchema = import_zod17.z.object({
key: import_zod17.z.object({
remoteJid: import_zod17.z.string(),
id: import_zod17.z.string()
}),
messageTimestamp: import_zod17.z.coerce.date()
}).transform((data) => ({
receiver: {
phoneNumber: phoneNumberFromJid(data.key.remoteJid),
jid: Jid(data.key.remoteJid)
},
messageId: MessageId(data.key.id),
timestamp: data.messageTimestamp
}));
// src/modules/messages/schemas/video.ts
var import_zod18 = require("zod");
var VideoMessageOptionsSchema = BaseMessageOptionsSchema.extend({
/**
* Video URL or file in base64
*/
video: mediaSchema,
/**
* Caption to send with video
*/
caption: import_zod18.z.string().optional(),
/**
* Video mimetype
*/
mimetype: import_zod18.z.string().optional()
});
var VideoMessageBodySchema = VideoMessageOptionsSchema.transform(
({ video, ...data }) => ({ ...data, media: video, mediatype: "video" })
);
var VideoMessageResponseSchema = import_zod18.z.object({
key: import_zod18.z.object({
remoteJid: import_zod18.z.string(),
id: import_zod18.z.string()
}),
message: import_zod18.z.object({
videoMessage: import_zod18.z.object({
url: import_zod18.z.string().url(),
mimetype: import_zod18.z.string().optional(),
fileSha256: import_zod18.z.string().base64(),
fileLength: import_zod18.z.coerce.number(),
mediaKey: import_zod18.z.string().base64(),
caption: import_zod18.z.string().optional(),
gifPlayback: import_zod18.z.boolean(),
fileEncSha256: import_zod18.z.string().base64(),
directPath: import_zod18.z.string(),
mediaKeyTimestamp: import_zod18.z.coerce.number().transform((value) => new Date(value))
})
}),
messageTimestamp: import_zod18.z.coerce.date()
}).transform((data) => ({
receiver: {
phoneNumber: phoneNumberFromJid(data.key.remoteJid),
jid: Jid(data.key.remoteJid)
},
media: {
url: data.message.videoMessage.url,
caption: data.message.videoMessage.caption,
mimetype: data.message.videoMessage.mimetype,
gifPlayback: data.message.videoMessage.gifPlayback,
length: data.message.videoMessage.fileLength,
sha256: data.message.videoMessage.fileSha256,
encryptedSha256: data.message.videoMessage.fileEncSha256,
directPath: data.message.videoMessage.directPath,
key: data.message.videoMessage.mediaKey,
keyTimestamp: data.message.videoMessage.mediaKeyTimestamp
},
id: MessageId(data.key.id),
timestamp: data.messageTimestamp
}));
// src/modules/messages/schemas/voice.ts
var import_zod19 = require("zod");
var VoiceMessageOptionsSchema = BaseMessageOptionsSchema.extend({
/**
* Audio URL or file in base64
*/
audio: mediaSchema,
/**
* Encode audio into WhatsApp default format (allows audio to be sped up)
* @default true
*/
encoding: import_zod19.z.boolean().optional().default(true)
});
var VoiceMessageBodySchema = VoiceMessageOptionsSchema;
var VoiceMessageResponseSchema = import_zod19.z.object({
key: import_zod19.z.object({
remoteJid: import_zod19.z.string(),
id: import_zod19.z.string()
}),
message: import_zod19.z.object({
audioMessage: import_zod19.z.object({
url: import_zod19.z.string().url(),
mimetype: import_zod19.z.string(),
fileSha256: import_zod19.z.string().base64(),
fileLength: import_zod19.z.coerce.number(),
seconds: import_zod19.z.number(),
ptt: import_zod19.z.boolean().optional(),
mediaKey: import_zod19.z.string().base64(),
fileEncSha256: import_zod19.z.string().base64(),
directPath: import_zod19.z.string(),
mediaKeyTimestamp: import_zod19.z.coerce.number().transform((value) => new Date(value)),
waveform: import_zod19.z.string().base64().nullish()
})
}),
messageTimestamp: import_zod19.z.coerce.date()
}).transform((data) => ({
receiver: {
phoneNumber: phoneNumberFromJid(data.key.remoteJid),
jid: Jid(data.key.remoteJid)
},
media: {
url: data.message.audioMessage.url,
mimetype: data.message.audioMessage.mimetype,
length: data.message.audioMessage.fileLength,
durationInSeconds: data.message.audioMessage.seconds,
sha256: data.message.audioMessage.fileSha256,
encryptedSha256: data.message.audioMessage.fileEncSha256,
directPath: data.message.audioMessage.directPath,
/**
* Indicates whether the audio message is a push-to-talk (PTT) message
*/
isPtt: data.message.audioMessage.ptt,
key: data.message.audioMessage.mediaKey,
keyTimestamp: data.message.audioMessage.mediaKeyTimestamp,
waveform: data.message.audioMessage.waveform
},
messageId: MessageId(data.key.id),
timestamp: data.messageTimestamp
}));
// src/modules/messages/index.ts
var MessagesModule = class {
constructor(api) {
this.api = api;
}
/**
* Sends a text message
* @param options - Text message options
*/
async sendText(options) {
const body = TextMessageBodySchema.parse(options);
const response = await this.api.post(Routes.Message.SendText, { body });
return TextMessageResponseSchema.parse(response);
}
/**
* Sends an image
* @param options - Image message options
*/
async sendImage(options) {
const body = ImageMessageBodySchema.parse(options);
const response = await this.api.post(Routes.Message.SendMedia, { body });
return ImageMessageResponseSchema.parse(response);
}
/**
* Sends a video
* @param options - Video message options
*/
async sendVideo(options) {
const body = VideoMessageBodySchema.parse(options);
const response = await this.api.post(Routes.Message.SendMedia, { body });
return VideoMessageResponseSchema.parse(response);
}
/**
* Sends a document
* @param options - Document message options
*/
async sendDocument(options) {
const body = DocumentMessageBodySchema.parse(options);
const response = await this.api.post(Routes.Message.SendMedia, { body });
return DocumentMessageResponseSchema.parse(response);
}
/**
* Sends an audio
* @param options - Audio message options
*/
async sendAudio(options) {
const body = AudioMessageBodySchema.parse(options);
const response = await this.api.post(Routes.Message.SendMedia, { body });
return AudioMessageResponseSchema.parse(response);
}
/**
* Sends a voice message
* @param options - Voice message options
*/
async sendVoice(options) {
const body = VoiceMessageBodySchema.parse(options);
const response = await this.api.post(Routes.Message.SendVoice, { body });
return VoiceMessageResponseSchema.parse(response);
}
/**
* Sends a sticker
* @param options - Sticker message options
*/
async sendSticker(options) {
const body = StickerMessageBodySchema.parse(options);
const response = await this.api.post(Routes.Message.SendSticker, { body });
return StickerMessageResponseSchema.parse(response);
}
/**
* Sends a location
* @param options - Location message options
*/
async sendLocation(options) {
const body = LocationMessageBodySchema.parse(options);
const response = await this.api.post(Routes.Message.SendLocation, { body });
return LocationMessageResponseSchema.parse(response);
}
/**
* Sends a contact
* @param options - Contact message options
*/
async sendContact(options) {
const body = ContactMessageBodySchema.parse(options);
const response = await this.api.post(Routes.Message.SendContact, { body });
return ContactMessageResponseSchema.parse(response);
}
};
// src/schemas/client.ts
var import_zod20 = require("zod");
var ClientOptionsSchema = import_zod20.z.object({
/**
* Your server URL
*/
serverUrl: import_zod20.z.string().url(),
/**
* Your instance token or global API key
*/
token: import_zod20.z.string(),
/**
* Your instance name
*/
instance: import_zod20.z.string()
});
// src/index.ts
var EvolutionClient = class {
/**
* Evolution Client - API client for interacting with the Evolution API
* @param options - Client options
*/
constructor(options) {
this.options = options;
/**
* API service for directly interacting with the Evolution API (no specific typings)
*/
__publicField(this, "api");
/**
* Find and manage chats, send presences and check numbers
*/
__publicField(this, "chats");
/**
* Find and manage groups
*/
__publicField(this, "groups");
/**
* Send messages
*/
__publicField(this, "messages");
ClientOptionsSchema.parse(options);
this.api = new ApiService(options);
this.chats = new ChatsModule(this.api);
this.groups = new GroupsModule(this.api);
this.messages = new MessagesModule(this.api);
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ChatId,
EvolutionApiError,
EvolutionClient,
GroupJid,
Jid,
MessageId,
phoneNumberFromJid
});
//# sourceMappingURL=index.js.map