Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(engine): extract the pure mapping regions from mapMessage

Yudhi Armyndharis1195614e55f2
diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.ts
index cd0acd003..756735984 100644
--- a/src/engine/adapters/baileys-events.ts
+++ b/src/engine/adapters/baileys-events.ts
@@ -9,7 +9,13 @@ import {
ReactionEvent,
RevokedMessage,
} from '../interfaces/whatsapp-engine.interface';
-import { buildIncomingMessageFromBaileys, extractBaileysBody, mapBaileysStatus } from './baileys-message-mapper';
+import {
+ buildIncomingMessageFromBaileys,
+ extractBaileysBody,
+ extractBaileysContext,
+ extractBaileysLocation,
+ mapBaileysStatus,
+} from './baileys-message-mapper';
import { buildEditedMessage } from './message-mapper';
import { toUnixSeconds } from './baileys-history';
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
@@ -524,41 +530,22 @@ export class BaileysEvents {
return withInboundDownloadTimeout(download, inboundMediaTimeoutMs(), () => stream?.destroy?.());
}
- async mapMessage(
+ /**
+ * Resolve the media payload of an inbound message: the omitted marker when the download is skipped
+ * or disabled, the same marker when the declared size trips the pre-download gate, otherwise the
+ * capped stream-download. Impure by nature — it downloads, logs and reads env — so it stays beside
+ * {@link downloadInboundMediaCapped} rather than moving to the pure mapper module.
+ *
+ * `skipMediaDownload` is a plain boolean so the `||` keeps its short-circuit order:
+ * `isMediaDownloadEnabled()` reads `process.env` at call time and must not run when skip is set.
+ */
+ private async resolveInboundMedia(
msg: WAMessage,
contentType: string | undefined,
- opts?: { skipMediaDownload?: boolean },
- ): Promise<IncomingMessage> {
- const b = await this.host.loadLib();
- const content = msg.message ?? {};
- // Read body/isPtt off the NORMALIZED content: a disappearing message (ephemeralMessage), a captioned
- // document (documentWithCaptionMessage) and viewOnce/edited wrappers nest the real text/caption under
- // an inner message, so the raw wrapper exposes none at top level. Identity no-op when unwrapped.
- const normalized = b.normalizeMessageContent(content) ?? content;
-
- // Body: text first, then media caption, then WhatsApp Business interactive shapes (#562).
- const body = extractBaileysBody(normalized);
-
- // --- location ---
- // ILocationMessage has name/address; ILiveLocationMessage does not — use the static variant only.
- let location: IncomingMessage['location'];
- if (contentType === 'locationMessage' || contentType === 'liveLocationMessage') {
- // Read off the NORMALIZED content: an ephemeral/disappearing-chat location nests under the wrapper,
- // so the raw `content.locationMessage` is undefined and the coordinates would be silently dropped.
- const lm = normalized.locationMessage ?? normalized.liveLocationMessage;
- if (lm) {
- const staticLm = normalized.locationMessage; // only ILocationMessage has name/address
- location = {
- latitude: lm.degreesLatitude ?? 0,
- longitude: lm.degreesLongitude ?? 0,
- description: staticLm?.name ?? undefined,
- address: staticLm?.address ?? undefined,
- };
- }
- }
-
- // --- media (image / video / audio / document / sticker) ---
- let media: IncomingMessage['media'];
+ content: NonNullable<WAMessage['message']>,
+ b: typeof BaileysLib,
+ skipMediaDownload: boolean,
+ ): Promise<IncomingMessage['media']> {
const isMediaType =
contentType === 'imageMessage' ||
contentType === 'videoMessage' ||
@@ -566,127 +553,104 @@ export class BaileysEvents {
contentType === 'documentMessage' ||
contentType === 'documentWithCaptionMessage' ||
contentType === 'stickerMessage';
- if (isMediaType) {
- // The outbound "sent" echo passes skipMediaDownload: the sender already holds the media, and for
- // parity with the wwjs message.sent (which carries no media buffer) we emit only the marker here.
- if (opts?.skipMediaDownload || !isMediaDownloadEnabled()) {
- // Emit the omitted marker so the media field is present (webhook/n8n/dashboard contract).
- // mimetype is available pre-download from the message content.
- const normalizedContent = b.normalizeMessageContent(content) ?? content;
- const subMessage =
- normalizedContent.imageMessage ??
- normalizedContent.videoMessage ??
- normalizedContent.audioMessage ??
- normalizedContent.documentMessage ??
- normalizedContent.stickerMessage;
- media = {
- mimetype: subMessage?.mimetype ?? '',
- filename: normalizedContent.documentMessage?.fileName ?? undefined,
- omitted: true,
- sizeBytes: coerceDeclaredSize(subMessage?.fileLength),
- };
- } else {
- // normalizeMessageContent unwraps documentWithCaptionMessage / viewOnceMessage / ephemeralMessage
- // so we reach the inner media sub-message — needed BEFORE download for the declared-size pre-gate.
- const normalizedContent = b.normalizeMessageContent(content) ?? content;
- const subMessage =
- normalizedContent.imageMessage ??
- normalizedContent.videoMessage ??
- normalizedContent.audioMessage ??
- normalizedContent.documentMessage ??
- normalizedContent.stickerMessage;
- const mimetype = subMessage?.mimetype ?? '';
- const filename = normalizedContent.documentMessage?.fileName ?? undefined;
- const maxBytes = inboundMediaMaxBytes();
- const declared = coerceDeclaredSize(subMessage?.fileLength);
-
- if (declared > maxBytes) {
- // Pre-download gate: an honest over-cap sender's media is never decrypted into heap at all
- // (Baileys integrity-checks content against the declared size, so this is a robust bound).
- media = { mimetype, filename, omitted: true, sizeBytes: declared };
- this.host.logger.warn('Inbound media declared size exceeds MEDIA_DOWNLOAD_MAX_BYTES; skipped download', {
- msgId: msg.key.id,
- sizeBytes: declared,
- });
- } else {
- try {
- // Stream-download with a running-total abort so a sender who understates fileLength still
- // can't materialise an over-cap blob. For under-cap media this yields the identical buffer.
- const buf = await this.downloadInboundMediaCapped(msg, maxBytes);
- if (buf === null) {
- media = { mimetype, filename, omitted: true, sizeBytes: maxBytes };
- this.host.logger.warn(
- 'Inbound media download aborted (over MEDIA_DOWNLOAD_MAX_BYTES or past MEDIA_DOWNLOAD_TIMEOUT_MS); emitting omitted marker',
- { msgId: msg.key.id },
- );
- } else {
- // capInboundMedia is the last line (lazy base64, never persist/webhook/broadcast an over-cap
- // blob); the real heap bound is the pre-gate + streaming abort + concurrency limiter.
- media = capInboundMedia({
- mimetype,
- filename,
- sizeBytes: buf.byteLength,
- toBase64: () => buf.toString('base64'),
- });
- }
- } catch (err) {
- this.host.logger.debug('Failed to download inbound media; emitting message without media', {
- error: err instanceof Error ? err.message : String(err),
- msgId: msg.key.id,
- });
- }
- }
- }
+ if (!isMediaType) {
+ return undefined;
}
- // --- quoted message + disappearing-messages timer ---
- let quotedMessage: IncomingMessage['quotedMessage'];
- // Read context off the NORMALIZED content: a live disappearing message arrives wrapped in
- // `ephemeralMessage` (also viewOnce / documentWithCaption), whose inner content carries the
- // contextInfo. The raw wrapper exposes none at top level, so both the quote and the timer
- // (`contextInfo.expiration`) would be missed if we read the raw content here.
- const normalizedForContext = b.normalizeMessageContent(content) ?? content;
- const subForContext =
- normalizedForContext.extendedTextMessage ??
- normalizedForContext.imageMessage ??
- normalizedForContext.videoMessage ??
- normalizedForContext.audioMessage ??
- normalizedForContext.documentMessage ??
- normalizedForContext.stickerMessage ??
- normalizedForContext.locationMessage;
- // A text status's styling rides on the extended-text content (proto backgroundArgb/font) —
- // surface it so the store/viewer can render the story the way it was posted.
- const extText = normalizedForContext.extendedTextMessage;
- const contextInfo = (
- subForContext as
- | {
- contextInfo?: {
- stanzaId?: string | null;
- quotedMessage?: Record<string, unknown> | null;
- expiration?: number | null;
- mentionedJid?: string[] | null;
- };
- }
- | undefined
- )?.contextInfo;
- if (contextInfo?.quotedMessage && contextInfo.stanzaId) {
- const qm = contextInfo.quotedMessage as {
- conversation?: string | null;
- extendedTextMessage?: { text?: string | null } | null;
- imageMessage?: { caption?: string | null } | null;
- videoMessage?: { caption?: string | null } | null;
- documentMessage?: { caption?: string | null } | null;
+ // The outbound "sent" echo passes skipMediaDownload: the sender already holds the media, and for
+ // parity with the wwjs message.sent (which carries no media buffer) we emit only the marker here.
+ if (skipMediaDownload || !isMediaDownloadEnabled()) {
+ // Emit the omitted marker so the media field is present (webhook/n8n/dashboard contract).
+ // mimetype is available pre-download from the message content.
+ const normalizedContent = b.normalizeMessageContent(content) ?? content;
+ const subMessage =
+ normalizedContent.imageMessage ??
+ normalizedContent.videoMessage ??
+ normalizedContent.audioMessage ??
+ normalizedContent.documentMessage ??
+ normalizedContent.stickerMessage;
+ return {
+ mimetype: subMessage?.mimetype ?? '',
+ filename: normalizedContent.documentMessage?.fileName ?? undefined,
+ omitted: true,
+ sizeBytes: coerceDeclaredSize(subMessage?.fileLength),
};
- const qBody =
- qm.conversation ??
- qm.extendedTextMessage?.text ??
- qm.imageMessage?.caption ??
- qm.videoMessage?.caption ??
- qm.documentMessage?.caption ??
- '';
- quotedMessage = { id: contextInfo.stanzaId, body: qBody };
}
+ // normalizeMessageContent unwraps documentWithCaptionMessage / viewOnceMessage / ephemeralMessage
+ // so we reach the inner media sub-message — needed BEFORE download for the declared-size pre-gate.
+ const normalizedContent = b.normalizeMessageContent(content) ?? content;
+ const subMessage =
+ normalizedContent.imageMessage ??
+ normalizedContent.videoMessage ??
+ normalizedContent.audioMessage ??
+ normalizedContent.documentMessage ??
+ normalizedContent.stickerMessage;
+ const mimetype = subMessage?.mimetype ?? '';
+ const filename = normalizedContent.documentMessage?.fileName ?? undefined;
+ const maxBytes = inboundMediaMaxBytes();
+ const declared = coerceDeclaredSize(subMessage?.fileLength);
+
+ if (declared > maxBytes) {
+ // Pre-download gate: an honest over-cap sender's media is never decrypted into heap at all
+ // (Baileys integrity-checks content against the declared size, so this is a robust bound).
+ this.host.logger.warn('Inbound media declared size exceeds MEDIA_DOWNLOAD_MAX_BYTES; skipped download', {
+ msgId: msg.key.id,
+ sizeBytes: declared,
+ });
+ return { mimetype, filename, omitted: true, sizeBytes: declared };
+ }
+
+ try {
+ // Stream-download with a running-total abort so a sender who understates fileLength still
+ // can't materialise an over-cap blob. For under-cap media this yields the identical buffer.
+ const buf = await this.downloadInboundMediaCapped(msg, maxBytes);
+ if (buf === null) {
+ this.host.logger.warn(
+ 'Inbound media download aborted (over MEDIA_DOWNLOAD_MAX_BYTES or past MEDIA_DOWNLOAD_TIMEOUT_MS); emitting omitted marker',
+ { msgId: msg.key.id },
+ );
+ return { mimetype, filename, omitted: true, sizeBytes: maxBytes };
+ }
+ // capInboundMedia is the last line (lazy base64, never persist/webhook/broadcast an over-cap
+ // blob); the real heap bound is the pre-gate + streaming abort + concurrency limiter.
+ return capInboundMedia({
+ mimetype,
+ filename,
+ sizeBytes: buf.byteLength,
+ toBase64: () => buf.toString('base64'),
+ });
+ } catch (err) {
+ // A download failure yields a message with no media, never a propagated throw.
+ this.host.logger.debug('Failed to download inbound media; emitting message without media', {
+ error: err instanceof Error ? err.message : String(err),
+ msgId: msg.key.id,
+ });
+ return undefined;
+ }
+ }
+
+ async mapMessage(
+ msg: WAMessage,
+ contentType: string | undefined,
+ opts?: { skipMediaDownload?: boolean },
+ ): Promise<IncomingMessage> {
+ const b = await this.host.loadLib();
+ const content = msg.message ?? {};
+ // Read body/location/media/context off the NORMALIZED content: a disappearing message
+ // (ephemeralMessage), a captioned document (documentWithCaptionMessage) and viewOnce/edited wrappers
+ // nest the real payload under an inner message, so the raw wrapper exposes none at top level.
+ // Identity no-op when unwrapped.
+ const normalized = b.normalizeMessageContent(content) ?? content;
+
+ // Body: text first, then media caption, then WhatsApp Business interactive shapes (#562).
+ const body = extractBaileysBody(normalized);
+ const location = extractBaileysLocation(normalized, contentType);
+ const media = await this.resolveInboundMedia(msg, contentType, content, b, opts?.skipMediaDownload === true);
+ // The quote, the disappearing-messages timer, the mentions and the status styling all come from
+ // one region of the content — see BaileysMessageContext.
+ const context = extractBaileysContext(normalized);
+
return buildIncomingMessageFromBaileys(
{
id: msg.key.id ?? '',
@@ -701,11 +665,11 @@ export class BaileysEvents {
selfJid: this.host.normalizedSelfJid(),
media,
location,
- quotedMessage,
- ephemeralDuration: contextInfo?.expiration ?? undefined,
- mentionedJids: contextInfo?.mentionedJid ?? undefined,
- backgroundArgb: typeof extText?.backgroundArgb === 'number' ? extText.backgroundArgb : undefined,
- font: typeof extText?.font === 'number' ? extText.font : undefined,
+ quotedMessage: context.quotedMessage,
+ ephemeralDuration: context.ephemeralDuration,
+ mentionedJids: context.mentionedJids,
+ backgroundArgb: context.backgroundArgb,
+ font: context.font,
},
jid => this.host.toNeutralJid(jid),
);
diff --git a/src/engine/adapters/baileys-message-mapper.ts b/src/engine/adapters/baileys-message-mapper.ts
index 5a68c3cfb..b634cb0d7 100644
--- a/src/engine/adapters/baileys-message-mapper.ts
+++ b/src/engine/adapters/baileys-message-mapper.ts
@@ -101,6 +101,141 @@ export function extractBaileysBody(content: BaileysBodyContent): string {
);
}
+/**
+ * The inbound message-content subset the location extractor reads. Declared structurally (not
+ * `proto.IMessage`) for the same reason as {@link BaileysBodyContent}. The live variant carries
+ * only the two coordinates on purpose: `proto.Message.ILiveLocationMessage` has no `name`/`address`
+ * — only `ILocationMessage` does — which is why those two are sourced from the static variant.
+ */
+export interface BaileysLocationContent {
+ locationMessage?: {
+ degreesLatitude?: number | null;
+ degreesLongitude?: number | null;
+ name?: string | null;
+ address?: string | null;
+ } | null;
+ liveLocationMessage?: { degreesLatitude?: number | null; degreesLongitude?: number | null } | null;
+}
+
+/**
+ * Extract the coordinates of a location message, static or live. Returns `undefined` for any other
+ * content type, and for a location content type whose sub-message is absent. Pass the NORMALIZED
+ * content (an ephemeral/disappearing-chat location nests under the wrapper, so the raw
+ * `content.locationMessage` is undefined and the coordinates would be silently dropped).
+ */
+export function extractBaileysLocation(
+ content: BaileysLocationContent,
+ contentType: string | undefined,
+): IncomingMessage['location'] {
+ if (contentType !== 'locationMessage' && contentType !== 'liveLocationMessage') {
+ return undefined;
+ }
+ const lm = content.locationMessage ?? content.liveLocationMessage;
+ if (!lm) {
+ return undefined;
+ }
+ const staticLm = content.locationMessage; // only ILocationMessage has name/address
+ return {
+ latitude: lm.degreesLatitude ?? 0,
+ longitude: lm.degreesLongitude ?? 0,
+ description: staticLm?.name ?? undefined,
+ address: staticLm?.address ?? undefined,
+ };
+}
+
+/**
+ * A content sub-message that may carry a `contextInfo` — the quote, the disappearing-messages timer
+ * and the mention list all ride there, on whichever sub-message the payload happens to be.
+ * `quotedMessage` is `unknown` rather than `Record<string, unknown>`: `proto.IContextInfo.quotedMessage`
+ * is `proto.IMessage | null`, an interface with no index signature, so it is not assignable to a
+ * record type.
+ */
+interface BaileysContextCarrier {
+ contextInfo?: {
+ stanzaId?: string | null;
+ quotedMessage?: unknown;
+ expiration?: number | null;
+ mentionedJid?: string[] | null;
+ } | null;
+}
+
+/**
+ * The inbound message-content subset the context extractor reads: every sub-message that can carry a
+ * `contextInfo`, plus the extended-text styling fields. Declared structurally, as {@link BaileysBodyContent} is.
+ */
+export interface BaileysContextContent {
+ extendedTextMessage?: (BaileysContextCarrier & { backgroundArgb?: number | null; font?: number | null }) | null;
+ imageMessage?: BaileysContextCarrier | null;
+ videoMessage?: BaileysContextCarrier | null;
+ audioMessage?: BaileysContextCarrier | null;
+ documentMessage?: BaileysContextCarrier | null;
+ stickerMessage?: BaileysContextCarrier | null;
+ locationMessage?: BaileysContextCarrier | null;
+}
+
+/** Everything the context region of an inbound message yields — not just the quote. */
+export interface BaileysMessageContext {
+ /** The quoted (replied-to) message, when `contextInfo` carries both a quote and its stanza id. */
+ quotedMessage?: IncomingMessage['quotedMessage'];
+ /** Disappearing-messages timer from `contextInfo.expiration`. */
+ ephemeralDuration?: number;
+ /** @mentioned JIDs from `contextInfo.mentionedJid`. */
+ mentionedJids?: string[];
+ /** Styling of an extended-text (status) message: proto `backgroundArgb` (fixed32 ARGB). */
+ backgroundArgb?: number;
+ /** Styling of an extended-text (status) message: proto `font` (WhatsApp font index). */
+ font?: number;
+}
+
+/**
+ * Extract the quoted message, the disappearing-messages timer, the mention list and the extended-text
+ * styling from an inbound message's content. Pass the NORMALIZED content: a live disappearing message
+ * arrives wrapped in `ephemeralMessage` (also viewOnce / documentWithCaption), whose inner content
+ * carries the `contextInfo`. The raw wrapper exposes none at top level, so both the quote and the
+ * timer (`contextInfo.expiration`) would be missed if the raw content were passed here.
+ */
+export function extractBaileysContext(content: BaileysContextContent): BaileysMessageContext {
+ const subForContext =
+ content.extendedTextMessage ??
+ content.imageMessage ??
+ content.videoMessage ??
+ content.audioMessage ??
+ content.documentMessage ??
+ content.stickerMessage ??
+ content.locationMessage;
+ // A text status's styling rides on the extended-text content (proto backgroundArgb/font) —
+ // surface it so the store/viewer can render the story the way it was posted.
+ const extText = content.extendedTextMessage;
+ const contextInfo = subForContext?.contextInfo;
+
+ const context: BaileysMessageContext = {
+ ephemeralDuration: contextInfo?.expiration ?? undefined,
+ mentionedJids: contextInfo?.mentionedJid ?? undefined,
+ backgroundArgb: typeof extText?.backgroundArgb === 'number' ? extText.backgroundArgb : undefined,
+ font: typeof extText?.font === 'number' ? extText.font : undefined,
+ };
+
+ if (contextInfo?.quotedMessage && contextInfo.stanzaId) {
+ const qm = contextInfo.quotedMessage as {
+ conversation?: string | null;
+ extendedTextMessage?: { text?: string | null } | null;
+ imageMessage?: { caption?: string | null } | null;
+ videoMessage?: { caption?: string | null } | null;
+ documentMessage?: { caption?: string | null } | null;
+ };
+ const qBody =
+ qm.conversation ??
+ qm.extendedTextMessage?.text ??
+ qm.imageMessage?.caption ??
+ qm.videoMessage?.caption ??
+ qm.documentMessage?.caption ??
+ '';
+ context.quotedMessage = { id: contextInfo.stanzaId, body: qBody };
+ }
+
+ return context;
+}
+
/**
* 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