@12-apps/messaging 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/whatsapp-web/envelope.ts","../../src/whatsapp-web/adapter.ts","../../src/whatsapp-web/auth-state.ts","../../src/whatsapp-web/baileys-port.ts","../../src/whatsapp-web/normalize.ts","../../src/whatsapp-web/media.ts","../../src/whatsapp-web/session.ts"],"sourcesContent":["import type { InboundContent, NormalizedEvent, ReceiptStatus } from \"../core/types\";\n\n/**\n * The raw body a session hands the engine's inbox.\n *\n * The inbox stores every delivery raw before processing it, and re-parses it\n * on a retry. A socket has no HTTP body, so the session writes one: its\n * already-normalized events, as JSON. Never Baileys' own message objects —\n * they carry media keys and the full protobuf, and the inbox keeps what it\n * is given.\n *\n * `{ \"format\": \"whatsapp-web/1\", \"events\": [...] }`, dates as ISO strings.\n */\nexport const ENVELOPE_FORMAT = \"whatsapp-web/1\";\n\nexport function encodeEnvelope(events: readonly NormalizedEvent[]): string {\n return JSON.stringify({ format: ENVELOPE_FORMAT, events });\n}\n\ntype Json = Record<string, unknown>;\nconst isObject = (value: unknown): value is Json => typeof value === \"object\" && value !== null && !Array.isArray(value);\nconst str = (value: unknown): string | null => (typeof value === \"string\" && value.length > 0 ? value : null);\nconst strOrNull = (value: unknown): string | null => (typeof value === \"string\" ? value : null);\nconst date = (value: unknown): Date | null => {\n const parsed = typeof value === \"string\" ? new Date(value) : null;\n return parsed && Number.isFinite(parsed.getTime()) ? parsed : null;\n};\n\nconst RECEIPTS: readonly ReceiptStatus[] = [\"SENT\", \"DELIVERED\", \"READ\", \"FAILED\"];\n\nconst CONTENT: Readonly<Record<string, (value: Json) => InboundContent | null>> = {\n TEXT: (value) => (typeof value.text === \"string\" ? { kind: \"TEXT\", text: value.text } : null),\n INTERACTIVE: (value) => (str(value.replyId) ? { kind: \"INTERACTIVE\", replyId: value.replyId as string, title: strOrNull(value.title) ?? \"\" } : null),\n AUDIO: (value) => (str(value.mediaId) ? { kind: \"AUDIO\", mediaId: value.mediaId as string, mimeType: strOrNull(value.mimeType) } : null),\n OTHER: (value) => (str(value.channelType) ? { kind: \"OTHER\", channelType: value.channelType as string } : null),\n};\n\nfunction content(value: unknown): InboundContent | null {\n if (!isObject(value) || typeof value.kind !== \"string\") return null;\n return CONTENT[value.kind]?.(value) ?? null;\n}\n\nfunction messageEvent(value: Json, accountId: string): NormalizedEvent | null {\n const contactId = str(value.contactId);\n const externalId = str(value.externalId);\n const sentAt = date(value.sentAt);\n const body = content(value.content);\n if (!contactId || !externalId || !sentAt || !body) return null;\n return { type: \"message\", accountId, contactId, contactName: strOrNull(value.contactName), externalId, sentAt, content: body, optOut: value.optOut === true };\n}\n\nfunction statusEvent(value: Json, accountId: string): NormalizedEvent | null {\n const externalId = str(value.externalId);\n const at = date(value.at);\n const status = RECEIPTS.find((receipt) => receipt === value.status);\n if (!externalId || !at || !status) return null;\n const optional = { contactId: strOrNull(value.contactId), error: strOrNull(value.error), callbackData: strOrNull(value.callbackData) };\n return { type: \"status\", accountId, externalId, status, at, ...optional };\n}\n\nfunction optOutEvent(value: Json, accountId: string): NormalizedEvent | null {\n const contactId = str(value.contactId);\n const at = date(value.at);\n return contactId && at ? { type: \"opt_out\", accountId, contactId, at } : null;\n}\n\nconst EVENTS: Readonly<Record<string, (value: Json, accountId: string) => NormalizedEvent | null>> = {\n message: messageEvent,\n status: statusEvent,\n opt_out: optOutEvent,\n};\n\nfunction event(value: unknown): NormalizedEvent | null {\n if (!isObject(value) || typeof value.type !== \"string\") return null;\n const accountId = str(value.accountId);\n return accountId ? (EVENTS[value.type]?.(value, accountId) ?? null) : null;\n}\n\n/**\n * An envelope's events, in order. Another format, or an event of an unknown\n * shape, yields nothing for it; only bytes that are not JSON throw.\n */\nexport function parseEnvelope(rawBody: string): NormalizedEvent[] {\n const payload = JSON.parse(rawBody) as unknown;\n if (!isObject(payload) || payload.format !== ENVELOPE_FORMAT || !Array.isArray(payload.events)) return [];\n return payload.events.map(event).filter((parsed): parsed is NormalizedEvent => parsed !== null);\n}\n","import { ChannelMediaFailure, ChannelSendFailure, OPEN_SEND_POLICY, type ChannelAdapter, type SendPolicy } from \"../core/channel\";\nimport { WHATSAPP_CHANNEL } from \"../whatsapp\";\nimport { parseEnvelope } from \"./envelope\";\nimport type { WhatsAppWebSession } from \"./session\";\n\nexport interface WhatsAppWebAdapterConfig {\n /**\n * The session that serves an account: one session, or a lookup by the\n * connection's account id (the linked number's digits). A session serves\n * only the account it is linked to.\n */\n sessions: WhatsAppWebSession | ((accountId: string) => WhatsAppWebSession | undefined);\n /**\n * The channel key. Default `whatsapp`, the Cloud adapter's: a host switches a\n * number between the two transports by mounting one adapter or the other,\n * and its connections and conversations stay where they are. Give another\n * key (`whatsapp-web`) to run both side by side.\n */\n kind?: string;\n /**\n * When free-form sends are allowed. Default: always. A personal account has\n * no service window; that window is a rule of the Business API.\n */\n policy?: SendPolicy;\n}\n\n/**\n * The WhatsApp Web adapter: the same `ChannelAdapter` as the Cloud one, over\n * a Baileys session instead of the Graph API.\n *\n * - `handshake` and `verify`: there is no webhook. The verify FAILS CLOSED,\n * so the webhook route refuses any POST to this channel: inbound arrives\n * only from the session's own socket, through `engine.receive`.\n * - `parse` reads the session's envelope (normalized events, never Baileys'\n * raw objects).\n * - `send` and `fetchMedia` go through the session. The connection's\n * credential is not used: the linked device's keys live in the session's\n * auth store.\n */\nexport function createWhatsAppWebAdapter(config: WhatsAppWebAdapterConfig): ChannelAdapter {\n const sessionFor = (accountId: string): WhatsAppWebSession | undefined => {\n if (typeof config.sessions === \"function\") return config.sessions(accountId);\n return config.sessions.accountId() === accountId ? config.sessions : undefined;\n };\n return {\n kind: config.kind ?? WHATSAPP_CHANNEL,\n handshake: () => null,\n verify: () => false,\n parse: parseEnvelope,\n send: async ({ accountId, to, content }) => {\n const session = sessionFor(accountId);\n if (!session) throw new ChannelSendFailure(\"NOT_CONNECTED\", \"no open WhatsApp Web session for this account\");\n return session.send(to, content);\n },\n fetchMedia: async ({ accountId, mediaId, maxBytes, timeoutMs }) => {\n const session = sessionFor(accountId);\n if (!session) throw new ChannelMediaFailure(\"NOT_CONNECTED\", \"no open WhatsApp Web session for this account\");\n return session.downloadMedia(mediaId, { maxBytes, ...(timeoutMs !== undefined ? { timeoutMs } : {}) });\n },\n policy: config.policy ?? OPEN_SEND_POLICY,\n };\n}\n","import type { BaileysAuthState, BaileysModule } from \"./baileys-port\";\n\n/**\n * WHERE A LINKED SESSION'S KEYS LIVE. The host's, never the package's.\n *\n * A Baileys session is a linked device: its auth state (the account's\n * identity and Signal keys) gives whoever holds it full access to the\n * account, every chat included. The package therefore writes NOTHING itself:\n * the host passes a store, and decides where it lives and how it is sealed\n * (an encrypted column, a secrets manager, a 0600 file on the owner's\n * machine). The package never logs a value, never puts one in an error.\n *\n * Values are opaque JSON text (Baileys' `BufferJSON`); keys are\n * `creds` and `<category>-<id>`.\n */\nexport interface AuthStateStore {\n read(key: string): Promise<string | null>;\n write(key: string, value: string): Promise<void>;\n remove(key: string): Promise<void>;\n /** Remove every key of this session. Optional: without it, a logout removes only `creds`, which already unlinks it. */\n clear?(): Promise<void>;\n}\n\n/** An in-memory store: for tests, and for a session that may be lost at restart (it must pair again). */\nexport function createMemoryAuthStateStore(): AuthStateStore & { keys(): string[]; clear(): Promise<void> } {\n const values = new Map<string, string>();\n return {\n read: async (key) => values.get(key) ?? null,\n write: async (key, value) => {\n values.set(key, value);\n },\n remove: async (key) => {\n values.delete(key);\n },\n keys: () => [...values.keys()],\n clear: async () => {\n values.clear();\n },\n };\n}\n\nconst CREDS_KEY = \"creds\";\nconst APP_STATE_SYNC_KEY = \"app-state-sync-key\";\n\n/**\n * Baileys' auth state over a host store: the same recipe as Baileys' own\n * `useMultiFileAuthState`, with the store in place of the folder. A store with\n * no creds yet starts a NEW device (the session pairs); `saveCreds` must run on\n * every `creds.update`.\n */\nexport async function loadAuthState(\n baileys: Pick<BaileysModule<unknown>, \"initAuthCreds\" | \"BufferJSON\" | \"proto\">,\n store: AuthStateStore,\n): Promise<{ state: BaileysAuthState; saveCreds: () => Promise<void>; isNew: boolean }> {\n const encode = (value: unknown): string => JSON.stringify(value, baileys.BufferJSON.replacer);\n const decode = (text: string | null): unknown => (text === null ? null : (JSON.parse(text, baileys.BufferJSON.reviver) as unknown));\n\n const stored = decode(await store.read(CREDS_KEY));\n const isNew = stored === null || typeof stored !== \"object\";\n const creds = isNew ? baileys.initAuthCreds() : (stored as object);\n const appStateKey = baileys.proto?.Message?.AppStateSyncKeyData;\n\n const state: BaileysAuthState = {\n creds,\n keys: {\n get: async (type, ids) => {\n const found: Record<string, unknown> = {};\n await Promise.all(\n ids.map(async (id) => {\n let value = decode(await store.read(`${type}-${id}`));\n if (type === APP_STATE_SYNC_KEY && value && appStateKey) value = appStateKey.fromObject(value);\n found[id] = value ?? undefined;\n }),\n );\n return found;\n },\n set: async (data) => {\n const writes = Object.entries(data).flatMap(([category, entries]) =>\n Object.entries(entries).map(([id, value]) => (value ? store.write(`${category}-${id}`, encode(value)) : store.remove(`${category}-${id}`))),\n );\n await Promise.all(writes);\n },\n },\n };\n return { state, saveCreds: () => store.write(CREDS_KEY, encode(creds)), isNew };\n}\n\n/** Forget a session's keys, after a logout: the next start pairs a NEW device. */\nexport async function clearAuthState(store: AuthStateStore): Promise<void> {\n if (store.clear) await store.clear();\n else await store.remove(CREDS_KEY);\n}\n","/**\n * The slice of Baileys (`baileys` / `@whiskeysockets/baileys`, v7) this layer\n * uses, typed STRUCTURALLY. The package never imports Baileys: the host passes\n * the module it installed (`import * as baileys from \"baileys\"`), so a host on\n * the official Cloud adapter never installs it, and the suites drive a fake.\n *\n * Every shape here is what Baileys 7.0.0 declares, narrowed to the fields read.\n * Anything wider is left `unknown` and read defensively.\n */\n\n/** A protobuf `Long`, as Baileys hands timestamps: a number, or `{ low, high }`. */\nexport type LongLike = number | string | { low: number; high: number; unsigned?: boolean } | null | undefined;\n\n/** `WAMessageKey`: Baileys' `proto.IMessageKey` plus the v7 LID alternates. */\nexport interface BaileysMessageKey {\n remoteJid?: string | null;\n /** The same chat's other address: the phone-number JID when `remoteJid` is a LID, and back. */\n remoteJidAlt?: string | null;\n fromMe?: boolean | null;\n id?: string | null;\n participant?: string | null;\n}\n\n/** `WAMessage` (`proto.IWebMessageInfo`), the fields read. `message` is the raw `proto.IMessage`. */\nexport interface BaileysMessage {\n key: BaileysMessageKey;\n message?: object | null;\n messageTimestamp?: number | { low: number; high: number } | null;\n pushName?: string | null;\n /** `proto.WebMessageInfo.Status`: 0 ERROR, 1 PENDING, 2 SERVER_ACK, 3 DELIVERY_ACK, 4 READ, 5 PLAYED. */\n status?: number | null;\n}\n\n/** One `messages.update` entry. */\nexport interface BaileysMessageUpdate {\n key: BaileysMessageKey;\n update: { status?: number | null } & Record<string, unknown>;\n}\n\n/** The close reason Baileys reports: a Boom, whose `output.statusCode` is the `DisconnectReason`. */\nexport interface BaileysDisconnect {\n error?: { output?: { statusCode?: number }; message?: string } | Error | null | undefined;\n date?: Date;\n}\n\nexport interface BaileysConnectionUpdate {\n connection?: \"open\" | \"connecting\" | \"close\";\n lastDisconnect?: BaileysDisconnect;\n qr?: string;\n}\n\n/** The events this layer listens to, by Baileys' own names. */\nexport interface BaileysEventMap<Msg extends BaileysMessage = BaileysMessage> {\n \"connection.update\": BaileysConnectionUpdate;\n \"creds.update\": Record<string, unknown>;\n \"messages.upsert\": { messages: Msg[]; type: \"notify\" | \"append\" | string };\n \"messages.update\": BaileysMessageUpdate[];\n}\n\n/** `SignalKeyStore`: keyed by category, then id. A null value deletes. */\nexport interface BaileysKeyStore {\n get(type: string, ids: string[]): Promise<Record<string, unknown>>;\n set(data: Record<string, Record<string, unknown>>): Promise<void>;\n}\n\n/** `AuthenticationState`, as this layer builds it. `creds` and every key are Baileys' own values, opaque here. */\nexport interface BaileysAuthState {\n creds: object;\n keys: BaileysKeyStore;\n}\n\n/** The socket `makeWASocket` returns, the members used. */\n/** `Msg` is Baileys' own `WAMessage`, inferred from the module: messages go back to Baileys as they came. */\nexport interface BaileysSocket<Msg extends BaileysMessage = BaileysMessage> {\n ev: {\n on<E extends keyof BaileysEventMap>(event: E, listener: (data: BaileysEventMap<Msg>[E]) => void): void;\n };\n /** The linked account, once open: `id` is `5511999999999:12@s.whatsapp.net`. */\n user?: { id?: string | null | undefined } | null | undefined;\n sendMessage(jid: string, content: { text: string }): Promise<Msg | undefined>;\n requestPairingCode(phoneNumber: string): Promise<string>;\n logout(msg?: string): Promise<void>;\n end(error: Error | undefined): Promise<void> | void;\n /** Asks the phone to re-upload expired media; passed to `downloadMediaMessage`. */\n updateMediaMessage?(message: Msg): Promise<Msg>;\n}\n\n/** Baileys' `ILogger`: pino satisfies it. */\nexport interface BaileysLogger {\n level: string;\n child(obj: Record<string, unknown>): BaileysLogger;\n trace(obj: unknown, msg?: string): void;\n debug(obj: unknown, msg?: string): void;\n info(obj: unknown, msg?: string): void;\n warn(obj: unknown, msg?: string): void;\n error(obj: unknown, msg?: string): void;\n}\n\n/** The members of the Baileys MODULE this layer calls. `import * as baileys from \"baileys\"` satisfies it. */\n/**\n * `Auth` is Baileys' own `AuthenticationState` and `Msg` its `WAMessage`, inferred from the module the\n * host passes. The layer builds it from the host's store, where the values are\n * Baileys' own, serialized by its `BufferJSON`.\n */\nexport interface BaileysModule<Auth = BaileysAuthState, Msg extends BaileysMessage = BaileysMessage> {\n makeWASocket(config: {\n auth: Auth;\n logger?: BaileysLogger;\n browser?: [string, string, string];\n markOnlineOnConnect?: boolean;\n syncFullHistory?: boolean;\n }): BaileysSocket<Msg>;\n initAuthCreds(): object;\n BufferJSON: {\n replacer(key: string, value: unknown): unknown;\n reviver(key: string, value: unknown): unknown;\n };\n downloadMediaMessage(\n message: Msg,\n type: \"buffer\",\n options: Record<string, unknown>,\n ctx?: { logger?: BaileysLogger; reuploadRequest?: (message: Msg) => Promise<Msg> },\n ): Promise<Uint8Array>;\n /** Optional: rebuilds an app-state sync key read back from storage (Baileys' own file store does). */\n proto?: { Message?: { AppStateSyncKeyData?: { fromObject(value: unknown): unknown } } };\n}\n\n/** Baileys' `DisconnectReason` values this layer acts on. */\nexport const DISCONNECT = {\n /** The phone unlinked this device, or the session was logged out: never reconnect. */\n loggedOut: 401,\n /** Another client took the session over. Reconnecting would fight it: stop. */\n connectionReplaced: 440,\n /** The account is banned or the session is unusable: stop. */\n forbidden: 403,\n /** Baileys asks for a fresh socket right after pairing: reconnect at once. */\n restartRequired: 515,\n} as const;\n\n/** The close's `DisconnectReason`, or null when Baileys gave none. */\nexport function disconnectCode(disconnect: BaileysDisconnect | undefined): number | null {\n const error = disconnect?.error;\n if (!error || typeof error !== \"object\" || !(\"output\" in error)) return null;\n const code = error.output?.statusCode;\n return typeof code === \"number\" ? code : null;\n}\n","import type { InboundContent, NormalizedEvent, ReceiptStatus, StatusEvent } from \"../core/types\";\nimport { DEFAULT_OPT_OUT_KEYWORDS, isOptOutText } from \"../whatsapp/opt-out\";\nimport type { BaileysMessage, BaileysMessageKey, BaileysMessageUpdate, LongLike } from \"./baileys-port\";\n\n/**\n * Baileys' socket events → the engine's normalized events: the SAME\n * `NormalizedEvent`s the Cloud webhook's parser produces, so the inbox, the\n * dedupe, the conversations and the retention cannot tell the transports apart.\n *\n * Read defensively: an unknown shape is skipped, never thrown on. What is\n * left out, on purpose:\n * - groups, broadcast lists, Status and channels (`@g.us`, `@broadcast`,\n * `@newsletter`): the engine's conversation is one contact;\n * - messages the account sent itself (`fromMe`): from another linked device,\n * or the echo of a send of ours, which the engine already recorded;\n * - history sync (`messages.upsert` of type `append`): only live messages;\n * - protocol messages (a deletion, an edit, a key distribution).\n */\n\ntype Json = Record<string, unknown>;\nconst isObject = (value: unknown): value is Json => typeof value === \"object\" && value !== null && !Array.isArray(value);\nconst text = (value: unknown): string | null => (typeof value === \"string\" && value.length > 0 ? value : null);\n\nconst PN_SUFFIX = \"@s.whatsapp.net\";\nconst LID_SUFFIX = \"@lid\";\n\n/** A JID's user part, without the device (`5511…:12@s.whatsapp.net` → `5511…`). */\nexport function jidUser(jid: string): string {\n const user = jid.slice(0, jid.indexOf(\"@\") >= 0 ? jid.indexOf(\"@\") : jid.length);\n const colon = user.indexOf(\":\");\n return colon >= 0 ? user.slice(0, colon) : user;\n}\n\n/**\n * The contact's address, as the engine stores it. A phone-number JID becomes\n * its digits (`5511987654321`), the same address the Cloud API's `wa_id` is.\n * A contact WhatsApp only names by a LID keeps the whole LID JID\n * (`123456@lid`): the send path routes it back as is. Null for anything that\n * is not one person.\n */\nexport function contactAddress(key: BaileysMessageKey): string | null {\n const candidates = [key.remoteJid, key.remoteJidAlt].filter((jid): jid is string => typeof jid === \"string\");\n const pn = candidates.find((jid) => jid.endsWith(PN_SUFFIX));\n if (pn) return jidUser(pn) || null;\n const lid = candidates.find((jid) => jid.endsWith(LID_SUFFIX));\n return lid ? `${jidUser(lid)}${LID_SUFFIX}` : null;\n}\n\n/** The JID a send goes to, for an address `contactAddress` produced (or plain digits). */\nexport function addressJid(address: string): string {\n if (address.includes(\"@\")) return address;\n const digits = address.replace(/\\D/g, \"\");\n return `${digits}${PN_SUFFIX}`;\n}\n\n/** A protobuf Long (a timestamp in seconds, a byte length) as a positive number, or null. */\nexport function longNumber(value: LongLike): number | null {\n if (typeof value === \"number\") return Number.isFinite(value) && value > 0 ? value : null;\n if (typeof value === \"string\") return longNumber(Number(value));\n if (isObject(value) && typeof value.low === \"number\" && typeof value.high === \"number\") {\n return longNumber(value.high * 2 ** 32 + (value.low >>> 0));\n }\n return null;\n}\n\n/** Wrappers whose inner `message` is the real content. */\nconst WRAPPERS = [\"ephemeralMessage\", \"viewOnceMessage\", \"viewOnceMessageV2\", \"viewOnceMessageV2Extension\", \"documentWithCaptionMessage\", \"editedMessage\"];\n/** Fields of a message that are never its content. */\nconst NOT_CONTENT = new Set([\"messageContextInfo\", \"senderKeyDistributionMessage\"]);\n/** Content that is not a message a person reads: skipped whole. */\nconst SKIPPED = new Set([\"protocolMessage\", \"reactionMessage\", \"pollUpdateMessage\", \"keepInChatMessage\"]);\n\n/** A message's real content, out of its ephemeral, view-once or edit wrappers. `{}` for anything else. */\nexport function unwrapMessage(message: unknown): Json {\n if (!isObject(message)) return {};\n for (const wrapper of WRAPPERS) {\n const inner = message[wrapper];\n if (isObject(inner) && isObject(inner.message)) return unwrapMessage(inner.message);\n }\n return message;\n}\n\ntype Reader = (body: unknown) => InboundContent | null;\n\nconst interactive = (replyId: unknown, title: unknown): InboundContent | null =>\n text(replyId) ? { kind: \"INTERACTIVE\", replyId: replyId as string, title: text(title) ?? \"\" } : null;\n\n/** How each content type a person reads is read. A type not listed is OTHER. */\nconst READERS: Readonly<Record<string, Reader>> = {\n conversation: (body) => (text(body) ? { kind: \"TEXT\", text: body as string } : null),\n extendedTextMessage: (body) => (isObject(body) && text(body.text) ? { kind: \"TEXT\", text: body.text as string } : null),\n buttonsResponseMessage: (body) => (isObject(body) ? interactive(body.selectedButtonId, body.selectedDisplayText) : null),\n templateButtonReplyMessage: (body) => (isObject(body) ? interactive(body.selectedId, body.selectedDisplayText) : null),\n listResponseMessage: (body) =>\n isObject(body) && isObject(body.singleSelectReply) ? interactive(body.singleSelectReply.selectedRowId, body.title) : null,\n // The media id is filled with the message id by the caller.\n audioMessage: (body) => (isObject(body) ? { kind: \"AUDIO\", mediaId: \"\", mimeType: text(body.mimetype) } : null),\n};\n\n/** The message's content, or null to skip it. */\nexport function contentOf(raw: unknown): InboundContent | null {\n const message = unwrapMessage(raw);\n const type = Object.keys(message).find((key) => !NOT_CONTENT.has(key) && message[key] !== null && message[key] !== undefined);\n if (!type || SKIPPED.has(type)) return null;\n const reader = READERS[type];\n return reader ? reader(message[type]) : { kind: \"OTHER\", channelType: type.replace(/Message$/, \"\") || type };\n}\n\nexport interface NormalizeOptions {\n /** The whole-message words that opt a contact out. Default: the Cloud adapter's. */\n optOutKeywords?: readonly string[];\n}\n\n/** One message → its inbound event, or null when it is not one a contact sent to this account. */\nfunction inboundEvent(accountId: string, message: BaileysMessage, keywords: readonly string[]): NormalizedEvent | null {\n if (!isObject(message) || !isObject(message.key) || message.key.fromMe) return null;\n const id = text(message.key.id);\n const contactId = contactAddress(message.key);\n const seconds = longNumber(message.messageTimestamp);\n const content = contentOf(message.message);\n if (!id || !contactId || seconds === null || !content) return null;\n return {\n type: \"message\",\n accountId,\n contactId,\n contactName: text(message.pushName),\n externalId: id,\n sentAt: new Date(seconds * 1000),\n // An audio's media id is the message's own id: the session keeps the message to download it.\n content: content.kind === \"AUDIO\" ? { ...content, mediaId: id } : content,\n optOut: content.kind === \"TEXT\" && isOptOutText(content.text, keywords),\n };\n}\n\n/** One live `messages.upsert` → inbound message events. `accountId` is the linked account's digits. */\nexport function normalizeUpsert(\n accountId: string,\n upsert: { messages: readonly BaileysMessage[]; type: string },\n options: NormalizeOptions = {},\n): NormalizedEvent[] {\n if (upsert.type !== \"notify\") return [];\n const keywords = options.optOutKeywords ?? DEFAULT_OPT_OUT_KEYWORDS;\n return upsert.messages.map((message) => inboundEvent(accountId, message, keywords)).filter((event): event is NormalizedEvent => event !== null);\n}\n\n/** `proto.WebMessageInfo.Status` → a receipt. PENDING (1) and unknown values are not receipts. */\nexport function receiptOf(status: unknown): ReceiptStatus | null {\n switch (status) {\n case 0:\n return \"FAILED\";\n case 2:\n return \"SENT\";\n case 3:\n return \"DELIVERED\";\n case 4:\n case 5:\n return \"READ\";\n default:\n return null;\n }\n}\n\n/** One `messages.update` → receipts for the messages this account sent. `at` is when the socket saw it. */\nexport function normalizeUpdates(accountId: string, updates: readonly BaileysMessageUpdate[], at: Date): StatusEvent[] {\n const events: StatusEvent[] = [];\n for (const entry of updates) {\n if (!isObject(entry) || !isObject(entry.key) || !entry.key.fromMe || !isObject(entry.update)) continue;\n const id = text(entry.key.id);\n const status = receiptOf(entry.update.status);\n if (!id || !status) continue;\n events.push({\n type: \"status\",\n accountId,\n externalId: id,\n status,\n at,\n contactId: contactAddress(entry.key),\n error: status === \"FAILED\" ? \"ERROR\" : null,\n callbackData: null,\n });\n }\n return events;\n}\n","import { ChannelMediaFailure, DEFAULT_MEDIA_TIMEOUT_MS, type ChannelMedia } from \"../core/channel\";\nimport type { BaileysLogger, BaileysMessage, BaileysModule } from \"./baileys-port\";\nimport { longNumber, unwrapMessage } from \"./normalize\";\n\n/**\n * Inbound audio, for `fetchMedia`. A Baileys media message is downloaded from\n * the message itself (its URL and media key), so the session keeps the most\n * recent audio messages IN MEMORY, by message id, and nothing else: the media\n * key never reaches the inbox or the host's database. After a restart an\n * older audio is `NOT_FOUND`.\n */\nexport class AudioCache<Msg extends BaileysMessage> {\n private readonly messages = new Map<string, Msg>();\n\n constructor(private readonly size: number) {}\n\n /** Keep `message` if it is an audio. The oldest is dropped past the size. */\n remember(message: Msg): void {\n const id = message.key?.id;\n if (!id || !audioOf(message)) return;\n this.messages.set(id, message);\n while (this.messages.size > this.size) this.messages.delete(this.messages.keys().next().value as string);\n }\n\n get(id: string): Msg | undefined {\n return this.messages.get(id);\n }\n}\n\n/** The audio content of a message, unwrapped, or null. */\nexport function audioOf(message: BaileysMessage): Record<string, unknown> | null {\n const audio = unwrapMessage(message.message).audioMessage;\n return typeof audio === \"object\" && audio !== null ? (audio as Record<string, unknown>) : null;\n}\n\nasync function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new ChannelMediaFailure(\"TIMEOUT\", `media download passed its ${ms} ms deadline`)), ms);\n });\n try {\n return await Promise.race([work, deadline]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction refuseOverCap(size: number | null, maxBytes: number, what: \"declares\" | \"is\"): void {\n if (size !== null && size > maxBytes) throw new ChannelMediaFailure(\"TOO_LARGE\", `the media ${what} ${size} bytes, over ${maxBytes}`);\n}\n\nexport interface DownloadAudioInput<Msg extends BaileysMessage> {\n baileys: Pick<BaileysModule<unknown, Msg>, \"downloadMediaMessage\">;\n message: Msg | undefined;\n maxBytes: number;\n timeoutMs?: number | undefined;\n logger?: BaileysLogger | undefined;\n reupload?: ((message: Msg) => Promise<Msg>) | undefined;\n}\n\n/** Download one cached audio into memory. Throws `ChannelMediaFailure`; never stores anything. */\nexport async function downloadAudio<Msg extends BaileysMessage>(input: DownloadAudioInput<Msg>): Promise<ChannelMedia> {\n const audio = input.message ? audioOf(input.message) : null;\n if (!input.message || !audio) throw new ChannelMediaFailure(\"NOT_FOUND\", \"no recent audio with this id in this session\");\n refuseOverCap(longNumber(audio.fileLength as number | null), input.maxBytes, \"declares\");\n const ctx = {\n ...(input.logger ? { logger: input.logger } : {}),\n ...(input.reupload ? { reuploadRequest: input.reupload } : {}),\n };\n const bytes = await withDeadline(input.baileys.downloadMediaMessage(input.message, \"buffer\", {}, ctx), input.timeoutMs ?? DEFAULT_MEDIA_TIMEOUT_MS).catch(\n (error: unknown) => {\n throw error instanceof ChannelMediaFailure ? error : new ChannelMediaFailure(\"DOWNLOAD_FAILED\", \"the media could not be downloaded\");\n },\n );\n refuseOverCap(bytes.length, input.maxBytes, \"is\");\n const mimeType = typeof audio.mimetype === \"string\" && audio.mimetype ? audio.mimetype : \"application/octet-stream\";\n return { bytes: new Uint8Array(bytes), mimeType, size: bytes.length };\n}\n","import { ChannelSendFailure, type ChannelMedia } from \"../core/channel\";\nimport type { NormalizedEvent, OutboundContent } from \"../core/types\";\nimport { clearAuthState, loadAuthState, type AuthStateStore } from \"./auth-state\";\nimport {\n DISCONNECT,\n disconnectCode,\n type BaileysAuthState,\n type BaileysConnectionUpdate,\n type BaileysLogger,\n type BaileysMessage,\n type BaileysModule,\n type BaileysSocket,\n} from \"./baileys-port\";\nimport { encodeEnvelope } from \"./envelope\";\nimport { AudioCache, downloadAudio } from \"./media\";\nimport { addressJid, jidUser, normalizeUpdates, normalizeUpsert } from \"./normalize\";\n\n/**\n * ONE linked WhatsApp account, over Baileys: the socket, its pairing, its\n * reconnects, and the bridge to the engine.\n *\n * Inbound, the session normalizes every live socket event and hands the host\n * a raw body (`deliver`) that the host stores through `engine.receive(channel,\n * rawBody)`, exactly as the webhook edge does for the Cloud API: the inbox,\n * the processing job and the reconciliation sweep are the same. Outbound,\n * the adapter sends through the session's socket.\n */\n\n/** Where the session stands. `qr` and `pairing-code` wait for the person to link the device on their phone. */\nexport type WhatsAppWebStatus =\n | { state: \"idle\" }\n | { state: \"connecting\" }\n /** Show `qr` as a QR code; WhatsApp › Linked devices › Link a device. It rotates: a new status replaces it. */\n | { state: \"qr\"; qr: string }\n /** Type `code` on the phone: WhatsApp › Linked devices › Link with phone number. */\n | { state: \"pairing-code\"; code: string }\n | { state: \"open\"; accountId: string }\n | { state: \"reconnecting\"; attempt: number; code: number | null }\n /** The phone unlinked this device (or WhatsApp logged it out). The keys were cleared: the next start pairs again. */\n | { state: \"logged-out\"; code: number | null }\n /** Stopped for good: another client took the session (440), the account is refused (403), or reconnects ran out. */\n | { state: \"failed\"; code: number | null; reason: \"replaced\" | \"forbidden\" | \"reconnects-exhausted\" | \"start-failed\" }\n | { state: \"stopped\" };\n\nexport interface WhatsAppWebSessionConfig<Auth = BaileysAuthState, Msg extends BaileysMessage = BaileysMessage> {\n /** The Baileys module the host installed: `import * as baileys from \"baileys\"`. */\n baileys: BaileysModule<Auth, Msg>;\n /** Where the linked device's keys live. The host's: see {@link AuthStateStore}. */\n authStore: AuthStateStore;\n /**\n * Store one inbound raw body: `(rawBody) => engine.receive(channel, rawBody)`.\n * Called in socket order, one at a time. A socket does not redeliver, so a\n * throw is reported through `onError` and that body is lost.\n */\n deliver(rawBody: string): Promise<unknown>;\n /** Every status change. Show the QR or the pairing code from here. */\n onStatus?(status: WhatsAppWebStatus): void;\n /** A failure the session could not hand to a caller: a delivery or a creds save. Never carries a key. */\n onError?(error: unknown, where: \"deliver\" | \"save-creds\" | \"pairing-code\"): void;\n /** Pair with a code typed on the phone instead of a QR: the account's number, digits with country code. */\n pairingPhoneNumber?: string;\n /** Opt-out words, as the Cloud adapter's `optOutKeywords`. */\n optOutKeywords?: readonly string[];\n /** A pino-compatible logger for Baileys. Default: Baileys' own. */\n logger?: BaileysLogger;\n /** How the linked device is named on the phone: `[client, browser, version]`. */\n browser?: [string, string, string];\n /** Reconnects after an unexpected close. Default 5 attempts, from 2 s, doubling. */\n reconnect?: { maxAttempts?: number; delayMs?: number };\n /** How many recent audio messages are kept in memory for `downloadMedia`. Default 200. */\n mediaCacheSize?: number;\n /** For tests. */\n now?(): Date;\n sleep?(ms: number): Promise<void>;\n}\n\nexport interface WhatsAppWebSession {\n /** Open the socket: resume the stored device, or pair a new one. Idempotent while running. */\n start(): Promise<void>;\n /** Close the socket and keep the keys: `start` resumes without pairing. */\n stop(): Promise<void>;\n /** Unlink this device on WhatsApp and clear its keys. */\n logout(): Promise<void>;\n status(): WhatsAppWebStatus;\n /** The linked account's digits once open (`5511987654321`), else null. */\n accountId(): string | null;\n /** Send one message. Throws `ChannelSendFailure`. */\n send(to: string, content: OutboundContent): Promise<{ externalId: string }>;\n /** Download a recent inbound audio by its media id (the message id). Throws `ChannelMediaFailure`. */\n downloadMedia(mediaId: string, options: { maxBytes: number; timeoutMs?: number }): Promise<ChannelMedia>;\n}\n\n/**\n * The text a personal account sends for an outbound message. Reply buttons\n * and lists are a Business API feature: here their choices become numbered\n * lines under the text, and the contact's answer arrives as TEXT.\n */\nexport function renderOutboundText(content: OutboundContent): string {\n if (content.kind === \"TEXT\") return content.text;\n if (content.kind === \"BUTTONS\") return [content.text, \"\", ...content.buttons.map((button, i) => `${i + 1}. ${button.title}`)].join(\"\\n\");\n let n = 0;\n const sections = content.sections.map((section) => [\n \"\",\n ...(section.title ? [`*${section.title}*`] : []),\n ...section.rows.map((row) => `${++n}. ${row.title}${row.description ? ` — ${row.description}` : \"\"}`),\n ]);\n return [content.text, ...sections.flat()].join(\"\\n\");\n}\n\nconst defaultSleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\n/** The close codes after which the session stops for good, and how it reports each. */\nconst TERMINAL: Readonly<Record<number, Extract<WhatsAppWebStatus, { state: \"failed\" }>[\"reason\"]>> = {\n [DISCONNECT.connectionReplaced]: \"replaced\",\n [DISCONNECT.forbidden]: \"forbidden\",\n};\n\nclass BaileysSession<Auth, Msg extends BaileysMessage> implements WhatsAppWebSession {\n private socket: BaileysSocket<Msg> | null = null;\n private current: WhatsAppWebStatus = { state: \"idle\" };\n private account: string | null = null;\n private attempts = 0;\n private stopping = false;\n private pairingRequested = false;\n private deliveries: Promise<void> = Promise.resolve();\n private readonly audio: AudioCache<Msg>;\n\n constructor(private readonly config: WhatsAppWebSessionConfig<Auth, Msg>) {\n this.audio = new AudioCache(config.mediaCacheSize ?? 200);\n }\n\n status = (): WhatsAppWebStatus => this.current;\n accountId = (): string | null => this.account;\n\n async start(): Promise<void> {\n if (this.socket) return;\n this.stopping = false;\n this.attempts = 0;\n this.pairingRequested = false;\n try {\n await this.open();\n } catch (error) {\n this.socket = null;\n this.setStatus({ state: \"failed\", code: null, reason: \"start-failed\" });\n throw error;\n }\n }\n\n async stop(): Promise<void> {\n const sock = this.detach();\n if (sock) await sock.end(undefined);\n this.setStatus({ state: \"stopped\" });\n }\n\n async logout(): Promise<void> {\n const sock = this.detach();\n if (sock) await sock.logout();\n await clearAuthState(this.config.authStore);\n this.setStatus({ state: \"logged-out\", code: null });\n }\n\n async send(to: string, content: OutboundContent): Promise<{ externalId: string }> {\n const sock = this.socket;\n if (!sock || this.current.state !== \"open\") throw new ChannelSendFailure(\"NOT_CONNECTED\", \"the WhatsApp Web session is not open\");\n const sent = await sock.sendMessage(addressJid(to), { text: renderOutboundText(content) }).catch((error: unknown) => {\n const code = disconnectCode({ error: error as Error });\n throw new ChannelSendFailure(code === null ? \"SEND_FAILED\" : String(code), \"the WhatsApp Web socket refused the send\");\n });\n const externalId = sent?.key?.id;\n if (!externalId) throw new ChannelSendFailure(\"NO_MESSAGE_ID\", \"the WhatsApp Web socket returned no message id\");\n return { externalId };\n }\n\n downloadMedia(mediaId: string, options: { maxBytes: number; timeoutMs?: number }): Promise<ChannelMedia> {\n const sock = this.socket;\n return downloadAudio({\n baileys: this.config.baileys,\n message: this.audio.get(mediaId),\n maxBytes: options.maxBytes,\n timeoutMs: options.timeoutMs,\n logger: this.config.logger,\n reupload: sock?.updateMediaMessage ? (message: Msg) => sock.updateMediaMessage!(message) : undefined,\n });\n }\n\n // ── The socket ──────────────────────────────────────────────────────────\n\n private detach(): BaileysSocket<Msg> | null {\n this.stopping = true;\n const sock = this.socket;\n this.socket = null;\n this.account = null;\n return sock;\n }\n\n private setStatus(status: WhatsAppWebStatus): void {\n this.current = status;\n this.config.onStatus?.(status);\n }\n\n private async open(): Promise<void> {\n this.setStatus({ state: \"connecting\" });\n const { state, saveCreds } = await loadAuthState(this.config.baileys, this.config.authStore);\n const sock = this.config.baileys.makeWASocket({\n // The ONE boundary cast: the store holds Baileys' own values, which its key store types per category.\n auth: state as Auth,\n markOnlineOnConnect: false,\n syncFullHistory: false,\n ...(this.config.logger ? { logger: this.config.logger } : {}),\n ...(this.config.browser ? { browser: this.config.browser } : {}),\n });\n this.socket = sock;\n sock.ev.on(\"creds.update\", () => {\n saveCreds().catch((error: unknown) => this.config.onError?.(error, \"save-creds\"));\n });\n sock.ev.on(\"connection.update\", (update) => {\n if (sock === this.socket) void this.onConnection(sock, update);\n });\n sock.ev.on(\"messages.upsert\", (upsert) => {\n const account = this.linked(sock);\n if (!account) return;\n if (upsert.type === \"notify\") upsert.messages.forEach((message) => this.audio.remember(message));\n this.deliver(normalizeUpsert(account, upsert, this.config.optOutKeywords ? { optOutKeywords: this.config.optOutKeywords } : {}));\n });\n sock.ev.on(\"messages.update\", (updates) => {\n const account = this.linked(sock);\n if (account) this.deliver(normalizeUpdates(account, updates, (this.config.now ?? (() => new Date()))()));\n });\n }\n\n /** The account a CURRENT socket is linked to: from the open event, or its own user while still opening. */\n private linked(sock: BaileysSocket<Msg>): string | null {\n if (sock !== this.socket) return null;\n return this.account ?? (sock.user?.id ? jidUser(sock.user.id) : null);\n }\n\n /** Hand one body to the host, after every earlier one: a socket's order is kept. */\n private deliver(events: NormalizedEvent[]): void {\n if (events.length === 0) return;\n const body = encodeEnvelope(events);\n this.deliveries = this.deliveries.then(() =>\n this.config.deliver(body).then(\n () => undefined,\n (error: unknown) => this.config.onError?.(error, \"deliver\"),\n ),\n );\n }\n\n private async onConnection(sock: BaileysSocket<Msg>, update: BaileysConnectionUpdate): Promise<void> {\n if (update.qr) await this.onQr(sock, update.qr);\n if (update.connection === \"open\") {\n this.attempts = 0;\n this.account = sock.user?.id ? jidUser(sock.user.id) : null;\n this.setStatus(this.account ? { state: \"open\", accountId: this.account } : { state: \"connecting\" });\n } else if (update.connection === \"close\") {\n await this.onClose(disconnectCode(update.lastDisconnect));\n }\n }\n\n private async onQr(sock: BaileysSocket<Msg>, qr: string): Promise<void> {\n const phone = this.config.pairingPhoneNumber;\n if (!phone) return this.setStatus({ state: \"qr\", qr });\n if (this.pairingRequested) return;\n this.pairingRequested = true;\n try {\n this.setStatus({ state: \"pairing-code\", code: await sock.requestPairingCode(phone.replace(/\\D/g, \"\")) });\n } catch (error) {\n this.pairingRequested = false;\n this.config.onError?.(error, \"pairing-code\");\n }\n }\n\n private async onClose(code: number | null): Promise<void> {\n this.socket = null;\n this.account = null;\n if (this.stopping) return this.setStatus({ state: \"stopped\" });\n if (code === DISCONNECT.loggedOut) {\n await clearAuthState(this.config.authStore);\n return this.setStatus({ state: \"logged-out\", code });\n }\n const terminal = code === null ? undefined : TERMINAL[code];\n if (terminal) return this.setStatus({ state: \"failed\", code, reason: terminal });\n if (code !== DISCONNECT.restartRequired && !(await this.backOff(code))) return;\n await this.open();\n }\n\n /** Wait before a reconnect; false when the attempts ran out or the session was stopped meanwhile. */\n private async backOff(code: number | null): Promise<boolean> {\n const maxAttempts = this.config.reconnect?.maxAttempts ?? 5;\n this.attempts += 1;\n if (this.attempts > maxAttempts) {\n this.setStatus({ state: \"failed\", code, reason: \"reconnects-exhausted\" });\n return false;\n }\n this.setStatus({ state: \"reconnecting\", attempt: this.attempts, code });\n await (this.config.sleep ?? defaultSleep)((this.config.reconnect?.delayMs ?? 2_000) * 2 ** (this.attempts - 1));\n if (!this.stopping) return true;\n this.setStatus({ state: \"stopped\" });\n return false;\n }\n}\n\n/** One linked WhatsApp account over Baileys. Nothing connects until `start()`. */\nexport function createWhatsAppWebSession<Auth, Msg extends BaileysMessage>(config: WhatsAppWebSessionConfig<Auth, Msg>): WhatsAppWebSession {\n return new BaileysSession(config);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAaO,IAAM,kBAAkB;AAExB,SAAS,eAAe,QAA4C;AACzE,SAAO,KAAK,UAAU,EAAE,QAAQ,iBAAiB,OAAO,CAAC;AAC3D;AAFgB;AAKhB,IAAM,WAAW,wBAAC,UAAkC,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,GAAtG;AACjB,IAAM,MAAM,wBAAC,UAAmC,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ,MAA5F;AACZ,IAAM,YAAY,wBAAC,UAAmC,OAAO,UAAU,WAAW,QAAQ,MAAxE;AAClB,IAAM,OAAO,wBAAC,UAAgC;AAC5C,QAAM,SAAS,OAAO,UAAU,WAAW,IAAI,KAAK,KAAK,IAAI;AAC7D,SAAO,UAAU,OAAO,SAAS,OAAO,QAAQ,CAAC,IAAI,SAAS;AAChE,GAHa;AAKb,IAAM,WAAqC,CAAC,QAAQ,aAAa,QAAQ,QAAQ;AAEjF,IAAM,UAA4E;AAAA,EAChF,MAAM,wBAAC,UAAW,OAAO,MAAM,SAAS,WAAW,EAAE,MAAM,QAAQ,MAAM,MAAM,KAAK,IAAI,MAAlF;AAAA,EACN,aAAa,wBAAC,UAAW,IAAI,MAAM,OAAO,IAAI,EAAE,MAAM,eAAe,SAAS,MAAM,SAAmB,OAAO,UAAU,MAAM,KAAK,KAAK,GAAG,IAAI,MAAlI;AAAA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C;AAAA,EACF;AAAA,EAEA,MAAc,QAAQ,MAAoC;AACxD,SAAK,SAAS;AACd,SAAK,UAAU;AACf,QAAI,KAAK,SAAU,QAAO,KAAK,UAAU,EAAE,OAAO,UAAU,CAAC;AAC7D,QAAI,SAAS,WAAW,WAAW;AACjC,YAAM,eAAe,KAAK,OAAO,SAAS;AAC1C,aAAO,KAAK,UAAU,EAAE,OAAO,cAAc,KAAK,CAAC;AAAA,IACrD;AACA,UAAM,WAAW,SAAS,OAAO,SAAY,SAAS,IAAI;AAC1D,QAAI,SAAU,QAAO,KAAK,UAAU,EAAE,OAAO,UAAU,MAAM,QAAQ,SAAS,CAAC;AAC/E,QAAI,SAAS,WAAW,mBAAmB,CAAE,MAAM,KAAK,QAAQ,IAAI,EAAI;AACxE,UAAM,KAAK,KAAK;AAAA,EAClB;AAAA;AAAA,EAGA,MAAc,QAAQ,MAAuC;AAC3D,UAAM,cAAc,KAAK,OAAO,WAAW,eAAe;AAC1D,SAAK,YAAY;AACjB,QAAI,KAAK,WAAW,aAAa;AAC/B,WAAK,UAAU,EAAE,OAAO,UAAU,MAAM,QAAQ,uBAAuB,CAAC;AACxE,aAAO;AAAA,IACT;AACA,SAAK,UAAU,EAAE,OAAO,gBAAgB,SAAS,KAAK,UAAU,KAAK,CAAC;AACtE,WAAO,KAAK,OAAO,SAAS,eAAe,KAAK,OAAO,WAAW,WAAW,OAAS,MAAM,KAAK,WAAW,EAAE;AAC9G,QAAI,CAAC,KAAK,SAAU,QAAO;AAC3B,SAAK,UAAU,EAAE,OAAO,UAAU,CAAC;AACnC,WAAO;AAAA,EACT;AACF;AAGO,SAAS,yBAA2D,QAAiE;AAC1I,SAAO,IAAI,eAAe,MAAM;AAClC;AAFgB;","names":["content","text","isObject","content","event","content"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/messaging",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "A channel-agnostic conversational messaging connector: channel connections with sealed credentials, a durable inbox of raw webhook deliveries, conversations with an owner state and a structured summary, messages with delivery statuses, an opt-out, a per-channel send policy and a text-retention sweep, behind a channel adapter port. WhatsApp Cloud is the first adapter (./whatsapp), with its signature check, payload parser, Graph sender and Embedded Signup helpers. Framework-neutral webhook routes (./server), dep-free job blueprints and the package-owned Prisma partial + migrations.",
@@ -13,6 +13,10 @@
13
13
  "types": "./dist/whatsapp/index.d.ts",
14
14
  "default": "./dist/whatsapp/index.js"
15
15
  },
