Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(engine): add baileys-message-mapper (proto -> neutral IncomingMessage)

rmyndharis4c803a2e8098
diff --git a/src/engine/adapters/baileys-message-mapper.spec.ts b/src/engine/adapters/baileys-message-mapper.spec.ts
new file mode 100644
index 000000000..bf3a05125
--- /dev/null
+++ b/src/engine/adapters/baileys-message-mapper.spec.ts
@@ -0,0 +1,107 @@
+import {
+ BaileysIncomingFields,
+ buildIncomingMessageFromBaileys,
+ mapBaileysMessageType,
+ mapBaileysStatus,
+} from './baileys-message-mapper';
+
+describe('mapBaileysMessageType (baileys content-type -> neutral MessageType)', () => {
+ it.each([
+ ['conversation', false, 'text'],
+ ['extendedTextMessage', false, 'text'],
+ ['imageMessage', false, 'image'],
+ ['videoMessage', false, 'video'],
+ ['audioMessage', false, 'audio'],
+ ['audioMessage', true, 'voice'],
+ ['documentMessage', false, 'document'],
+ ['stickerMessage', false, 'sticker'],
+ ['locationMessage', false, 'location'],
+ ['contactMessage', false, 'contact'],
+ [undefined, false, 'unknown'],
+ ['pollCreationMessage', false, 'unknown'],
+ ])('maps %s (ptt=%s) -> %s', (raw, ptt, expected) => {
+ expect(mapBaileysMessageType(raw as string | undefined, ptt as boolean)).toBe(expected);
+ });
+});
+
+describe('mapBaileysStatus (proto WAMessageStatus -> neutral DeliveryStatus)', () => {
+ it.each([
+ [0, 'failed'],
+ [1, 'pending'],
+ [2, 'sent'],
+ [3, 'delivered'],
+ [4, 'read'],
+ [5, 'read'], // PLAYED collapses to read, mirroring the wwjs adapter
+ ])('maps status %s -> %s', (status, expected) => {
+ expect(mapBaileysStatus(status)).toBe(expected);
+ });
+
+ it('returns null for an unknown/absent status so the adapter skips the ack', () => {
+ expect(mapBaileysStatus(undefined)).toBeNull();
+ expect(mapBaileysStatus(99)).toBeNull();
+ });
+});
+
+describe('buildIncomingMessageFromBaileys', () => {
+ const base: BaileysIncomingFields = {
+ id: 'MSG1',
+ remoteJid: '[email protected]',
+ fromMe: false,
+ body: 'hi',
+ contentType: 'conversation',
+ timestamp: 1700000000,
+ selfJid: '[email protected]',
+ };
+
+ it('maps a 1:1 inbound message to the neutral shape (chatId, type, non-group)', () => {
+ const r = buildIncomingMessageFromBaileys(base);
+ expect(r.id).toBe('MSG1');
+ expect(r.chatId).toBe('[email protected]');
+ expect(r.from).toBe('[email protected]');
+ expect(r.to).toBe('[email protected]');
+ expect(r.type).toBe('text');
+ expect(r.isGroup).toBe(false);
+ expect(r.fromMe).toBe(false);
+ });
+
+ it('inverts from/to for an outgoing (fromMe) message', () => {
+ const r = buildIncomingMessageFromBaileys({ ...base, fromMe: true });
+ expect(r.from).toBe('[email protected]'); // self
+ expect(r.to).toBe('[email protected]'); // chat
+ });
+
+ it('sets author to the participant for a group message and flags isGroup', () => {
+ const r = buildIncomingMessageFromBaileys({
+ ...base,
+ remoteJid: '[email protected]',
+ participant: '[email protected]',
+ });
+ expect(r.isGroup).toBe(true);
+ expect(r.author).toBe('[email protected]');
+ expect(r.chatId).toBe('[email protected]');
+ });
+
+ it('flags an @lid 1:1 sender', () => {
+ const r = buildIncomingMessageFromBaileys({ ...base, remoteJid: '111@lid' });
+ expect(r.isLidSender).toBe(true);
+ });
+
+ it('flags an @lid group participant via participant, not the group JID', () => {
+ const r = buildIncomingMessageFromBaileys({
+ ...base,
+ remoteJid: '[email protected]',
+ participant: '222@lid',
+ });
+ expect(r.isLidSender).toBe(true);
+ });
+
+ it('flags a status broadcast', () => {
+ const r = buildIncomingMessageFromBaileys({ ...base, remoteJid: 'status@broadcast' });
+ expect(r.isStatusBroadcast).toBe(true);
+ });
+
+ it('carries the push name onto contact when present', () => {
+ const r = buildIncomingMessageFromBaileys({ ...base, pushName: 'Alice' });
+ expect(r.contact).toEqual({ pushName: 'Alice' });
+ });
+});
diff --git a/src/engine/adapters/baileys-message-mapper.ts b/src/engine/adapters/baileys-message-mapper.ts
new file mode 100644
index 000000000..3fab3473a
--- /dev/null
+++ b/src/engine/adapters/baileys-message-mapper.ts
@@ -0,0 +1,121 @@
+import { DeliveryStatus, IncomingMessage, MessageType } from '../interfaces/whatsapp-engine.interface';
+
+/**
+ * Map a Baileys message content-type token (from `getContentType`) to the engine-neutral
+ * {@link MessageType}. `audioMessage` splits on the `ptt` flag into `voice` vs `audio`,
+ * mirroring the wwjs `ptt -> voice` mapping. Anything unmapped becomes `unknown`.
+ */
+export function mapBaileysMessageType(contentType: string | undefined, isPtt = false): MessageType {
+ switch (contentType) {
+ case 'conversation':
+ case 'extendedTextMessage':
+ return 'text';
+ case 'imageMessage':
+ return 'image';
+ case 'videoMessage':
+ return 'video';
+ case 'audioMessage':
+ return isPtt ? 'voice' : 'audio';
+ case 'documentMessage':
+ case 'documentWithCaptionMessage':
+ return 'document';
+ case 'stickerMessage':
+ return 'sticker';
+ case 'locationMessage':
+ case 'liveLocationMessage':
+ return 'location';
+ case 'contactMessage':
+ case 'contactsArrayMessage':
+ return 'contact';
+ default:
+ return 'unknown';
+ }
+}
+
+/**
+ * Map a Baileys delivery status (`proto.WebMessageInfo.Status`, numeric) to the engine-neutral
+ * {@link DeliveryStatus}. Returns `null` for an absent/unknown status so the adapter skips emitting
+ * an ack. PLAYED collapses to `read`, matching the wwjs adapter.
+ */
+export function mapBaileysStatus(status: number | null | undefined): DeliveryStatus | null {
+ switch (status) {
+ case 0:
+ return 'failed'; // ERROR
+ case 1:
+ return 'pending'; // PENDING
+ case 2:
+ return 'sent'; // SERVER_ACK
+ case 3:
+ return 'delivered'; // DELIVERY_ACK
+ case 4:
+ return 'read'; // READ
+ case 5:
+ return 'read'; // PLAYED
+ default:
+ return null;
+ }
+}
+
+/**
+ * The subset of a Baileys `WAMessage` the adapter reads (after proto extraction) to build the
+ * base of an {@link IncomingMessage}. Declared explicitly so the neutral-shape logic is
+ * unit-testable without constructing a full proto message — mirrors wwjs `RawMessageFields`.
+ */
+export interface BaileysIncomingFields {
+ id: string;
+ /** The chat JID (`key.remoteJid`): a contact, a `@g.us` group, or `status@broadcast`. */
+ remoteJid: string;
+ fromMe: boolean;
+ /** Group sender (`key.participant`); `remoteJid` is the group JID for group messages. */
+ participant?: string;
+ body: string;
+ /** Result of `getContentType(msg.message)`. */
+ contentType: string | undefined;
+ /** `audioMessage.ptt === true` — distinguishes a voice note from an audio file. */
+ isPtt?: boolean;
+ timestamp: number;
+ pushName?: string;
+ /** The account's own normalized JID, for from/to on outgoing messages. */
+ selfJid?: string;
+}
+
+/**
+ * Build a neutral {@link IncomingMessage} from extracted Baileys fields. The chat is always
+ * `remoteJid` (Baileys reports the conversation directly); `fromMe` only flips from/to. The group
+ * sender lives in `participant` (exposed as `author`), matching the wwjs convention where `from`
+ * is the group JID.
+ */
+export function buildIncomingMessageFromBaileys(fields: BaileysIncomingFields): IncomingMessage {
+ const chatId = fields.remoteJid;
+ const isGroup = chatId.endsWith('@g.us');
+ const self = fields.selfJid ?? '';
+
+ const incoming: IncomingMessage = {
+ id: fields.id,
+ from: fields.fromMe ? self : chatId,
+ to: fields.fromMe ? chatId : self,
+ chatId,
+ body: fields.body,
+ type: mapBaileysMessageType(fields.contentType, fields.isPtt),
+ timestamp: fields.timestamp,
+ fromMe: fields.fromMe,
+ isGroup,
+ isStatusBroadcast: chatId === 'status@broadcast',
+ };
+
+ if (isGroup && fields.participant) {
+ incoming.author = fields.participant;
+ }
+
+ // The real sender for an @lid check is the participant in a group, else the chat JID itself.
+ const senderJid = fields.participant ?? chatId;
+ if (senderJid.endsWith('@lid')) {
+ incoming.isLidSender = true;
+ }
+
+ if (fields.pushName) {
+ incoming.contact = { pushName: fields.pushName };
+ }
+
+ return incoming;
+}