@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.
@@ -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 };