16
+ "./whatsapp-web": {
17
+ "types": "./dist/whatsapp-web/index.d.ts",
18
+ "default": "./dist/whatsapp-web/index.js"
19
+ },
16
20
  "./inbound-guard": {
17
21
  "types": "./dist/inbound-guard/index.d.ts",
18
22
  "default": "./dist/inbound-guard/index.js"
@@ -0,0 +1,62 @@
1
+ import { ChannelMediaFailure, ChannelSendFailure, OPEN_SEND_POLICY, type ChannelAdapter, type SendPolicy } from "../core/channel";
2
+ import { WHATSAPP_CHANNEL } from "../whatsapp";
3
+ import { parseEnvelope } from "./envelope";
4
+ import type { WhatsAppWebSession } from "./session";
5
+
6
+ export interface WhatsAppWebAdapterConfig {
7
+ /**
8
+ * The session that serves an account: one session, or a lookup by the
9
+ * connection's account id (the linked number's digits). A session serves
10
+ * only the account it is linked to.
11
+ */
12
+ sessions: WhatsAppWebSession | ((accountId: string) => WhatsAppWebSession | undefined);
13
+ /**
14
+ * The channel key. Default `whatsapp`, the Cloud adapter's: a host switches a
15
+ * number between the two transports by mounting one adapter or the other,
16
+ * and its connections and conversations stay where they are. Give another
17
+ * key (`whatsapp-web`) to run both side by side.
18
+ */
19
+ kind?: string;
20
+ /**
21
+ * When free-form sends are allowed. Default: always. A personal account has
22
+ * no service window; that window is a rule of the Business API.
23
+ */
24
+ policy?: SendPolicy;
25
+ }
26
+
27
+ /**
28
+ * The WhatsApp Web adapter: the same `ChannelAdapter` as the Cloud one, over
29
+ * a Baileys session instead of the Graph API.
30
+ *
31
+ * - `handshake` and `verify`: there is no webhook. The verify FAILS CLOSED,
32
+ * so the webhook route refuses any POST to this channel: inbound arrives
33
+ * only from the session's own socket, through `engine.receive`.
34
+ * - `parse` reads the session's envelope (normalized events, never Baileys'
35
+ * raw objects).
36
+ * - `send` and `fetchMedia` go through the session. The connection's
37
+ * credential is not used: the linked device's keys live in the session's
38
+ * auth store.
39
+ */
40
+ export function createWhatsAppWebAdapter(config: WhatsAppWebAdapterConfig): ChannelAdapter {
41
+ const sessionFor = (accountId: string): WhatsAppWebSession | undefined => {
42
+ if (typeof config.sessions === "function") return config.sessions(accountId);
43
+ return config.sessions.accountId() === accountId ? config.sessions : undefined;
44
+ };
45
+ return {
46
+ kind: config.kind ?? WHATSAPP_CHANNEL,
47
+ handshake: () => null,
48
+ verify: () => false,
49
+ parse: parseEnvelope,
50
+ send: async ({ accountId, to, content }) => {
51
+ const session = sessionFor(accountId);
52
+ if (!session) throw new ChannelSendFailure("NOT_CONNECTED", "no open WhatsApp Web session for this account");
53
+ return session.send(to, content);
54
+ },
55
+ fetchMedia: async ({ accountId, mediaId, maxBytes, timeoutMs }) => {
56
+ const session = sessionFor(accountId);
57
+ if (!session) throw new ChannelMediaFailure("NOT_CONNECTED", "no open WhatsApp Web session for this account");
58
+ return session.downloadMedia(mediaId, { maxBytes, ...(timeoutMs !== undefined ? { timeoutMs } : {}) });
59
+ },
60
+ policy: config.policy ?? OPEN_SEND_POLICY,
61
+ };
62
+ }
@@ -0,0 +1,92 @@
1
+ import type { BaileysAuthState, BaileysModule } from "./baileys-port";
2
+
3
+ /**
4
+ * WHERE A LINKED SESSION'S KEYS LIVE. The host's, never the package's.
5
+ *
6
+ * A Baileys session is a linked device: its auth state (the account's
7
+ * identity and Signal keys) gives whoever holds it full access to the
8
+ * account, every chat included. The package therefore writes NOTHING itself:
9
+ * the host passes a store, and decides where it lives and how it is sealed
10
+ * (an encrypted column, a secrets manager, a 0600 file on the owner's
11
+ * machine). The package never logs a value, never puts one in an error.
12
+ *
13
+ * Values are opaque JSON text (Baileys' `BufferJSON`); keys are
14
+ * `creds` and `<category>-<id>`.
15
+ */
16
+ export interface AuthStateStore {
17
+ read(key: string): Promise<string | null>;
18
+ write(key: string, value: string): Promise<void>;
19
+ remove(key: string): Promise<void>;
20
+ /** Remove every key of this session. Optional: without it, a logout removes only `creds`, which already unlinks it. */
21
+ clear?(): Promise<void>;
22
+ }
23
+
24
+ /** An in-memory store: for tests, and for a session that may be lost at restart (it must pair again). */
25
+ export function createMemoryAuthStateStore(): AuthStateStore & { keys(): string[]; clear(): Promise<void> } {
26
+ const values = new Map<string, string>();
27
+ return {
28
+ read: async (key) => values.get(key) ?? null,
29
+ write: async (key, value) => {
30
+ values.set(key, value);
31
+ },
32
+ remove: async (key) => {
33
+ values.delete(key);
34
+ },
35
+ keys: () => [...values.keys()],
36
+ clear: async () => {
37
+ values.clear();
38
+ },
39
+ };
40
+ }
41
+
42
+ const CREDS_KEY = "creds";
43
+ const APP_STATE_SYNC_KEY = "app-state-sync-key";
44
+
45
+ /**
46
+ * Baileys' auth state over a host store: the same recipe as Baileys' own
47
+ * `useMultiFileAuthState`, with the store in place of the folder. A store with
48
+ * no creds yet starts a NEW device (the session pairs); `saveCreds` must run on
49
+ * every `creds.update`.
50
+ */
51
+ export async function loadAuthState(
52
+ baileys: Pick<BaileysModule<unknown>, "initAuthCreds" | "BufferJSON" | "proto">,
53
+ store: AuthStateStore,
54
+ ): Promise<{ state: BaileysAuthState; saveCreds: () => Promise<void>; isNew: boolean }> {
55
+ const encode = (value: unknown): string => JSON.stringify(value, baileys.BufferJSON.replacer);
56
+ const decode = (text: string | null): unknown => (text === null ? null : (JSON.parse(text, baileys.BufferJSON.reviver) as unknown));
57
+
58
+ const stored = decode(await store.read(CREDS_KEY));
59
+ const isNew = stored === null || typeof stored !== "object";
60
+ const creds = isNew ? baileys.initAuthCreds() : (stored as object);
61
+ const appStateKey = baileys.proto?.Message?.AppStateSyncKeyData;
62
+
63
+ const state: BaileysAuthState = {
64
+ creds,
65
+ keys: {
66
+ get: async (type, ids) => {
67
+ const found: Record<string, unknown> = {};
68
+ await Promise.all(
69
+ ids.map(async (id) => {
70
+ let value = decode(await store.read(`${type}-${id}`));
71
+ if (type === APP_STATE_SYNC_KEY && value && appStateKey) value = appStateKey.fromObject(value);
72
+ found[id] = value ?? undefined;
73
+ }),
74
+ );
75
+ return found;
76
+ },
77
+ set: async (data) => {
78
+ const writes = Object.entries(data).flatMap(([category, entries]) =>
79
+ Object.entries(entries).map(([id, value]) => (value ? store.write(`${category}-${id}`, encode(value)) : store.remove(`${category}-${id}`))),
80
+ );
81
+ await Promise.all(writes);
82
+ },
83
+ },
84
+ };
85
+ return { state, saveCreds: () => store.write(CREDS_KEY, encode(creds)), isNew };
86
+ }
87
+
88
+ /** Forget a session's keys, after a logout: the next start pairs a NEW device. */
89
+ export async function clearAuthState(store: AuthStateStore): Promise<void> {
90
+ if (store.clear) await store.clear();
91
+ else await store.remove(CREDS_KEY);
92
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * The slice of Baileys (`baileys` / `@whiskeysockets/baileys`, v7) this layer
3
+ * uses, typed STRUCTURALLY. The package never imports Baileys: the host passes
4
+ * the module it installed (`import * as baileys from "baileys"`), so a host on
5
+ * the official Cloud adapter never installs it, and the suites drive a fake.
6
+ *
7
+ * Every shape here is what Baileys 7.0.0 declares, narrowed to the fields read.
8
+ * Anything wider is left `unknown` and read defensively.
9
+ */
10
+
11
+ /** A protobuf `Long`, as Baileys hands timestamps: a number, or `{ low, high }`. */
12
+ export type LongLike = number | string | { low: number; high: number; unsigned?: boolean } | null | undefined;
13
+
14
+ /** `WAMessageKey`: Baileys' `proto.IMessageKey` plus the v7 LID alternates. */
15
+ export interface BaileysMessageKey {
16
+ remoteJid?: string | null;
17
+ /** The same chat's other address: the phone-number JID when `remoteJid` is a LID, and back. */
18
+ remoteJidAlt?: string | null;
19
+ fromMe?: boolean | null;
20
+ id?: string | null;
21
+ participant?: string | null;
22
+ }
23
+
24
+ /** `WAMessage` (`proto.IWebMessageInfo`), the fields read. `message` is the raw `proto.IMessage`. */
25
+ export interface BaileysMessage {
26
+ key: BaileysMessageKey;
27
+ message?: object | null;
28
+ messageTimestamp?: number | { low: number; high: number } | null;
29
+ pushName?: string | null;
30
+ /** `proto.WebMessageInfo.Status`: 0 ERROR, 1 PENDING, 2 SERVER_ACK, 3 DELIVERY_ACK, 4 READ, 5 PLAYED. */
31
+ status?: number | null;
32
+ }
33
+
34
+ /** One `messages.update` entry. */
35
+ export interface BaileysMessageUpdate {
36
+ key: BaileysMessageKey;
37
+ update: { status?: number | null } & Record<string, unknown>;
38
+ }
39
+
40
+ /** The close reason Baileys reports: a Boom, whose `output.statusCode` is the `DisconnectReason`. */
41
+ export interface BaileysDisconnect {
42
+ error?: { output?: { statusCode?: number }; message?: string } | Error | null | undefined;
43
+ date?: Date;
44
+ }
45
+
46
+ export interface BaileysConnectionUpdate {
47
+ connection?: "open" | "connecting" | "close";
48
+ lastDisconnect?: BaileysDisconnect;
49
+ qr?: string;
50
+ }
51
+
52
+ /** The events this layer listens to, by Baileys' own names. */
53
+ export interface BaileysEventMap<Msg extends BaileysMessage = BaileysMessage> {
54
+ "connection.update": BaileysConnectionUpdate;
55
+ "creds.update": Record<string, unknown>;
56
+ "messages.upsert": { messages: Msg[]; type: "notify" | "append" | string };
57
+ "messages.update": BaileysMessageUpdate[];
58
+ }
59
+
60
+ /** `SignalKeyStore`: keyed by category, then id. A null value deletes. */
61
+ export interface BaileysKeyStore {
62
+ get(type: string, ids: string[]): Promise<Record<string, unknown>>;
63
+ set(data: Record<string, Record<string, unknown>>): Promise<void>;
64
+ }
65
+
66
+ /** `AuthenticationState`, as this layer builds it. `creds` and every key are Baileys' own values, opaque here. */
67
+ export interface BaileysAuthState {
68
+ creds: object;
69
+ keys: BaileysKeyStore;
70
+ }
71
+
72
+ /** The socket `makeWASocket` returns, the members used. */
73
+ /** `Msg` is Baileys' own `WAMessage`, inferred from the module: messages go back to Baileys as they came. */
74
+ export interface BaileysSocket<Msg extends BaileysMessage = BaileysMessage> {
75
+ ev: {
76
+ on<E extends keyof BaileysEventMap>(event: E, listener: (data: BaileysEventMap<Msg>[E]) => void): void;
77
+ };
78
+ /** The linked account, once open: `id` is `5511999999999:12@s.whatsapp.net`. */
79
+ user?: { id?: string | null | undefined } | null | undefined;
80
+ sendMessage(jid: string, content: { text: string }): Promise<Msg | undefined>;
81
+ requestPairingCode(phoneNumber: string): Promise<string>;
82
+ logout(msg?: string): Promise<void>;
83
+ end(error: Error | undefined): Promise<void> | void;
84
+ /** Asks the phone to re-upload expired media; passed to `downloadMediaMessage`. */
85
+ updateMediaMessage?(message: Msg): Promise<Msg>;
86
+ }
87
+
88
+ /** Baileys' `ILogger`: pino satisfies it. */
89
+ export interface BaileysLogger {
90
+ level: string;
91
+ child(obj: Record<string, unknown>): BaileysLogger;
92
+ trace(obj: unknown, msg?: string): void;
93
+ debug(obj: unknown, msg?: string): void;
94
+ info(obj: unknown, msg?: string): void;
95
+ warn(obj: unknown, msg?: string): void;
96
+ error(obj: unknown, msg?: string): void;
97
+ }
98
+
99
+ /** The members of the Baileys MODULE this layer calls. `import * as baileys from "baileys"` satisfies it. */
100
+ /**
101
+ * `Auth` is Baileys' own `AuthenticationState` and `Msg` its `WAMessage`, inferred from the module the
102
+ * host passes. The layer builds it from the host's store, where the values are
103
+ * Baileys' own, serialized by its `BufferJSON`.
104
+ */
105
+ export interface BaileysModule<Auth = BaileysAuthState, Msg extends BaileysMessage = BaileysMessage> {
106
+ makeWASocket(config: {
107
+ auth: Auth;
108
+ logger?: BaileysLogger;
109
+ browser?: [string, string, string];
110
+ markOnlineOnConnect?: boolean;
111
+ syncFullHistory?: boolean;
112
+ }): BaileysSocket<Msg>;
113
+ initAuthCreds(): object;
114
+ BufferJSON: {
115
+ replacer(key: string, value: unknown): unknown;
116
+ reviver(key: string, value: unknown): unknown;
117
+ };
118
+ downloadMediaMessage(
119
+ message: Msg,
120
+ type: "buffer",
121
+ options: Record<string, unknown>,
122
+ ctx?: { logger?: BaileysLogger; reuploadRequest?: (message: Msg) => Promise<Msg> },
123
+ ): Promise<Uint8Array>;
124
+ /** Optional: rebuilds an app-state sync key read back from storage (Baileys' own file store does). */
125
+ proto?: { Message?: { AppStateSyncKeyData?: { fromObject(value: unknown): unknown } } };
126
+ }
127
+
128
+ /** Baileys' `DisconnectReason` values this layer acts on. */
129
+ export const DISCONNECT = {
130
+ /** The phone unlinked this device, or the session was logged out: never reconnect. */
131
+ loggedOut: 401,
132
+ /** Another client took the session over. Reconnecting would fight it: stop. */
133
+ connectionReplaced: 440,
134
+ /** The account is banned or the session is unusable: stop. */
135
+ forbidden: 403,
136
+ /** Baileys asks for a fresh socket right after pairing: reconnect at once. */
137
+ restartRequired: 515,
138
+ } as const;
139
+
140
+ /** The close's `DisconnectReason`, or null when Baileys gave none. */
141
+ export function disconnectCode(disconnect: BaileysDisconnect | undefined): number | null {
142
+ const error = disconnect?.error;
143
+ if (!error || typeof error !== "object" || !("output" in error)) return null;
144
+ const code = error.output?.statusCode;
145
+ return typeof code === "number" ? code : null;
146
+ }
@@ -0,0 +1,87 @@
1
+ import type { InboundContent, NormalizedEvent, ReceiptStatus } from "../core/types";
2
+
3
+ /**
4
+ * The raw body a session hands the engine's inbox.
5
+ *
6
+ * The inbox stores every delivery raw before processing it, and re-parses it
7
+ * on a retry. A socket has no HTTP body, so the session writes one: its
8
+ * already-normalized events, as JSON. Never Baileys' own message objects —
9
+ * they carry media keys and the full protobuf, and the inbox keeps what it
10
+ * is given.
11
+ *
12
+ * `{ "format": "whatsapp-web/1", "events": [...] }`, dates as ISO strings.
13
+ */
14
+ export const ENVELOPE_FORMAT = "whatsapp-web/1";
15
+
16
+ export function encodeEnvelope(events: readonly NormalizedEvent[]): string {
17
+ return JSON.stringify({ format: ENVELOPE_FORMAT, events });
18
+ }
19
+
20
+ type Json = Record<string, unknown>;
21
+ const isObject = (value: unknown): value is Json => typeof value === "object" && value !== null && !Array.isArray(value);
22
+ const str = (value: unknown): string | null => (typeof value === "string" && value.length > 0 ? value : null);
23
+ const strOrNull = (value: unknown): string | null => (typeof value === "string" ? value : null);
24
+ const date = (value: unknown): Date | null => {
25
+ const parsed = typeof value === "string" ? new Date(value) : null;
26
+ return parsed && Number.isFinite(parsed.getTime()) ? parsed : null;
27
+ };
28
+
29
+ const RECEIPTS: readonly ReceiptStatus[] = ["SENT", "DELIVERED", "READ", "FAILED"];
30
+
31
+ const CONTENT: Readonly<Record<string, (value: Json) => InboundContent | null>> = {
32
+ TEXT: (value) => (typeof value.text === "string" ? { kind: "TEXT", text: value.text } : null),
33
+ INTERACTIVE: (value) => (str(value.replyId) ? { kind: "INTERACTIVE", replyId: value.replyId as string, title: strOrNull(value.title) ?? "" } : null),
34
+ AUDIO: (value) => (str(value.mediaId) ? { kind: "AUDIO", mediaId: value.mediaId as string, mimeType: strOrNull(value.mimeType) } : null),
35
+ OTHER: (value) => (str(value.channelType) ? { kind: "OTHER", channelType: value.channelType as string } : null),
36
+ };
37
+
38
+ function content(value: unknown): InboundContent | null {
39
+ if (!isObject(value) || typeof value.kind !== "string") return null;
40
+ return CONTENT[value.kind]?.(value) ?? null;
41
+ }
42
+
43
+ function messageEvent(value: Json, accountId: string): NormalizedEvent | null {
44
+ const contactId = str(value.contactId);
45
+ const externalId = str(value.externalId);
46
+ const sentAt = date(value.sentAt);
47
+ const body = content(value.content);
48
+ if (!contactId || !externalId || !sentAt || !body) return null;
49
+ return { type: "message", accountId, contactId, contactName: strOrNull(value.contactName), externalId, sentAt, content: body, optOut: value.optOut === true };
50
+ }
51
+
52
+ function statusEvent(value: Json, accountId: string): NormalizedEvent | null {
53
+ const externalId = str(value.externalId);
54
+ const at = date(value.at);
55
+ const status = RECEIPTS.find((receipt) => receipt === value.status);
56
+ if (!externalId || !at || !status) return null;
57
+ const optional = { contactId: strOrNull(value.contactId), error: strOrNull(value.error), callbackData: strOrNull(value.callbackData) };
58
+ return { type: "status", accountId, externalId, status, at, ...optional };
59
+ }
60
+
61
+ function optOutEvent(value: Json, accountId: string): NormalizedEvent | null {
62
+ const contactId = str(value.contactId);
63
+ const at = date(value.at);
64
+ return contactId && at ? { type: "opt_out", accountId, contactId, at } : null;
65
+ }
66
+
67
+ const EVENTS: Readonly<Record<string, (value: Json, accountId: string) => NormalizedEvent | null>> = {
68
+ message: messageEvent,
69
+ status: statusEvent,
70
+ opt_out: optOutEvent,
71
+ };
72
+
73
+ function event(value: unknown): NormalizedEvent | null {
74
+ if (!isObject(value) || typeof value.type !== "string") return null;
75
+ const accountId = str(value.accountId);
76
+ return accountId ? (EVENTS[value.type]?.(value, accountId) ?? null) : null;
77
+ }
78
+
79
+ /**
80
+ * An envelope's events, in order. Another format, or an event of an unknown
81
+ * shape, yields nothing for it; only bytes that are not JSON throw.
82
+ */
83
+ export function parseEnvelope(rawBody: string): NormalizedEvent[] {
84
+ const payload = JSON.parse(rawBody) as unknown;
85
+ if (!isObject(payload) || payload.format !== ENVELOPE_FORMAT || !Array.isArray(payload.events)) return [];
86
+ return payload.events.map(event).filter((parsed): parsed is NormalizedEvent => parsed !== null);
87
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * `@12-apps/messaging/whatsapp-web` — WhatsApp over the WhatsApp Web protocol
3
+ * (a linked device, through Baileys), as an alternative transport to the
4
+ * official Cloud API adapter at `@12-apps/messaging/whatsapp`.
5
+ *
6
+ * UNOFFICIAL. WhatsApp's terms forbid unofficial clients and the number used
7
+ * may be banned. A linked session's keys give full access to the account:
8
+ * where they live is the host's decision (`AuthStateStore`), and the package
9
+ * never logs them. See the README's "WhatsApp Web (unofficial)" section.
10
+ *
11
+ * Baileys is NOT a dependency: the host installs `baileys` and passes the
12
+ * module in. Nothing here loads it.
13
+ */
14
+ export { createWhatsAppWebAdapter, type WhatsAppWebAdapterConfig } from "./adapter";
15
+ export {
16
+ createWhatsAppWebSession,
17
+ renderOutboundText,
18
+ type WhatsAppWebSession,
19
+ type WhatsAppWebSessionConfig,
20
+ type WhatsAppWebStatus,
21
+ } from "./session";
22
+ export { clearAuthState, createMemoryAuthStateStore, loadAuthState, type AuthStateStore } from "./auth-state";
23
+ export { ENVELOPE_FORMAT, encodeEnvelope, parseEnvelope } from "./envelope";
24
+ export { addressJid, contactAddress, contentOf, normalizeUpdates, normalizeUpsert, receiptOf, type NormalizeOptions } from "./normalize";
25
+ export {
26
+ DISCONNECT,
27
+ disconnectCode,
28
+ type BaileysAuthState,
29
+ type BaileysConnectionUpdate,
30
+ type BaileysLogger,
31
+ type BaileysMessage,
32
+ type BaileysMessageKey,
33
+ type BaileysMessageUpdate,
34
+ type BaileysModule,
35
+ type BaileysSocket,
36
+ } from "./baileys-port";