@theokit/gateway-whatsapp 0.1.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.
- package/CHANGELOG.md +31 -0
- package/README.md +7 -0
- package/dist/bridge/whatsapp-web-bridge.mjs +140 -0
- package/dist/index.cjs +809 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +428 -0
- package/dist/index.d.ts +428 -0
- package/dist/index.js +769 -0
- package/dist/index.js.map +1 -0
- package/package.json +54 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/split.ts","../src/adapter.ts","../src/errors.ts","../src/backend/cloud/client.ts","../src/backend/cloud/webhook.ts","../src/backend/cloud/index.ts","../src/backend/web/ipc.ts","../src/backend/web/lifecycle.ts","../src/backend/web/index.ts"],"names":["BasePlatformAdapter","crypto","path","fs","execSync","spawn","resolve","path2"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,IAAM,iBAAA,GAAoB,IAAA;AAE1B,SAAS,qBAAqB,SAAA,EAA2B;AACvD,EAAA,IAAI,GAAA,GAAM,SAAA,CAAU,WAAA,CAAY,MAAA,EAAQ,iBAAiB,CAAA;AACzD,EAAA,IAAI,MAAM,iBAAA,GAAoB,GAAA,QAAW,SAAA,CAAU,WAAA,CAAY,MAAM,iBAAiB,CAAA;AACtF,EAAA,IAAI,MAAM,iBAAA,GAAoB,GAAA,QAAW,SAAA,CAAU,WAAA,CAAY,KAAK,iBAAiB,CAAA;AACrF,EAAA,IAAI,GAAA,IAAO,GAAG,GAAA,GAAM,iBAAA;AACpB,EAAA,IAAI,GAAA,GAAM,UAAU,MAAA,EAAQ;AAC1B,IAAA,MAAM,IAAA,GAAO,SAAA,CAAU,UAAA,CAAW,GAAG,CAAA;AACrC,IAAA,IAAI,IAAA,IAAQ,KAAA,IAAU,IAAA,IAAQ,KAAA,EAAQ,GAAA,IAAO,CAAA;AAAA,EAC/C;AACA,EAAA,O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AA,CAAA,OAAA;AAAA,IACLA,wBAAQ,IAAI,GAAA,CAAI,2PAAe,EAAE,QAAQ,CAAA;AAAA,IAC9C;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Split a long string into ≤4096-char chunks for WhatsApp messages (ADR D310).\n *\n * Break preference: `\\n\\n` → `\\n` → ` `. UTF-16 surrogate-pair guard.\n *\n * EC-8 absorbed: empty parts are filtered out at the end so consecutive\n * newlines don't produce empty `sendMessage` calls Meta would reject.\n *\n * @internal\n */\n\nconst WHATSAPP_MAX_TEXT = 4096;\n\nfunction findWhatsAppCutPoint(remaining: string): number {\n let cut = remaining.lastIndexOf(\"\\n\\n\", WHATSAPP_MAX_TEXT);\n if (cut < WHATSAPP_MAX_TEXT * 0.5) cut = remaining.lastIndexOf(\"\\n\", WHATSAPP_MAX_TEXT);\n if (cut < WHATSAPP_MAX_TEXT * 0.5) cut = remaining.lastIndexOf(\" \", WHATSAPP_MAX_TEXT);\n if (cut <= 0) cut = WHATSAPP_MAX_TEXT;\n if (cut < remaining.length) {\n const code = remaining.charCodeAt(cut);\n if (code >= 0xdc00 && code <= 0xdfff) cut -= 1;\n }\n return cut <= 0 ? WHATSAPP_MAX_TEXT : cut;\n}\n\nexport function splitForWhatsApp(text: string): string[] {\n if (text.length <= WHATSAPP_MAX_TEXT) {\n const single = text.trim();\n return single.length > 0 ? [single] : [];\n }\n const chunks: string[] = [];\n let remaining = text;\n while (remaining.length > WHATSAPP_MAX_TEXT) {\n const cut = findWhatsAppCutPoint(remaining);\n chunks.push(remaining.slice(0, cut));\n remaining = remaining.slice(cut).replace(/^[\\s]+/, \"\");\n }\n if (remaining.length > 0) chunks.push(remaining);\n return chunks.map((p) => p.trim()).filter((p) => p.length > 0);\n}\n","/**\n * `WhatsAppAdapter` — WhatsApp platform adapter for `@theokit/gateway`\n * (Adoption Roadmap v1.4 #2; ADRs D303-D314).\n *\n * Multi-backend (Cloud + Web) — backend chosen via `WhatsAppAdapterOptions.backend`.\n * Backend-agnostic adapter delegates lifecycle + send + subscribe through the\n * `WhatsAppBackend` seam (D303).\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n type WhatsAppMessageEvent,\n} from \"@theokit/gateway\";\n\nimport type {\n WhatsAppBackend,\n WhatsAppInboundEvent,\n WhatsAppStatusReceipt,\n} from \"./backend-types.js\";\nimport { splitForWhatsApp } from \"./split.js\";\n\n/** Cloud (Meta WhatsApp Business Cloud API) backend config (ADR D304). */\nexport interface WhatsAppCloudConfig {\n /** Meta system-user / phone-number access token. */\n readonly accessToken: string;\n /** Meta-issued phone-number-id (NOT the user-facing phone). */\n readonly phoneNumberId: string;\n /** App secret used to verify `X-Hub-Signature-256` on inbound webhooks. */\n readonly appSecret: string;\n /** Graph API version. Defaults to `v18.0`. */\n readonly apiVersion?: string;\n}\n\n/** Web (whatsapp-web.js subprocess bridge) backend config (ADR D305). */\nexport interface WhatsAppWebConfig {\n /** Stable session id used to lock the bridge per-workspace. */\n readonly sessionId: string;\n /** Optional override of the bridge script path (defaults to packaged bridge). */\n readonly bridgeScriptPath?: string;\n}\n\n/** Discriminated options shape (ADR D311). */\nexport type WhatsAppAdapterOptions =\n | {\n readonly backend: \"cloud\";\n readonly cloud: WhatsAppCloudConfig;\n /** D309: require @mention in groups. Default `true`. */\n readonly requireMention?: boolean;\n /** Phone id to detect mentions of (digits only). Defaults to `cloud.phoneNumberId`. */\n readonly botPhoneId?: string;\n }\n | {\n readonly backend: \"web\";\n readonly web: WhatsAppWebConfig;\n readonly requireMention?: boolean;\n /** Phone id to detect mentions of (digits only). Required for groups in web mode. */\n readonly botPhoneId?: string;\n };\n\n/** EC-7: digit-only normalizer for mention comparison (handles `+`, `-`, `()`, spaces). */\nexport function digitsOnly(s: string): string {\n return s.replace(/[^\\d]/g, \"\");\n}\n\n/**\n * Adapter façade. Implements `BasePlatformAdapter` (D172).\n *\n * Use `WhatsAppAdapter.fromCloud(config)` or `WhatsAppAdapter.fromWeb(config)`\n * once the backend factories land (or pass `backend` directly in constructor).\n */\nexport class WhatsAppAdapter extends BasePlatformAdapter {\n readonly platform = \"whatsapp\" as const;\n private readonly backendImpl: WhatsAppBackend;\n private readonly requireMention: boolean;\n private readonly botPhoneId: string;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private statusHandler?: (receipt: WhatsAppStatusReceipt) => Promise<void>;\n // EC-H: track unsubscribe handles so onInbound REPLACES instead of stacks.\n private inboundUnsubscribe?: () => void;\n private statusUnsubscribe?: () => void;\n\n /** Construct from a pre-built backend (used by the static factories + tests). */\n constructor(\n backendImpl: WhatsAppBackend,\n opts: { requireMention?: boolean; botPhoneId?: string } = {},\n ) {\n super();\n this.backendImpl = backendImpl;\n this.requireMention = opts.requireMention ?? true;\n this.botPhoneId = digitsOnly(opts.botPhoneId ?? \"\");\n }\n\n /** Escape hatch (D180-style) for advanced features. */\n getBackend(): WhatsAppBackend {\n return this.backendImpl;\n }\n\n async connect(): Promise<boolean> {\n return this.backendImpl.connect();\n }\n\n async disconnect(): Promise<void> {\n this.inboundUnsubscribe?.();\n this.inboundUnsubscribe = undefined;\n this.statusUnsubscribe?.();\n this.statusUnsubscribe = undefined;\n this.handler = undefined;\n this.statusHandler = undefined;\n await this.backendImpl.disconnect();\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"Empty text rejected.\" } };\n }\n // EC-8: split filters empty parts internally.\n const parts = splitForWhatsApp(out.text);\n if (parts.length === 0) {\n return {\n ok: false,\n error: { code: \"empty_text\", message: \"Text reduced to zero parts after splitting.\" },\n };\n }\n let lastWamid: string | undefined;\n const isGroup = out.channel.type === \"group\";\n for (const part of parts) {\n const r = await this.backendImpl.send({ to: out.channel.id, isGroup, text: part });\n if (!r.ok) {\n return {\n ok: false,\n error: { code: r.error?.code ?? \"unknown\", message: r.error?.message ?? \"Send failed.\" },\n };\n }\n lastWamid = r.wamid;\n }\n return lastWamid !== undefined ? { ok: true, messageId: lastWamid } : { ok: true };\n }\n\n /** D309 + EC-7: group filter with digit-only normalization. */\n private shouldDropGroupMessage(inbound: WhatsAppInboundEvent): boolean {\n if (inbound.conversationType !== \"group\" || !this.requireMention) return false;\n if (this.botPhoneId.length === 0) return true; // misconfigured — drop silently\n const textDigits = digitsOnly(inbound.text);\n return !textDigits.includes(this.botPhoneId);\n }\n\n private toMessageEvent(inbound: WhatsAppInboundEvent): WhatsAppMessageEvent {\n return {\n id: inbound.wamid,\n platform: \"whatsapp\",\n sender: { id: inbound.fromPhone, displayName: inbound.contactName },\n channel: { id: inbound.channelId, type: inbound.conversationType },\n text: inbound.text,\n receivedAt: inbound.receivedAt,\n whatsapp: {\n wamid: inbound.wamid,\n phoneNumberId: inbound.phoneNumberId,\n contactName: inbound.contactName,\n backend: inbound.backend,\n raw: inbound.raw,\n },\n };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace any previous subscription.\n this.inboundUnsubscribe?.();\n this.handler = handler;\n\n this.inboundUnsubscribe = this.backendImpl.onInbound(async (inbound) => {\n if (!this.handler) return;\n if (this.shouldDropGroupMessage(inbound)) return;\n await this.handler(this.toMessageEvent(inbound));\n });\n\n return () => {\n this.inboundUnsubscribe?.();\n this.inboundUnsubscribe = undefined;\n this.handler = undefined;\n };\n }\n\n /** Status receipts (sent/delivered/read/failed). Adapter-specific (D307). */\n onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void {\n this.statusUnsubscribe?.();\n this.statusHandler = handler;\n this.statusUnsubscribe = this.backendImpl.onStatusReceipt(async (r) => {\n await this.statusHandler?.(r);\n });\n return () => {\n this.statusUnsubscribe?.();\n this.statusUnsubscribe = undefined;\n this.statusHandler = undefined;\n };\n }\n}\n","/**\n * Per-backend HTTP/IPC error → canonical `WhatsAppSendResult.error` shape.\n *\n * Cloud follows Meta error codes (https://developers.facebook.com/docs/graph-api/guides/error-handling).\n * Web follows whatsapp-web.js error strings.\n *\n * @internal\n */\n\nimport type { WhatsAppSendResult } from \"./backend-types.js\";\n\ntype ErrorPayload = Required<WhatsAppSendResult>[\"error\"];\n\ninterface MetaErrorBody {\n error?: {\n code?: number;\n message?: string;\n error_subcode?: number;\n };\n}\n\n/** Custom error: `connect()` timed out waiting for \"ready\" (EC-6). */\nexport class WhatsAppConnectTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`WhatsApp web bridge connect timed out after ${timeoutMs}ms (QR code not scanned?)`);\n this.name = \"WhatsAppConnectTimeoutError\";\n }\n}\n\nfunction cloudErrorCode(\n status: number,\n errCode: number,\n): \"auth_failed\" | \"rate_limit\" | \"invalid_request\" | \"server_error\" | \"unknown\" {\n if (errCode === 190 || status === 401) return \"auth_failed\";\n if (errCode === 130 || errCode === 131 || status === 429) return \"rate_limit\";\n if (status === 400 || errCode === 100) return \"invalid_request\";\n if (status >= 500) return \"server_error\";\n return \"unknown\";\n}\n\nexport function mapWhatsAppCloudError(status: number, body: unknown): ErrorPayload {\n const parsed = (body !== null && typeof body === \"object\" ? body : {}) as MetaErrorBody;\n const errCode = parsed.error?.code ?? 0;\n const errMsg = parsed.error?.message ?? `HTTP ${status}`;\n const code = cloudErrorCode(status, errCode);\n if (code === \"auth_failed\") return { code, message: `Bearer token rejected: ${errMsg}` };\n if (code === \"rate_limit\") return { code, message: `Throttled: ${errMsg}` };\n return { code, message: errMsg };\n}\n\nexport function mapWhatsAppWebError(ipcError: string | undefined): ErrorPayload {\n const msg = ipcError ?? \"unknown bridge error\";\n if (msg.includes(\"AUTHENTICATION\") || msg.includes(\"UNAUTHORIZED\")) {\n return { code: \"auth_failed\", message: msg };\n }\n if (msg.includes(\"RATE\") || msg.includes(\"THROTTLE\")) {\n return { code: \"rate_limit\", message: msg };\n }\n if (msg.includes(\"PROTOCOL\") || msg.includes(\"DISCONNECT\")) {\n return { code: \"server_error\", message: msg };\n }\n if (msg.includes(\"TIMEOUT\")) {\n return { code: \"timeout\", message: msg };\n }\n return { code: \"unknown\", message: msg };\n}\n","/**\n * `WhatsAppCloudClient` — typed `fetch` wrapper for Meta WhatsApp Business\n * Cloud API (ADR D304). No Meta SDK; we own the wire.\n *\n * @internal\n */\n\nimport type { WhatsAppSendResult } from \"../../backend-types.js\";\nimport { mapWhatsAppCloudError } from \"../../errors.js\";\nimport type {\n MetaErrorEnvelope,\n MetaMarkReadRequest,\n MetaSendResponse,\n MetaSendTextRequest,\n} from \"./types.js\";\n\ninterface WhatsAppCloudClientOptions {\n readonly accessToken: string;\n readonly phoneNumberId: string;\n readonly apiVersion?: string;\n /** Test seam. */\n readonly fetch?: typeof fetch;\n}\n\nexport class WhatsAppCloudClient {\n private readonly fetchImpl: typeof fetch;\n private readonly baseUrl: string;\n\n constructor(private readonly opts: WhatsAppCloudClientOptions) {\n this.fetchImpl = opts.fetch ?? fetch;\n const apiVersion = opts.apiVersion ?? \"v18.0\";\n this.baseUrl = `https://graph.facebook.com/${apiVersion}/${opts.phoneNumberId}`;\n }\n\n /** Send a text message. v1 scope — no media (D286 deferred). */\n async sendText(to: string, body: string, isGroup: boolean): Promise<WhatsAppSendResult> {\n const req: MetaSendTextRequest = isGroup\n ? {\n messaging_product: \"whatsapp\",\n to,\n type: \"text\",\n text: { body, preview_url: false },\n }\n : {\n messaging_product: \"whatsapp\",\n recipient_type: \"individual\",\n to,\n type: \"text\",\n text: { body, preview_url: false },\n };\n\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.baseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${this.opts.accessToken}`,\n },\n body: JSON.stringify(req),\n });\n } catch (cause) {\n return {\n ok: false,\n error: {\n code: \"server_error\",\n message: `Network error: ${cause instanceof Error ? cause.message : String(cause)}`,\n },\n };\n }\n\n if (!response.ok) {\n const errBody = (await response.json().catch(() => ({}))) as MetaErrorEnvelope | unknown;\n return { ok: false, error: mapWhatsAppCloudError(response.status, errBody) };\n }\n\n const data = (await response.json()) as MetaSendResponse;\n const wamid = data.messages?.[0]?.id;\n if (wamid === undefined) {\n return { ok: false, error: { code: \"unknown\", message: \"Meta returned no wamid.\" } };\n }\n return { ok: true, wamid };\n }\n\n /** Mark an inbound message as read (status receipt back to user). */\n async markAsRead(wamid: string): Promise<boolean> {\n const body: MetaMarkReadRequest = {\n messaging_product: \"whatsapp\",\n status: \"read\",\n message_id: wamid,\n };\n try {\n const response = await this.fetchImpl(`${this.baseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${this.opts.accessToken}`,\n },\n body: JSON.stringify(body),\n });\n return response.ok;\n } catch {\n return false;\n }\n }\n}\n","/**\n * Webhook helpers for Meta WhatsApp Business Cloud API (ADR D306, D312).\n *\n * Two boundaries:\n * 1. GET handshake — `verifyWebhookSubscription` (EC-1).\n * 2. POST callbacks — `verifyWebhookSignature` (EC-3 length guard) +\n * `normalizeInboundMessages` (EC-4 text-only filter) +\n * `normalizeStatusReceipts`.\n *\n * The user owns the HTTP route; we expose pure helpers they call from inside it.\n *\n * @public\n */\n\nimport * as crypto from \"node:crypto\";\n\nimport type { WhatsAppInboundEvent, WhatsAppStatusReceipt } from \"../../backend-types.js\";\nimport type { MetaIncomingMessage, MetaStatusUpdate, MetaWebhookEnvelope } from \"./types.js\";\n\nconst warnedNonTextTypes = new Set<string>();\n\n/**\n * Verify Meta's GET `/webhook?hub.mode=subscribe&hub.challenge=...&hub.verify_token=...`\n * handshake (EC-1 absorbed).\n *\n * @returns `query[\"hub.challenge\"]` when valid, `null` otherwise. The caller\n * echoes the challenge as `text/plain` on success.\n */\nexport function verifyWebhookSubscription(\n query: Record<string, string | undefined>,\n expectedVerifyToken: string,\n): string | null {\n const mode = query[\"hub.mode\"];\n const token = query[\"hub.verify_token\"];\n const challenge = query[\"hub.challenge\"];\n if (mode !== \"subscribe\") return null;\n if (token === undefined || token !== expectedVerifyToken) return null;\n if (challenge === undefined || challenge.length === 0) return null;\n return challenge;\n}\n\n/**\n * Verify the `X-Hub-Signature-256` HMAC-SHA256 against the app secret (D312).\n *\n * EC-3 absorbed: length-guard BEFORE `timingSafeEqual` so a malformed header\n * (e.g. `sha256=ab`) returns `false` instead of throwing `RangeError` (DoS).\n *\n * @returns `true` iff the signature matches.\n */\nexport function verifyWebhookSignature(\n rawBody: Buffer | string,\n signatureHeader: string | undefined,\n appSecret: string,\n): boolean {\n if (signatureHeader === undefined) return false;\n if (!signatureHeader.startsWith(\"sha256=\")) return false;\n const receivedHex = signatureHeader.slice(7);\n if (!/^[0-9a-f]+$/i.test(receivedHex)) return false;\n const received = Buffer.from(receivedHex, \"hex\");\n const body = typeof rawBody === \"string\" ? Buffer.from(rawBody, \"utf8\") : rawBody;\n const expected = crypto.createHmac(\"sha256\", appSecret).update(body).digest();\n // EC-3: length guard before timingSafeEqual.\n if (received.length !== expected.length) return false;\n return crypto.timingSafeEqual(received, expected);\n}\n\n/** Parse the raw JSON payload into a typed envelope. Returns `null` if shape is unrecognized. */\nexport function parseWebhookPayload(json: unknown): MetaWebhookEnvelope | null {\n if (json === null || typeof json !== \"object\") return null;\n const env = json as MetaWebhookEnvelope;\n if (env.object === undefined || !Array.isArray(env.entry)) return null;\n return env;\n}\n\n/**\n * Normalize inbound messages → `WhatsAppInboundEvent[]`.\n *\n * EC-4 absorbed: filters `message.type !== \"text\"` (v1 text-only). Non-text\n * types emit a one-shot stderr warn per type.\n */\nfunction buildContactMap(\n value: NonNullable<MetaWebhookEnvelope[\"entry\"][number][\"changes\"][number][\"value\"]>,\n): Map<string, string | undefined> {\n const map = new Map<string, string | undefined>();\n for (const c of value.contacts ?? []) map.set(c.wa_id, c.profile?.name);\n return map;\n}\n\nfunction processChange(\n change: MetaWebhookEnvelope[\"entry\"][number][\"changes\"][number],\n out: WhatsAppInboundEvent[],\n): void {\n const value = change.value;\n if (value === undefined || value === null) return;\n const phoneNumberId = value.metadata?.phone_number_id;\n const contactByWaId = buildContactMap(value);\n for (const msg of value.messages ?? []) {\n const normalized = normalizeOneMessage(msg, phoneNumberId, contactByWaId);\n if (normalized !== null) out.push(normalized);\n }\n}\n\nexport function normalizeInboundMessages(envelope: MetaWebhookEnvelope): WhatsAppInboundEvent[] {\n const out: WhatsAppInboundEvent[] = [];\n for (const entry of envelope.entry) {\n for (const change of entry.changes) processChange(change, out);\n }\n return out;\n}\n\nfunction normalizeOneMessage(\n msg: MetaIncomingMessage,\n phoneNumberId: string | undefined,\n contactByWaId: Map<string, string | undefined>,\n): WhatsAppInboundEvent | null {\n // EC-4: text-only in v1.\n if (msg.type !== \"text\") {\n if (!warnedNonTextTypes.has(msg.type)) {\n warnedNonTextTypes.add(msg.type);\n process.stderr.write(\n `[whatsapp] ignoring ${msg.type} message — v1 text-only (will be supported in v0.2+).\\n`,\n );\n }\n return null;\n }\n const body = msg.text?.body ?? \"\";\n // Cloud API doesn't distinguish DM vs group at the message level — `from`\n // is the sender. We don't have a reliable group-detection signal in cloud\n // (groups need a different webhook subscription). v1 treats all inbound\n // as DM. If the user enables group webhooks, the `conversationType` heuristic\n // here is a future-extension point.\n return {\n wamid: msg.id,\n fromPhone: msg.from,\n phoneNumberId,\n contactName: contactByWaId.get(msg.from),\n conversationType: \"dm\",\n channelId: msg.from,\n text: body,\n receivedAt: Number(msg.timestamp) * 1000 || Date.now(),\n backend: \"cloud\",\n raw: msg,\n };\n}\n\n/** Normalize status updates → `WhatsAppStatusReceipt[]`. */\nexport function normalizeStatusReceipts(envelope: MetaWebhookEnvelope): WhatsAppStatusReceipt[] {\n const out: WhatsAppStatusReceipt[] = [];\n for (const entry of envelope.entry) {\n for (const change of entry.changes) {\n const statuses = change.value?.statuses ?? [];\n for (const s of statuses) {\n out.push(metaStatusToReceipt(s));\n }\n }\n }\n return out;\n}\n\nfunction metaStatusToReceipt(s: MetaStatusUpdate): WhatsAppStatusReceipt {\n return {\n wamid: s.id,\n status: s.status,\n recipient: s.recipient_id,\n timestamp: Number(s.timestamp) * 1000 || Date.now(),\n };\n}\n\n/** @internal — test seam to reset the one-shot warn de-dup. */\nexport function __resetNonTextWarnings(): void {\n warnedNonTextTypes.clear();\n}\n","/**\n * `WhatsAppCloudBackend` — Meta WhatsApp Business Cloud API backend (ADR D304).\n *\n * `connect()` / `disconnect()` are no-ops (HTTP push via webhook is the only\n * inbound channel). Outbound delegates to `WhatsAppCloudClient`. Inbound\n * dispatch is driven by the user calling `handleWebhookPayload(rawBody, sig)`\n * from inside their HTTP route.\n *\n * @public\n */\n\nimport type {\n WhatsAppBackend,\n WhatsAppInboundEvent,\n WhatsAppOutboundMessage,\n WhatsAppSendResult,\n WhatsAppStatusReceipt,\n} from \"../../backend-types.js\";\nimport { WhatsAppCloudClient } from \"./client.js\";\nimport {\n normalizeInboundMessages,\n normalizeStatusReceipts,\n parseWebhookPayload,\n verifyWebhookSignature,\n} from \"./webhook.js\";\n\nexport interface WhatsAppCloudBackendOptions {\n readonly accessToken: string;\n readonly phoneNumberId: string;\n readonly appSecret: string;\n readonly apiVersion?: string;\n /** Test seam. */\n readonly fetch?: typeof fetch;\n}\n\nexport class WhatsAppCloudBackend implements WhatsAppBackend {\n readonly kind = \"cloud\" as const;\n private readonly client: WhatsAppCloudClient;\n private readonly appSecret: string;\n private inboundHandler?: (event: WhatsAppInboundEvent) => Promise<void>;\n private statusHandler?: (receipt: WhatsAppStatusReceipt) => Promise<void>;\n\n constructor(opts: WhatsAppCloudBackendOptions) {\n this.client = new WhatsAppCloudClient({\n accessToken: opts.accessToken,\n phoneNumberId: opts.phoneNumberId,\n apiVersion: opts.apiVersion,\n ...(opts.fetch !== undefined ? { fetch: opts.fetch } : {}),\n });\n this.appSecret = opts.appSecret;\n }\n\n // Cloud has no persistent connection — webhook is push, send is HTTP.\n async connect(): Promise<boolean> {\n return true;\n }\n\n async disconnect(): Promise<void> {\n this.inboundHandler = undefined;\n this.statusHandler = undefined;\n }\n\n async send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult> {\n return this.client.sendText(message.to, message.text, message.isGroup);\n }\n\n onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void {\n this.inboundHandler = handler;\n return () => {\n this.inboundHandler = undefined;\n };\n }\n\n onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void {\n this.statusHandler = handler;\n return () => {\n this.statusHandler = undefined;\n };\n }\n\n /**\n * Webhook entrypoint. The user calls this from inside their POST /webhook\n * route after `verifyWebhookSubscription` on GET.\n *\n * @returns `true` if signature valid + dispatched (or empty payload).\n * `false` if signature invalid (route should return 401).\n */\n async handleWebhookPayload(\n rawBody: Buffer | string,\n signatureHeader: string | undefined,\n ): Promise<boolean> {\n if (!verifyWebhookSignature(rawBody, signatureHeader, this.appSecret)) {\n return false;\n }\n const json = JSON.parse(\n typeof rawBody === \"string\" ? rawBody : rawBody.toString(\"utf8\"),\n ) as unknown;\n const envelope = parseWebhookPayload(json);\n if (envelope === null) return true; // valid signature, unrecognized shape — nothing to dispatch\n const inbounds = normalizeInboundMessages(envelope);\n for (const event of inbounds) {\n if (this.inboundHandler !== undefined) {\n await this.inboundHandler(event);\n }\n }\n const statuses = normalizeStatusReceipts(envelope);\n for (const receipt of statuses) {\n if (this.statusHandler !== undefined) {\n await this.statusHandler(receipt);\n }\n }\n return true;\n }\n}\n","/**\n * IPC protocol between adapter and `whatsapp-web.js` subprocess bridge.\n *\n * Wire: stdin/stdout JSON-lines (each message terminated by `\\n`).\n *\n * @internal\n */\n\n/**\n * Sentinel runtime export — see `backend-types.ts` for rationale.\n *\n * @knipignore\n */\nexport const __ipcMarker: unique symbol = Symbol(\"ipc\");\n\n/** Commands the adapter sends to the bridge. */\nexport type IpcCommand =\n | { readonly cmd: \"send\"; readonly msgId: string; readonly to: string; readonly text: string }\n | { readonly cmd: \"shutdown\" };\n\n/** Events the bridge emits to the adapter. */\nexport type IpcEvent =\n | { readonly event: \"ready\"; readonly botPhone: string }\n | {\n readonly event: \"message\";\n readonly msgId: string;\n readonly from: string;\n readonly body: string;\n readonly isGroup: boolean;\n readonly chatId: string;\n readonly contactName?: string;\n readonly timestamp: number;\n }\n | {\n readonly event: \"send_ack\";\n readonly msgId: string;\n readonly success: boolean;\n readonly wamid?: string;\n readonly error?: string;\n }\n | {\n readonly event: \"status\";\n readonly msgId: string;\n readonly status: \"sent\" | \"delivered\" | \"read\" | \"failed\";\n readonly recipient: string;\n readonly timestamp: number;\n }\n | { readonly event: \"error\"; readonly message: string };\n\n/** Parse one JSON-line. Returns null on malformed. */\nexport function parseEvent(line: string): IpcEvent | null {\n if (line.length === 0) return null;\n try {\n const parsed = JSON.parse(line) as unknown;\n if (parsed === null || typeof parsed !== \"object\") return null;\n if (typeof (parsed as { event?: unknown }).event !== \"string\") return null;\n return parsed as IpcEvent;\n } catch {\n return null;\n }\n}\n\n/** Format an outbound command as JSON + newline. */\nexport function formatCommand(cmd: IpcCommand): string {\n return `${JSON.stringify(cmd)}\\n`;\n}\n\n/**\n * Line buffer — accumulates stdout chunks until `\\n` boundaries, yields\n * complete lines. Addresses EC-11 (chunked stdout across multiple reads).\n */\nexport class LineBuffer {\n private buffer = \"\";\n\n push(chunk: string): string[] {\n this.buffer += chunk;\n const out: string[] = [];\n let idx = this.buffer.indexOf(\"\\n\");\n while (idx !== -1) {\n out.push(this.buffer.slice(0, idx));\n this.buffer = this.buffer.slice(idx + 1);\n idx = this.buffer.indexOf(\"\\n\");\n }\n return out;\n }\n\n /** Test seam — current pending bytes. */\n get pending(): string {\n return this.buffer;\n }\n}\n","/**\n * Bridge subprocess lifecycle (ADR D305, D313). PID file lock + stale-process\n * cleanup. EC-5 absorbed: verifies cmdline before killing (otherwise we may\n * kill an unrelated process the OS recycled the PID for).\n *\n * @internal\n */\n\nimport { type ChildProcess, execSync, spawn } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\n/** Marker substring our bridge process MUST carry in its argv (EC-5). */\nexport const BRIDGE_PROCESS_TAG = \"whatsapp-web-bridge\";\n\ninterface SpawnBridgeOptions {\n readonly sessionId: string;\n readonly bridgeScriptPath: string;\n readonly theokitHome?: string;\n}\n\nexport interface BridgeHandle {\n readonly child: ChildProcess;\n readonly pidFilePath: string;\n}\n\nfunction pidFilePath(theokitHome: string, sessionId: string): string {\n return path.join(theokitHome, `whatsapp-bridge-${sessionId}.pid`);\n}\n\nfunction defaultTheokitHome(): string {\n return process.env.THEOKIT_HOME ?? path.join(process.env.HOME ?? \"/tmp\", \".theokit\");\n}\n\n/**\n * Verify whether `pid` belongs to a process whose argv contains our tag (EC-5).\n *\n * Without this guard, OS may have recycled the PID to e.g. `vim` and our\n * cleanup would terminate the user's editor.\n *\n * @internal\n */\nexport function pidBelongsToOurBridge(pid: number): boolean {\n try {\n // Linux: /proc/<pid>/cmdline (NUL-separated argv).\n const cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, \"utf8\");\n return cmdline.includes(BRIDGE_PROCESS_TAG);\n } catch {\n // macOS / BSD fallback: ps -p <pid> -o args=\n try {\n const out = execSync(`ps -p ${pid} -o args=`, {\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).toString();\n return out.includes(BRIDGE_PROCESS_TAG);\n } catch {\n return false;\n }\n }\n}\n\n/**\n * Acquire the PID lock for a session — kill any stale bridge (cmdline-verified),\n * then return the lock-file path (caller writes its own PID after spawn).\n */\n/** EC-5: kill `stalePid` ONLY if cmdline confirms ownership. */\nfunction killIfOurBridge(stalePid: number): void {\n if (!Number.isFinite(stalePid) || stalePid <= 0) return;\n if (!pidBelongsToOurBridge(stalePid)) return;\n try {\n process.kill(stalePid, \"SIGTERM\");\n } catch {\n // Process already gone — fine.\n }\n}\n\nfunction cleanupStaleLock(lockFile: string): void {\n const raw = fs.readFileSync(lockFile, \"utf8\").trim();\n killIfOurBridge(Number.parseInt(raw, 10));\n try {\n fs.unlinkSync(lockFile);\n } catch {\n /* ignore */\n }\n}\n\nexport function acquirePidLock(sessionId: string, theokitHome?: string): string {\n const home = theokitHome ?? defaultTheokitHome();\n fs.mkdirSync(home, { recursive: true });\n const lockFile = pidFilePath(home, sessionId);\n if (fs.existsSync(lockFile)) cleanupStaleLock(lockFile);\n return lockFile;\n}\n\n/** Spawn the bridge subprocess, write PID file. */\nexport function spawnBridge(opts: SpawnBridgeOptions): BridgeHandle {\n const home = opts.theokitHome ?? defaultTheokitHome();\n const lockFile = acquirePidLock(opts.sessionId, home);\n\n const child = spawn(\n \"node\",\n [opts.bridgeScriptPath, \"--tag\", BRIDGE_PROCESS_TAG, \"--session\", opts.sessionId],\n {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n detached: false,\n },\n );\n\n if (child.pid !== undefined) {\n fs.writeFileSync(lockFile, String(child.pid), { mode: 0o600 });\n }\n\n // EC-12: pipe stderr so the buffer never fills.\n if (child.stderr !== null) {\n child.stderr.pipe(process.stderr);\n }\n\n return { child, pidFilePath: lockFile };\n}\n\n/** Terminate the bridge: SIGTERM → wait 3s → SIGKILL. Removes PID file. */\nexport async function terminateBridge(handle: BridgeHandle): Promise<void> {\n const { child, pidFilePath: lockFile } = handle;\n if (child.pid !== undefined && !child.killed) {\n try {\n child.kill(\"SIGTERM\");\n } catch {\n /* ignore */\n }\n const exited = await waitForExit(child, 3000);\n if (!exited) {\n try {\n child.kill(\"SIGKILL\");\n } catch {\n /* ignore */\n }\n await waitForExit(child, 1000);\n }\n }\n try {\n fs.unlinkSync(lockFile);\n } catch {\n /* ignore */\n }\n}\n\nfunction waitForExit(child: ChildProcess, timeoutMs: number): Promise<boolean> {\n return new Promise((resolve) => {\n if (child.exitCode !== null || child.signalCode !== null) {\n resolve(true);\n return;\n }\n let resolved = false;\n const onExit = () => {\n if (resolved) return;\n resolved = true;\n resolve(true);\n };\n child.once(\"exit\", onExit);\n setTimeout(() => {\n if (resolved) return;\n resolved = true;\n child.removeListener(\"exit\", onExit);\n resolve(false);\n }, timeoutMs).unref();\n });\n}\n","/**\n * `WhatsAppWebBackend` — `whatsapp-web.js` subprocess bridge backend (ADR D305).\n *\n * Lifecycle (T3.1) + IPC (T3.2) wired behind the `WhatsAppBackend` interface.\n * EC-6 absorbed: `connect()` races against a 120s timeout so unattended QR\n * pairings fail fast instead of hanging the app.\n *\n * @public\n */\n\nimport * as path from \"node:path\";\nimport type {\n WhatsAppBackend,\n WhatsAppInboundEvent,\n WhatsAppOutboundMessage,\n WhatsAppSendResult,\n WhatsAppStatusReceipt,\n} from \"../../backend-types.js\";\nimport { mapWhatsAppWebError, WhatsAppConnectTimeoutError } from \"../../errors.js\";\nimport { formatCommand, type IpcEvent, LineBuffer, parseEvent } from \"./ipc.js\";\nimport { type BridgeHandle, spawnBridge, terminateBridge } from \"./lifecycle.js\";\n\nexport interface WhatsAppWebBackendOptions {\n readonly sessionId: string;\n /** Override the default bridge script path. Defaults to bundled script. */\n readonly bridgeScriptPath?: string;\n /** EC-6 connect timeout in ms. Default 120000. */\n readonly connectTimeoutMs?: number;\n /** Per-send timeout in ms. Default 30000. */\n readonly sendTimeoutMs?: number;\n /** Test seam: override the spawned child via a factory. */\n readonly spawnFactory?: () => BridgeHandle;\n /** Test seam: theokit home for PID locks. */\n readonly theokitHome?: string;\n}\n\ninterface PendingSend {\n readonly resolve: (r: WhatsAppSendResult) => void;\n readonly timer: NodeJS.Timeout;\n}\n\nconst DEFAULT_CONNECT_TIMEOUT_MS = 120_000;\nconst DEFAULT_SEND_TIMEOUT_MS = 30_000;\n\nexport class WhatsAppWebBackend implements WhatsAppBackend {\n readonly kind = \"web\" as const;\n private handle?: BridgeHandle;\n private readonly buffer = new LineBuffer();\n private inboundHandler?: (event: WhatsAppInboundEvent) => Promise<void>;\n private statusHandler?: (receipt: WhatsAppStatusReceipt) => Promise<void>;\n private readonly pending = new Map<string, PendingSend>();\n private msgIdCounter = 0;\n private botPhone?: string;\n private connected = false;\n // EC-6: emitter resolvers for `event: \"ready\"`.\n private readyResolvers: Array<(phone: string) => void> = [];\n\n constructor(private readonly opts: WhatsAppWebBackendOptions) {}\n\n private spawnBridgeHandle(): NonNullable<typeof this.handle> {\n return this.opts.spawnFactory\n ? this.opts.spawnFactory()\n : spawnBridge({\n sessionId: this.opts.sessionId,\n bridgeScriptPath: this.opts.bridgeScriptPath ?? defaultBridgeScriptPath(),\n ...(this.opts.theokitHome !== undefined ? { theokitHome: this.opts.theokitHome } : {}),\n });\n }\n\n private wireStdout(): void {\n if (this.handle?.child.stdout === null || this.handle === undefined) return;\n this.handle.child.stdout.setEncoding(\"utf8\");\n this.handle.child.stdout.on(\"data\", (chunk: string) => {\n for (const line of this.buffer.push(chunk)) {\n const event = parseEvent(line);\n if (event !== null) this.dispatch(event);\n }\n });\n }\n\n private async cleanupHandle(): Promise<void> {\n if (this.handle === undefined) return;\n await terminateBridge(this.handle).catch(() => {});\n this.handle = undefined;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n this.handle = this.spawnBridgeHandle();\n this.wireStdout();\n\n const timeoutMs = this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;\n const ready = new Promise<string>((resolve) => this.readyResolvers.push(resolve));\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new WhatsAppConnectTimeoutError(timeoutMs)), timeoutMs);\n });\n\n try {\n const phone = await Promise.race([ready, timeout]);\n if (timer !== undefined) clearTimeout(timer);\n this.botPhone = phone;\n this.connected = true;\n return true;\n } catch (err) {\n if (timer !== undefined) clearTimeout(timer);\n await this.cleanupHandle();\n throw err;\n }\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected || this.handle === undefined) return;\n try {\n if (this.handle.child.stdin !== null && !this.handle.child.stdin.destroyed) {\n this.handle.child.stdin.write(formatCommand({ cmd: \"shutdown\" }));\n }\n } catch {\n /* ignore */\n }\n await terminateBridge(this.handle);\n this.handle = undefined;\n this.connected = false;\n // Reject any pending sends.\n for (const [_, p] of this.pending) {\n clearTimeout(p.timer);\n p.resolve({ ok: false, error: { code: \"server_error\", message: \"Bridge disconnected.\" } });\n }\n this.pending.clear();\n this.readyResolvers = [];\n }\n\n async send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult> {\n if (!this.connected || this.handle === undefined || this.handle.child.stdin === null) {\n return { ok: false, error: { code: \"server_error\", message: \"Bridge not connected.\" } };\n }\n const msgId = `out-${++this.msgIdCounter}`;\n const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;\n return new Promise<WhatsAppSendResult>((resolve) => {\n const timer = setTimeout(() => {\n this.pending.delete(msgId);\n resolve({\n ok: false,\n error: { code: \"timeout\", message: `Bridge send timed out after ${timeoutMs}ms.` },\n });\n }, timeoutMs);\n this.pending.set(msgId, { resolve, timer });\n try {\n this.handle!.child.stdin!.write(\n formatCommand({ cmd: \"send\", msgId, to: message.to, text: message.text }),\n );\n } catch (err) {\n clearTimeout(timer);\n this.pending.delete(msgId);\n resolve({\n ok: false,\n error: mapWhatsAppWebError(err instanceof Error ? err.message : String(err)),\n });\n }\n });\n }\n\n onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void {\n this.inboundHandler = handler;\n return () => {\n this.inboundHandler = undefined;\n };\n }\n\n onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void {\n this.statusHandler = handler;\n return () => {\n this.statusHandler = undefined;\n };\n }\n\n private handleReady(event: Extract<IpcEvent, { event: \"ready\" }>): void {\n for (const r of this.readyResolvers) r(event.botPhone);\n this.readyResolvers = [];\n }\n\n private handleMessage(event: Extract<IpcEvent, { event: \"message\" }>): void {\n if (this.inboundHandler === undefined) return;\n const normalized: WhatsAppInboundEvent = {\n wamid: event.msgId,\n fromPhone: event.from,\n contactName: event.contactName,\n conversationType: event.isGroup ? \"group\" : \"dm\",\n channelId: event.chatId,\n text: event.body,\n receivedAt: event.timestamp || Date.now(),\n backend: \"web\",\n raw: event,\n };\n void this.inboundHandler(normalized);\n }\n\n private handleSendAck(event: Extract<IpcEvent, { event: \"send_ack\" }>): void {\n const pending = this.pending.get(event.msgId);\n if (pending === undefined) return;\n this.pending.delete(event.msgId);\n clearTimeout(pending.timer);\n if (event.success) {\n pending.resolve(event.wamid !== undefined ? { ok: true, wamid: event.wamid } : { ok: true });\n } else {\n pending.resolve({ ok: false, error: mapWhatsAppWebError(event.error) });\n }\n }\n\n private handleStatus(event: Extract<IpcEvent, { event: \"status\" }>): void {\n if (this.statusHandler === undefined) return;\n void this.statusHandler({\n wamid: event.msgId,\n status: event.status,\n recipient: event.recipient,\n timestamp: event.timestamp || Date.now(),\n });\n }\n\n private dispatch(event: IpcEvent): void {\n switch (event.event) {\n case \"ready\":\n this.handleReady(event);\n return;\n case \"message\":\n this.handleMessage(event);\n return;\n case \"send_ack\":\n this.handleSendAck(event);\n return;\n case \"status\":\n this.handleStatus(event);\n return;\n case \"error\":\n process.stderr.write(`[whatsapp-web bridge] ${event.message}\\n`);\n return;\n }\n }\n}\n\nfunction defaultBridgeScriptPath(): string {\n // Points to the bundled script at `dist/bridge/whatsapp-web-bridge.mjs` once\n // the build copies it. Until then, callers can pass `bridgeScriptPath` directly.\n return path.resolve(\n path.dirname(new URL(import.meta.url).pathname),\n \"../../bridge/whatsapp-web-bridge.mjs\",\n );\n}\n"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent } from '@theokit/gateway';
|
|
2
|
+
export { WhatsAppMessageEvent } from '@theokit/gateway';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Backend abstraction (ADR D303). Lets `WhatsAppAdapter` stay backend-agnostic
|
|
6
|
+
* while we ship both Cloud (Meta API) and Web (`whatsapp-web.js` subprocess)
|
|
7
|
+
* implementations side by side.
|
|
8
|
+
*
|
|
9
|
+
* @internal
|
|
10
|
+
*/
|
|
11
|
+
/** Normalized inbound event — cloud + web both produce this shape. */
|
|
12
|
+
interface WhatsAppInboundEvent {
|
|
13
|
+
/** Stable message id (`wamid.xxx` cloud, `msg.id._serialized` web). */
|
|
14
|
+
readonly wamid: string;
|
|
15
|
+
/** Sender phone (digits only — no `+` prefix). */
|
|
16
|
+
readonly fromPhone: string;
|
|
17
|
+
/** Cloud-only Meta phone-number-id; undefined for web. */
|
|
18
|
+
readonly phoneNumberId?: string;
|
|
19
|
+
/** Display name when available. */
|
|
20
|
+
readonly contactName?: string;
|
|
21
|
+
/** Conversation type. */
|
|
22
|
+
readonly conversationType: "dm" | "group";
|
|
23
|
+
/** Channel id — either the sender phone (DM) or the group id (group). */
|
|
24
|
+
readonly channelId: string;
|
|
25
|
+
/** Plain-text body (already filtered by EC-4 — text-only in v1). */
|
|
26
|
+
readonly text: string;
|
|
27
|
+
/** Receipt timestamp (ms since epoch). */
|
|
28
|
+
readonly receivedAt: number;
|
|
29
|
+
/** Backend that emitted this event. */
|
|
30
|
+
readonly backend: "cloud" | "web";
|
|
31
|
+
/** Raw envelope for the escape hatch. */
|
|
32
|
+
readonly raw: unknown;
|
|
33
|
+
}
|
|
34
|
+
/** Outbound message — what `WhatsAppBackend.send` accepts. */
|
|
35
|
+
interface WhatsAppOutboundMessage {
|
|
36
|
+
/** Phone (digits, E.164 minus `+`) or group id. */
|
|
37
|
+
readonly to: string;
|
|
38
|
+
/** Whether `to` is a group id (cloud needs different shape; web is implicit). */
|
|
39
|
+
readonly isGroup: boolean;
|
|
40
|
+
/** Plain-text body (already split for 4096-char cap). */
|
|
41
|
+
readonly text: string;
|
|
42
|
+
}
|
|
43
|
+
/** Status receipt (ADR D307). */
|
|
44
|
+
interface WhatsAppStatusReceipt {
|
|
45
|
+
/** The `wamid` we previously sent. */
|
|
46
|
+
readonly wamid: string;
|
|
47
|
+
/** Delivery lifecycle stage. */
|
|
48
|
+
readonly status: "sent" | "delivered" | "read" | "failed";
|
|
49
|
+
/** Recipient (digits-only phone). */
|
|
50
|
+
readonly recipient: string;
|
|
51
|
+
/** Receipt timestamp. */
|
|
52
|
+
readonly timestamp: number;
|
|
53
|
+
}
|
|
54
|
+
/** Per-message send result returned by `WhatsAppBackend.send`. */
|
|
55
|
+
interface WhatsAppSendResult$1 {
|
|
56
|
+
readonly ok: boolean;
|
|
57
|
+
/** Set when ok=true. The wamid Meta / web assigned to the outbound message. */
|
|
58
|
+
readonly wamid?: string;
|
|
59
|
+
readonly error?: {
|
|
60
|
+
readonly code: "auth_failed" | "rate_limit" | "invalid_request" | "server_error" | "timeout" | "unknown";
|
|
61
|
+
readonly message: string;
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Backend contract — every backend (cloud, web, future) implements this shape.
|
|
66
|
+
* `WhatsAppAdapter` delegates lifecycle + send + subscribe through this seam.
|
|
67
|
+
*/
|
|
68
|
+
interface WhatsAppBackend {
|
|
69
|
+
readonly kind: "cloud" | "web";
|
|
70
|
+
connect(): Promise<boolean>;
|
|
71
|
+
disconnect(): Promise<void>;
|
|
72
|
+
send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult$1>;
|
|
73
|
+
/** Subscribe to normalized inbound events. Returns unsubscribe. */
|
|
74
|
+
onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void;
|
|
75
|
+
/** Subscribe to status receipts. Returns unsubscribe. */
|
|
76
|
+
onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* `WhatsAppAdapter` — WhatsApp platform adapter for `@theokit/gateway`
|
|
81
|
+
* (Adoption Roadmap v1.4 #2; ADRs D303-D314).
|
|
82
|
+
*
|
|
83
|
+
* Multi-backend (Cloud + Web) — backend chosen via `WhatsAppAdapterOptions.backend`.
|
|
84
|
+
* Backend-agnostic adapter delegates lifecycle + send + subscribe through the
|
|
85
|
+
* `WhatsAppBackend` seam (D303).
|
|
86
|
+
*
|
|
87
|
+
* @public
|
|
88
|
+
*/
|
|
89
|
+
|
|
90
|
+
/** Cloud (Meta WhatsApp Business Cloud API) backend config (ADR D304). */
|
|
91
|
+
interface WhatsAppCloudConfig {
|
|
92
|
+
/** Meta system-user / phone-number access token. */
|
|
93
|
+
readonly accessToken: string;
|
|
94
|
+
/** Meta-issued phone-number-id (NOT the user-facing phone). */
|
|
95
|
+
readonly phoneNumberId: string;
|
|
96
|
+
/** App secret used to verify `X-Hub-Signature-256` on inbound webhooks. */
|
|
97
|
+
readonly appSecret: string;
|
|
98
|
+
/** Graph API version. Defaults to `v18.0`. */
|
|
99
|
+
readonly apiVersion?: string;
|
|
100
|
+
}
|
|
101
|
+
/** Web (whatsapp-web.js subprocess bridge) backend config (ADR D305). */
|
|
102
|
+
interface WhatsAppWebConfig {
|
|
103
|
+
/** Stable session id used to lock the bridge per-workspace. */
|
|
104
|
+
readonly sessionId: string;
|
|
105
|
+
/** Optional override of the bridge script path (defaults to packaged bridge). */
|
|
106
|
+
readonly bridgeScriptPath?: string;
|
|
107
|
+
}
|
|
108
|
+
/** Discriminated options shape (ADR D311). */
|
|
109
|
+
type WhatsAppAdapterOptions = {
|
|
110
|
+
readonly backend: "cloud";
|
|
111
|
+
readonly cloud: WhatsAppCloudConfig;
|
|
112
|
+
/** D309: require @mention in groups. Default `true`. */
|
|
113
|
+
readonly requireMention?: boolean;
|
|
114
|
+
/** Phone id to detect mentions of (digits only). Defaults to `cloud.phoneNumberId`. */
|
|
115
|
+
readonly botPhoneId?: string;
|
|
116
|
+
} | {
|
|
117
|
+
readonly backend: "web";
|
|
118
|
+
readonly web: WhatsAppWebConfig;
|
|
119
|
+
readonly requireMention?: boolean;
|
|
120
|
+
/** Phone id to detect mentions of (digits only). Required for groups in web mode. */
|
|
121
|
+
readonly botPhoneId?: string;
|
|
122
|
+
};
|
|
123
|
+
/** EC-7: digit-only normalizer for mention comparison (handles `+`, `-`, `()`, spaces). */
|
|
124
|
+
declare function digitsOnly(s: string): string;
|
|
125
|
+
/**
|
|
126
|
+
* Adapter façade. Implements `BasePlatformAdapter` (D172).
|
|
127
|
+
*
|
|
128
|
+
* Use `WhatsAppAdapter.fromCloud(config)` or `WhatsAppAdapter.fromWeb(config)`
|
|
129
|
+
* once the backend factories land (or pass `backend` directly in constructor).
|
|
130
|
+
*/
|
|
131
|
+
declare class WhatsAppAdapter extends BasePlatformAdapter {
|
|
132
|
+
readonly platform: "whatsapp";
|
|
133
|
+
private readonly backendImpl;
|
|
134
|
+
private readonly requireMention;
|
|
135
|
+
private readonly botPhoneId;
|
|
136
|
+
private handler?;
|
|
137
|
+
private statusHandler?;
|
|
138
|
+
private inboundUnsubscribe?;
|
|
139
|
+
private statusUnsubscribe?;
|
|
140
|
+
/** Construct from a pre-built backend (used by the static factories + tests). */
|
|
141
|
+
constructor(backendImpl: WhatsAppBackend, opts?: {
|
|
142
|
+
requireMention?: boolean;
|
|
143
|
+
botPhoneId?: string;
|
|
144
|
+
});
|
|
145
|
+
/** Escape hatch (D180-style) for advanced features. */
|
|
146
|
+
getBackend(): WhatsAppBackend;
|
|
147
|
+
connect(): Promise<boolean>;
|
|
148
|
+
disconnect(): Promise<void>;
|
|
149
|
+
sendMessage(out: OutboundMessage): Promise<SendResult>;
|
|
150
|
+
/** D309 + EC-7: group filter with digit-only normalization. */
|
|
151
|
+
private shouldDropGroupMessage;
|
|
152
|
+
private toMessageEvent;
|
|
153
|
+
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
154
|
+
/** Status receipts (sent/delivered/read/failed). Adapter-specific (D307). */
|
|
155
|
+
onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* `WhatsAppCloudBackend` — Meta WhatsApp Business Cloud API backend (ADR D304).
|
|
160
|
+
*
|
|
161
|
+
* `connect()` / `disconnect()` are no-ops (HTTP push via webhook is the only
|
|
162
|
+
* inbound channel). Outbound delegates to `WhatsAppCloudClient`. Inbound
|
|
163
|
+
* dispatch is driven by the user calling `handleWebhookPayload(rawBody, sig)`
|
|
164
|
+
* from inside their HTTP route.
|
|
165
|
+
*
|
|
166
|
+
* @public
|
|
167
|
+
*/
|
|
168
|
+
|
|
169
|
+
interface WhatsAppCloudBackendOptions {
|
|
170
|
+
readonly accessToken: string;
|
|
171
|
+
readonly phoneNumberId: string;
|
|
172
|
+
readonly appSecret: string;
|
|
173
|
+
readonly apiVersion?: string;
|
|
174
|
+
/** Test seam. */
|
|
175
|
+
readonly fetch?: typeof fetch;
|
|
176
|
+
}
|
|
177
|
+
declare class WhatsAppCloudBackend implements WhatsAppBackend {
|
|
178
|
+
readonly kind: "cloud";
|
|
179
|
+
private readonly client;
|
|
180
|
+
private readonly appSecret;
|
|
181
|
+
private inboundHandler?;
|
|
182
|
+
private statusHandler?;
|
|
183
|
+
constructor(opts: WhatsAppCloudBackendOptions);
|
|
184
|
+
connect(): Promise<boolean>;
|
|
185
|
+
disconnect(): Promise<void>;
|
|
186
|
+
send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult$1>;
|
|
187
|
+
onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void;
|
|
188
|
+
onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void;
|
|
189
|
+
/**
|
|
190
|
+
* Webhook entrypoint. The user calls this from inside their POST /webhook
|
|
191
|
+
* route after `verifyWebhookSubscription` on GET.
|
|
192
|
+
*
|
|
193
|
+
* @returns `true` if signature valid + dispatched (or empty payload).
|
|
194
|
+
* `false` if signature invalid (route should return 401).
|
|
195
|
+
*/
|
|
196
|
+
handleWebhookPayload(rawBody: Buffer | string, signatureHeader: string | undefined): Promise<boolean>;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Inbound webhook payload — the full envelope Meta POSTs. */
|
|
200
|
+
interface MetaWebhookEnvelope {
|
|
201
|
+
readonly object: string;
|
|
202
|
+
readonly entry: ReadonlyArray<MetaWebhookEntry>;
|
|
203
|
+
}
|
|
204
|
+
interface MetaWebhookEntry {
|
|
205
|
+
readonly id: string;
|
|
206
|
+
readonly changes: ReadonlyArray<MetaWebhookChange>;
|
|
207
|
+
}
|
|
208
|
+
interface MetaWebhookChange {
|
|
209
|
+
readonly value: MetaWebhookValue;
|
|
210
|
+
readonly field: string;
|
|
211
|
+
}
|
|
212
|
+
interface MetaWebhookValue {
|
|
213
|
+
readonly messaging_product: "whatsapp";
|
|
214
|
+
readonly metadata: {
|
|
215
|
+
readonly display_phone_number: string;
|
|
216
|
+
readonly phone_number_id: string;
|
|
217
|
+
};
|
|
218
|
+
readonly contacts?: ReadonlyArray<{
|
|
219
|
+
readonly profile: {
|
|
220
|
+
readonly name?: string;
|
|
221
|
+
};
|
|
222
|
+
readonly wa_id: string;
|
|
223
|
+
}>;
|
|
224
|
+
readonly messages?: ReadonlyArray<MetaIncomingMessage>;
|
|
225
|
+
readonly statuses?: ReadonlyArray<MetaStatusUpdate>;
|
|
226
|
+
}
|
|
227
|
+
interface MetaIncomingMessage {
|
|
228
|
+
readonly from: string;
|
|
229
|
+
readonly id: string;
|
|
230
|
+
readonly timestamp: string;
|
|
231
|
+
readonly type: string;
|
|
232
|
+
readonly text?: {
|
|
233
|
+
readonly body: string;
|
|
234
|
+
};
|
|
235
|
+
readonly context?: {
|
|
236
|
+
readonly from: string;
|
|
237
|
+
readonly id: string;
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
interface MetaStatusUpdate {
|
|
241
|
+
readonly id: string;
|
|
242
|
+
readonly status: "sent" | "delivered" | "read" | "failed";
|
|
243
|
+
readonly timestamp: string;
|
|
244
|
+
readonly recipient_id: string;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Webhook helpers for Meta WhatsApp Business Cloud API (ADR D306, D312).
|
|
249
|
+
*
|
|
250
|
+
* Two boundaries:
|
|
251
|
+
* 1. GET handshake — `verifyWebhookSubscription` (EC-1).
|
|
252
|
+
* 2. POST callbacks — `verifyWebhookSignature` (EC-3 length guard) +
|
|
253
|
+
* `normalizeInboundMessages` (EC-4 text-only filter) +
|
|
254
|
+
* `normalizeStatusReceipts`.
|
|
255
|
+
*
|
|
256
|
+
* The user owns the HTTP route; we expose pure helpers they call from inside it.
|
|
257
|
+
*
|
|
258
|
+
* @public
|
|
259
|
+
*/
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Verify Meta's GET `/webhook?hub.mode=subscribe&hub.challenge=...&hub.verify_token=...`
|
|
263
|
+
* handshake (EC-1 absorbed).
|
|
264
|
+
*
|
|
265
|
+
* @returns `query["hub.challenge"]` when valid, `null` otherwise. The caller
|
|
266
|
+
* echoes the challenge as `text/plain` on success.
|
|
267
|
+
*/
|
|
268
|
+
declare function verifyWebhookSubscription(query: Record<string, string | undefined>, expectedVerifyToken: string): string | null;
|
|
269
|
+
/**
|
|
270
|
+
* Verify the `X-Hub-Signature-256` HMAC-SHA256 against the app secret (D312).
|
|
271
|
+
*
|
|
272
|
+
* EC-3 absorbed: length-guard BEFORE `timingSafeEqual` so a malformed header
|
|
273
|
+
* (e.g. `sha256=ab`) returns `false` instead of throwing `RangeError` (DoS).
|
|
274
|
+
*
|
|
275
|
+
* @returns `true` iff the signature matches.
|
|
276
|
+
*/
|
|
277
|
+
declare function verifyWebhookSignature(rawBody: Buffer | string, signatureHeader: string | undefined, appSecret: string): boolean;
|
|
278
|
+
/** Parse the raw JSON payload into a typed envelope. Returns `null` if shape is unrecognized. */
|
|
279
|
+
declare function parseWebhookPayload(json: unknown): MetaWebhookEnvelope | null;
|
|
280
|
+
declare function normalizeInboundMessages(envelope: MetaWebhookEnvelope): WhatsAppInboundEvent[];
|
|
281
|
+
/** Normalize status updates → `WhatsAppStatusReceipt[]`. */
|
|
282
|
+
declare function normalizeStatusReceipts(envelope: MetaWebhookEnvelope): WhatsAppStatusReceipt[];
|
|
283
|
+
|
|
284
|
+
interface BridgeHandle {
|
|
285
|
+
readonly child: ChildProcess;
|
|
286
|
+
readonly pidFilePath: string;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* `WhatsAppWebBackend` — `whatsapp-web.js` subprocess bridge backend (ADR D305).
|
|
291
|
+
*
|
|
292
|
+
* Lifecycle (T3.1) + IPC (T3.2) wired behind the `WhatsAppBackend` interface.
|
|
293
|
+
* EC-6 absorbed: `connect()` races against a 120s timeout so unattended QR
|
|
294
|
+
* pairings fail fast instead of hanging the app.
|
|
295
|
+
*
|
|
296
|
+
* @public
|
|
297
|
+
*/
|
|
298
|
+
|
|
299
|
+
interface WhatsAppWebBackendOptions {
|
|
300
|
+
readonly sessionId: string;
|
|
301
|
+
/** Override the default bridge script path. Defaults to bundled script. */
|
|
302
|
+
readonly bridgeScriptPath?: string;
|
|
303
|
+
/** EC-6 connect timeout in ms. Default 120000. */
|
|
304
|
+
readonly connectTimeoutMs?: number;
|
|
305
|
+
/** Per-send timeout in ms. Default 30000. */
|
|
306
|
+
readonly sendTimeoutMs?: number;
|
|
307
|
+
/** Test seam: override the spawned child via a factory. */
|
|
308
|
+
readonly spawnFactory?: () => BridgeHandle;
|
|
309
|
+
/** Test seam: theokit home for PID locks. */
|
|
310
|
+
readonly theokitHome?: string;
|
|
311
|
+
}
|
|
312
|
+
declare class WhatsAppWebBackend implements WhatsAppBackend {
|
|
313
|
+
private readonly opts;
|
|
314
|
+
readonly kind: "web";
|
|
315
|
+
private handle?;
|
|
316
|
+
private readonly buffer;
|
|
317
|
+
private inboundHandler?;
|
|
318
|
+
private statusHandler?;
|
|
319
|
+
private readonly pending;
|
|
320
|
+
private msgIdCounter;
|
|
321
|
+
private botPhone?;
|
|
322
|
+
private connected;
|
|
323
|
+
private readyResolvers;
|
|
324
|
+
constructor(opts: WhatsAppWebBackendOptions);
|
|
325
|
+
private spawnBridgeHandle;
|
|
326
|
+
private wireStdout;
|
|
327
|
+
private cleanupHandle;
|
|
328
|
+
connect(): Promise<boolean>;
|
|
329
|
+
disconnect(): Promise<void>;
|
|
330
|
+
send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult$1>;
|
|
331
|
+
onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void;
|
|
332
|
+
onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void;
|
|
333
|
+
private handleReady;
|
|
334
|
+
private handleMessage;
|
|
335
|
+
private handleSendAck;
|
|
336
|
+
private handleStatus;
|
|
337
|
+
private dispatch;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* IPC protocol between adapter and `whatsapp-web.js` subprocess bridge.
|
|
342
|
+
*
|
|
343
|
+
* Wire: stdin/stdout JSON-lines (each message terminated by `\n`).
|
|
344
|
+
*
|
|
345
|
+
* @internal
|
|
346
|
+
*/
|
|
347
|
+
/** Commands the adapter sends to the bridge. */
|
|
348
|
+
type IpcCommand = {
|
|
349
|
+
readonly cmd: "send";
|
|
350
|
+
readonly msgId: string;
|
|
351
|
+
readonly to: string;
|
|
352
|
+
readonly text: string;
|
|
353
|
+
} | {
|
|
354
|
+
readonly cmd: "shutdown";
|
|
355
|
+
};
|
|
356
|
+
/** Events the bridge emits to the adapter. */
|
|
357
|
+
type IpcEvent = {
|
|
358
|
+
readonly event: "ready";
|
|
359
|
+
readonly botPhone: string;
|
|
360
|
+
} | {
|
|
361
|
+
readonly event: "message";
|
|
362
|
+
readonly msgId: string;
|
|
363
|
+
readonly from: string;
|
|
364
|
+
readonly body: string;
|
|
365
|
+
readonly isGroup: boolean;
|
|
366
|
+
readonly chatId: string;
|
|
367
|
+
readonly contactName?: string;
|
|
368
|
+
readonly timestamp: number;
|
|
369
|
+
} | {
|
|
370
|
+
readonly event: "send_ack";
|
|
371
|
+
readonly msgId: string;
|
|
372
|
+
readonly success: boolean;
|
|
373
|
+
readonly wamid?: string;
|
|
374
|
+
readonly error?: string;
|
|
375
|
+
} | {
|
|
376
|
+
readonly event: "status";
|
|
377
|
+
readonly msgId: string;
|
|
378
|
+
readonly status: "sent" | "delivered" | "read" | "failed";
|
|
379
|
+
readonly recipient: string;
|
|
380
|
+
readonly timestamp: number;
|
|
381
|
+
} | {
|
|
382
|
+
readonly event: "error";
|
|
383
|
+
readonly message: string;
|
|
384
|
+
};
|
|
385
|
+
/** Parse one JSON-line. Returns null on malformed. */
|
|
386
|
+
declare function parseEvent(line: string): IpcEvent | null;
|
|
387
|
+
/** Format an outbound command as JSON + newline. */
|
|
388
|
+
declare function formatCommand(cmd: IpcCommand): string;
|
|
389
|
+
/**
|
|
390
|
+
* Line buffer — accumulates stdout chunks until `\n` boundaries, yields
|
|
391
|
+
* complete lines. Addresses EC-11 (chunked stdout across multiple reads).
|
|
392
|
+
*/
|
|
393
|
+
declare class LineBuffer {
|
|
394
|
+
private buffer;
|
|
395
|
+
push(chunk: string): string[];
|
|
396
|
+
/** Test seam — current pending bytes. */
|
|
397
|
+
get pending(): string;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* Per-backend HTTP/IPC error → canonical `WhatsAppSendResult.error` shape.
|
|
402
|
+
*
|
|
403
|
+
* Cloud follows Meta error codes (https://developers.facebook.com/docs/graph-api/guides/error-handling).
|
|
404
|
+
* Web follows whatsapp-web.js error strings.
|
|
405
|
+
*
|
|
406
|
+
* @internal
|
|
407
|
+
*/
|
|
408
|
+
type ErrorPayload = Required<WhatsAppSendResult>["error"];
|
|
409
|
+
/** Custom error: `connect()` timed out waiting for "ready" (EC-6). */
|
|
410
|
+
declare class WhatsAppConnectTimeoutError extends Error {
|
|
411
|
+
constructor(timeoutMs: number);
|
|
412
|
+
}
|
|
413
|
+
declare function mapWhatsAppCloudError(status: number, body: unknown): ErrorPayload;
|
|
414
|
+
declare function mapWhatsAppWebError(ipcError: string | undefined): ErrorPayload;
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Split a long string into ≤4096-char chunks for WhatsApp messages (ADR D310).
|
|
418
|
+
*
|
|
419
|
+
* Break preference: `\n\n` → `\n` → ` `. UTF-16 surrogate-pair guard.
|
|
420
|
+
*
|
|
421
|
+
* EC-8 absorbed: empty parts are filtered out at the end so consecutive
|
|
422
|
+
* newlines don't produce empty `sendMessage` calls Meta would reject.
|
|
423
|
+
*
|
|
424
|
+
* @internal
|
|
425
|
+
*/
|
|
426
|
+
declare function splitForWhatsApp(text: string): string[];
|
|
427
|
+
|
|
428
|
+
export { type IpcCommand, type IpcEvent, LineBuffer, WhatsAppAdapter, type WhatsAppAdapterOptions, type WhatsAppBackend, WhatsAppCloudBackend, type WhatsAppCloudBackendOptions, type WhatsAppCloudConfig, WhatsAppConnectTimeoutError, type WhatsAppInboundEvent, type WhatsAppOutboundMessage, type WhatsAppSendResult$1 as WhatsAppSendResult, type WhatsAppStatusReceipt, WhatsAppWebBackend, type WhatsAppWebBackendOptions, type WhatsAppWebConfig, digitsOnly, formatCommand, mapWhatsAppCloudError, mapWhatsAppWebError, normalizeInboundMessages, normalizeStatusReceipts, parseEvent, parseWebhookPayload, splitForWhatsApp, verifyWebhookSignature, verifyWebhookSubscription };
|