@12-apps/messaging 1.3.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.3.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,14 @@
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
+ },
20
+ "./inbound-guard": {
21
+ "types": "./dist/inbound-guard/index.d.ts",
22
+ "default": "./dist/inbound-guard/index.js"
23
+ },
16
24
  "./server": {
17
25
  "types": "./dist/server/index.d.ts",
18
26
  "default": "./dist/server/index.js"
@@ -0,0 +1,143 @@
1
+ /**
2
+ * `parseClassification` — the only shape a classifying agent's answer may
3
+ * take. Anything else (bad JSON, a missing or extra field, a value outside
4
+ * its set, a summary over 200 characters or carrying contact data) comes back
5
+ * as a typed error the caller reports and drops; nothing the agent wrote
6
+ * outside the schema reaches a person or a tool.
7
+ */
8
+
9
+ export const CLASSIFICATION_CATEGORIES = [
10
+ "duvida",
11
+ "reclamacao",
12
+ "lead",
13
+ "elogio",
14
+ "spam",
15
+ "suspeita",
16
+ ] as const;
17
+ export const CLASSIFICATION_URGENCIES = ["hoje", "normal"] as const;
18
+ export const SUMMARY_MAX_LENGTH = 200;
19
+
20
+ export type ClassificationCategory = (typeof CLASSIFICATION_CATEGORIES)[number];
21
+ export type ClassificationUrgency = (typeof CLASSIFICATION_URGENCIES)[number];
22
+
23
+ export interface Classification {
24
+ readonly id: string;
25
+ readonly category: ClassificationCategory;
26
+ readonly urgency: ClassificationUrgency;
27
+ readonly summary: string;
28
+ readonly needs_human: boolean;
29
+ }
30
+
31
+ export type ClassificationErrorCode =
32
+ | "invalid-json"
33
+ | "not-an-object"
34
+ | "unknown-field"
35
+ | "missing-field"
36
+ | "invalid-field"
37
+ | "unknown-id";
38
+
39
+ export interface ClassificationError {
40
+ readonly code: ClassificationErrorCode;
41
+ readonly field?: string;
42
+ readonly message: string;
43
+ }
44
+
45
+ export type ClassificationResult =
46
+ | { readonly ok: true; readonly value: Classification }
47
+ | { readonly ok: false; readonly error: ClassificationError };
48
+
49
+ export interface ParseClassificationOptions {
50
+ /** The ids that were sent to the agent. An answer about any other id is refused. */
51
+ readonly ids?: Iterable<string>;
52
+ }
53
+
54
+ const FIELDS = ["id", "category", "urgency", "summary", "needs_human"] as const;
55
+ /** Linear on any input: one character each side of `@` is enough to call it an address. */
56
+ const EMAIL = /[^\s@]@[^\s@.]+\.[^\s@.]/;
57
+ const PHONE_LIKE = /\d(?:[\s().-]*\d){7,}/;
58
+ const LINK = /\bhttps?:\/\/|\bwww\./i;
59
+
60
+ function fail(code: ClassificationErrorCode, message: string, field?: string): ClassificationResult {
61
+ return { ok: false, error: field === undefined ? { code, message } : { code, field, message } };
62
+ }
63
+
64
+ function readJson(input: unknown): { ok: true; value: unknown } | { ok: false } {
65
+ if (typeof input !== "string") return { ok: true, value: input };
66
+ try {
67
+ return { ok: true, value: JSON.parse(input) as unknown };
68
+ } catch {
69
+ return { ok: false };
70
+ }
71
+ }
72
+
73
+ function oneOf<T extends string>(set: readonly T[], value: unknown): value is T {
74
+ return typeof value === "string" && (set as readonly string[]).includes(value);
75
+ }
76
+
77
+ function summaryProblem(summary: unknown): string | null {
78
+ if (typeof summary !== "string" || summary.trim() === "") return "must be a non-empty string";
79
+ if ([...summary].length > SUMMARY_MAX_LENGTH) return `must be at most ${SUMMARY_MAX_LENGTH} characters`;
80
+ if (EMAIL.test(summary) || PHONE_LIKE.test(summary) || LINK.test(summary)) {
81
+ return "must not carry an e-mail, a phone number or a link";
82
+ }
83
+ return null;
84
+ }
85
+
86
+ function fieldProblem(record: Record<string, unknown>): ClassificationResult | null {
87
+ const { id, category, urgency, summary, needs_human: needsHuman } = record;
88
+ if (typeof id !== "string" || id.trim() === "" || id.length > 128) {
89
+ return fail("invalid-field", "id must be a non-empty string of at most 128 characters", "id");
90
+ }
91
+ if (!oneOf(CLASSIFICATION_CATEGORIES, category)) {
92
+ return fail("invalid-field", `category must be one of ${CLASSIFICATION_CATEGORIES.join(", ")}`, "category");
93
+ }
94
+ if (!oneOf(CLASSIFICATION_URGENCIES, urgency)) {
95
+ return fail("invalid-field", `urgency must be one of ${CLASSIFICATION_URGENCIES.join(", ")}`, "urgency");
96
+ }
97
+ const problem = summaryProblem(summary);
98
+ if (problem !== null) return fail("invalid-field", `summary ${problem}`, "summary");
99
+ if (typeof needsHuman !== "boolean") {
100
+ return fail("invalid-field", "needs_human must be a boolean", "needs_human");
101
+ }
102
+ return null;
103
+ }
104
+
105
+ function shapeProblem(value: unknown): ClassificationResult | null {
106
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
107
+ return fail("not-an-object", "the answer must be one JSON object");
108
+ }
109
+ const record = value as Record<string, unknown>;
110
+ const extra = Object.keys(record).find((key) => !(FIELDS as readonly string[]).includes(key));
111
+ if (extra !== undefined) {
112
+ const name = extra.slice(0, 64);
113
+ return fail("unknown-field", `unexpected field "${name}"`, name);
114
+ }
115
+ const missing = FIELDS.find((key) => !Object.hasOwn(record, key));
116
+ if (missing !== undefined) return fail("missing-field", `missing field "${missing}"`, missing);
117
+ return fieldProblem(record);
118
+ }
119
+
120
+ /** Validate one classification, given as a JSON string or an already-parsed value. */
121
+ export function parseClassification(
122
+ input: unknown,
123
+ opts: ParseClassificationOptions = {},
124
+ ): ClassificationResult {
125
+ const parsed = readJson(input);
126
+ if (!parsed.ok) return fail("invalid-json", "the answer is not valid JSON");
127
+ const problem = shapeProblem(parsed.value);
128
+ if (problem !== null) return problem;
129
+ const classification = parsed.value as Classification;
130
+ if (opts.ids !== undefined && !new Set(opts.ids).has(classification.id)) {
131
+ return fail("unknown-id", "the id was not among the messages sent", "id");
132
+ }
133
+ return {
134
+ ok: true,
135
+ value: {
136
+ id: classification.id,
137
+ category: classification.category,
138
+ urgency: classification.urgency,
139
+ summary: classification.summary,
140
+ needs_human: classification.needs_human,
141
+ },
142
+ };
143
+ }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * The encoded runs an inbound message may hide an instruction in: long
3
+ * base64, hex, URL-encoded escapes of letters, and Unicode tag characters
4
+ * (invisible ASCII). Each run is decoded only when the result reads as text,
5
+ * so a payment code, a hash or a tracking id (which decode to bytes, not
6
+ * words) yields nothing.
7
+ */
8
+
9
+ export type EncodingKind = "base64" | "hex" | "url" | "unicode-tags";
10
+
11
+ /** One encoded run found in a message and the text it decodes to. */
12
+ export interface DecodedRun {
13
+ readonly encoding: EncodingKind;
14
+ /** The run as it appears in the message. */
15
+ readonly source: string;
16
+ /** What it decodes to. Scanned by the screen like the message itself. */
17
+ readonly text: string;
18
+ }
19
+
20
+ const BASE64_RUN = /[A-Za-z0-9+/_-]{20,}={0,2}/g;
21
+ const HEX_RUN = /(?:[0-9a-fA-F]{2}){8,}|(?:\\x[0-9a-fA-F]{2}){4,}/g;
22
+ /** Whitespace-separated tokens; the ones carrying escapes are filtered in code, not by backtracking. */
23
+ const TOKEN = /\S+/g;
24
+ const URL_LETTER_ESCAPE = /%(?:3[0-9]|4[1-9a-fA-F]|5[0-9aA]|6[1-9a-fA-F]|7[0-9aA])/g;
25
+ const TAG_RUN = /(\u{1F3F4})?((?:[\u{E0020}-\u{E007E}])+)(\u{E007F})?/gu;
26
+
27
+ const PRINTABLE = /[\p{L}\p{N}\p{P}\p{S}\p{Zs}\n\t]/u;
28
+ const LETTER = /\p{L}/gu;
29
+
30
+ /** Text, not bytes: valid UTF-8, nine in ten characters printable, three letters. */
31
+ export function readsAsText(text: string): boolean {
32
+ if (text.length === 0) return false;
33
+ let printable = 0;
34
+ for (const ch of text) if (PRINTABLE.test(ch)) printable += 1;
35
+ const letters = text.match(LETTER)?.length ?? 0;
36
+ return printable / [...text].length >= 0.9 && letters >= 3;
37
+ }
38
+
39
+ function bytesToText(bytes: Uint8Array): string | null {
40
+ try {
41
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
42
+ } catch {
43
+ return null;
44
+ }
45
+ }
46
+
47
+ function decodeBase64(run: string): string | null {
48
+ let end = run.length;
49
+ while (end > 0 && run[end - 1] === "=") end -= 1;
50
+ let body = run.slice(0, end).replace(/-/g, "+").replace(/_/g, "/");
51
+ if (body.length % 4 === 1) body = body.slice(0, -1);
52
+ body += "=".repeat((4 - (body.length % 4)) % 4);
53
+ try {
54
+ const binary = atob(body);
55
+ return bytesToText(Uint8Array.from(binary, (c) => c.charCodeAt(0)));
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ /** A long word is not base64: a run counts only with a digit, or with both cases. */
62
+ function looksLikeBase64(run: string): boolean {
63
+ return /\d/.test(run) || (/[a-z]/.test(run) && /[A-Z]/.test(run));
64
+ }
65
+
66
+ function decodeHex(run: string): string | null {
67
+ const digits = run.replace(/\\x/g, "");
68
+ if (!/[a-fA-F]/.test(digits) || !/\d/.test(digits)) return null;
69
+ const bytes = new Uint8Array(digits.length / 2);
70
+ for (let i = 0; i < bytes.length; i += 1) {
71
+ bytes[i] = Number.parseInt(digits.slice(i * 2, i * 2 + 2), 16);
72
+ }
73
+ return bytesToText(bytes);
74
+ }
75
+
76
+ function decodeUrl(token: string): string | null {
77
+ // An address or a search link escapes spaces, commas and accents; an
78
+ // obfuscated instruction escapes LETTERS. Only the second is a run.
79
+ if ((token.match(URL_LETTER_ESCAPE)?.length ?? 0) < 3) return null;
80
+ try {
81
+ return decodeURIComponent(token.replace(/\+/g, " "));
82
+ } catch {
83
+ return null;
84
+ }
85
+ }
86
+
87
+ function collect(
88
+ text: string,
89
+ pattern: RegExp,
90
+ encoding: EncodingKind,
91
+ decode: (run: string) => string | null,
92
+ ): DecodedRun[] {
93
+ const runs: DecodedRun[] = [];
94
+ for (const match of text.matchAll(pattern)) {
95
+ const decoded = decode(match[0]);
96
+ if (decoded !== null && decoded !== match[0] && readsAsText(decoded)) {
97
+ runs.push({ encoding, source: match[0], text: decoded });
98
+ }
99
+ }
100
+ return runs;
101
+ }
102
+
103
+ /**
104
+ * Unicode tag characters (U+E0020–U+E007E) render as nothing and map one to
105
+ * one onto ASCII. Their one legitimate use is a subdivision flag, which opens
106
+ * with U+1F3F4 and closes with U+E007F; any other run is hidden text.
107
+ */
108
+ export function decodeTagRuns(text: string): DecodedRun[] {
109
+ const runs: DecodedRun[] = [];
110
+ for (const match of text.matchAll(TAG_RUN)) {
111
+ if (match[1] !== undefined && match[3] !== undefined) continue;
112
+ const hidden = String.fromCodePoint(
113
+ ...[...match[2]!].map((ch) => ch.codePointAt(0)! - 0xe0000),
114
+ );
115
+ runs.push({ encoding: "unicode-tags", source: match[0], text: hidden });
116
+ }
117
+ return runs;
118
+ }
119
+
120
+ /** Every base64, hex and URL-encoded run in `text` that decodes to text. */
121
+ export function decodeRuns(text: string): DecodedRun[] {
122
+ const base64 = (run: string) => (looksLikeBase64(run) ? decodeBase64(run) : null);
123
+ return [
124
+ ...collect(text, BASE64_RUN, "base64", base64),
125
+ ...collect(text, HEX_RUN, "hex", decodeHex),
126
+ ...collect(text, TOKEN, "url", (token) => (token.includes("%") ? decodeUrl(token) : null)),
127
+ ];
128
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * `@12-apps/messaging/inbound-guard` — a channel-agnostic screen for
3
+ * untrusted inbound text, run BEFORE a model reads it: normalize, score,
4
+ * wrap as quoted data (or withhold), and validate what the model answers.
5
+ * Pure functions, no I/O; the host decides what a `high` message triggers.
6
+ */
7
+
8
+ export {
9
+ normalizeInbound,
10
+ foldForMatching,
11
+ type NormalizedInbound,
12
+ type DecodedRun,
13
+ type EncodingKind,
14
+ } from "./normalize";
15
+ export {
16
+ DEFAULT_INBOUND_RULES,
17
+ DEFAULT_SCAN_LIMIT,
18
+ DEFAULT_THRESHOLDS,
19
+ DEFAULT_WEAK_CAP,
20
+ type InboundRule,
21
+ type PatternRule,
22
+ type SignalRule,
23
+ type ScreenThresholds,
24
+ } from "./rules";
25
+ export {
26
+ screenInbound,
27
+ riskOf,
28
+ capWeak,
29
+ type InboundRisk,
30
+ type ScreenOptions,
31
+ type ScreenResult,
32
+ } from "./screen";
33
+ export {
34
+ wrapForAgent,
35
+ wrapRuleLine,
36
+ randomDelimiter,
37
+ DelimiterCollisionError,
38
+ type InboundForAgent,
39
+ type WrapOptions,
40
+ type WrappedEntry,
41
+ type WrappedBatch,
42
+ } from "./wrap";
43
+ export {
44
+ parseClassification,
45
+ CLASSIFICATION_CATEGORIES,
46
+ CLASSIFICATION_URGENCIES,
47
+ SUMMARY_MAX_LENGTH,
48
+ type Classification,
49
+ type ClassificationCategory,
50
+ type ClassificationUrgency,
51
+ type ClassificationError,
52
+ type ClassificationErrorCode,
53
+ type ClassificationResult,
54
+ type ParseClassificationOptions,
55
+ } from "./classification";