@theokit/gateway-whatsapp 0.1.2 → 0.2.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/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent } from '@theokit/gateway';
1
+ import type { ChildProcess } from 'node:child_process';
2
+ import { GatewayConfigurationError, GatewayConfigurationErrorOptions, BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent } from '@theokit/gateway';
2
3
  export { WhatsAppMessageEvent } from '@theokit/gateway';
3
4
 
4
5
  /**
@@ -27,7 +28,7 @@ interface WhatsAppInboundEvent {
27
28
  /** Receipt timestamp (ms since epoch). */
28
29
  readonly receivedAt: number;
29
30
  /** Backend that emitted this event. */
30
- readonly backend: "cloud" | "web";
31
+ readonly backend: "cloud" | "web" | "baileys";
31
32
  /** Raw envelope for the escape hatch. */
32
33
  readonly raw: unknown;
33
34
  }
@@ -52,12 +53,27 @@ interface WhatsAppStatusReceipt {
52
53
  readonly timestamp: number;
53
54
  }
54
55
  /** Per-message send result returned by `WhatsAppBackend.send`. */
55
- interface WhatsAppSendResult$1 {
56
+ interface WhatsAppSendResult {
56
57
  readonly ok: boolean;
57
58
  /** Set when ok=true. The wamid Meta / web assigned to the outbound message. */
58
59
  readonly wamid?: string;
59
60
  readonly error?: {
60
- readonly code: "auth_failed" | "rate_limit" | "invalid_request" | "server_error" | "timeout" | "unknown";
61
+ readonly code: "auth_failed" | "rate_limit" | "invalid_request"
62
+ /**
63
+ * More than 24 hours since the recipient last replied. The payload was
64
+ * fine and the credential is fine; WhatsApp policy refuses free-form text
65
+ * outside that window. The remedy is specific and different from every
66
+ * other error here — resend as an approved template — which is why it is
67
+ * its own code rather than one more `invalid_request`.
68
+ */
69
+ | "session_window_expired"
70
+ /**
71
+ * The recipient cannot receive this message, and no retry changes that:
72
+ * no WhatsApp account, terms not accepted, an outdated client, or the
73
+ * business having blocked them. Terminal by nature; the cause is in the
74
+ * message.
75
+ */
76
+ | "undeliverable" | "server_error" | "timeout" | "unknown";
61
77
  readonly message: string;
62
78
  };
63
79
  }
@@ -66,10 +82,10 @@ interface WhatsAppSendResult$1 {
66
82
  * `WhatsAppAdapter` delegates lifecycle + send + subscribe through this seam.
67
83
  */
68
84
  interface WhatsAppBackend {
69
- readonly kind: "cloud" | "web";
85
+ readonly kind: "cloud" | "web" | "baileys";
70
86
  connect(): Promise<boolean>;
71
87
  disconnect(): Promise<void>;
72
- send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult$1>;
88
+ send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult>;
73
89
  /** Subscribe to normalized inbound events. Returns unsubscribe. */
74
90
  onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void;
75
91
  /** Subscribe to status receipts. Returns unsubscribe. */
@@ -98,6 +114,35 @@ interface WhatsAppCloudConfig {
98
114
  /** Graph API version. Defaults to `v18.0`. */
99
115
  readonly apiVersion?: string;
100
116
  }
117
+ /**
118
+ * Baileys backend config (ADR D319-D322).
119
+ *
120
+ * Unofficial, like the `web` backend: it automates a WhatsApp Web session, which Meta's terms
121
+ * do not sanction and which can get a number banned. Unlike `web` it needs no browser.
122
+ *
123
+ * @public
124
+ */
125
+ interface WhatsAppBaileysConfig {
126
+ /**
127
+ * Directory holding the multi-file auth state — the pairing, persisted.
128
+ *
129
+ * Treat it like a credential: it IS the session, and anyone holding it is the account.
130
+ */
131
+ readonly sessionDir: string;
132
+ /** Give up on `connect()` after this long. Default 60s. */
133
+ readonly connectTimeoutMs?: number;
134
+ /** Give up on one send after this long. Default 30s. */
135
+ readonly sendTimeoutMs?: number;
136
+ /**
137
+ * Where the pairing QR goes, as often as WhatsApp reissues it. Defaults to stderr.
138
+ *
139
+ * The backend has always accepted this; it was reachable only by constructing the backend by
140
+ * hand, which is the path this class exists to replace. A host that is not a terminal — a
141
+ * service, a container, a web app — cannot read stderr back to the person holding the phone,
142
+ * and without a route out the QR a fresh `sessionDir` can only ever time out.
143
+ */
144
+ readonly onQr?: (qr: string) => void;
145
+ }
101
146
  /** Web (whatsapp-web.js subprocess bridge) backend config (ADR D305). */
102
147
  interface WhatsAppWebConfig {
103
148
  /** Stable session id used to lock the bridge per-workspace. */
@@ -105,50 +150,149 @@ interface WhatsAppWebConfig {
105
150
  /** Optional override of the bridge script path (defaults to packaged bridge). */
106
151
  readonly bridgeScriptPath?: string;
107
152
  }
108
- /** Discriminated options shape (ADR D311). */
153
+ /**
154
+ * Which backend to build, and its configuration.
155
+ *
156
+ * The union carries only what DIFFERS between backends. Options that mean the same thing on
157
+ * either one — `requireMention`, `botPhoneId`, `allowedSenders` — live in
158
+ * {@link WhatsAppAdapterCommonOptions} instead, so there is one copy rather than one per arm
159
+ * for the two copies to drift apart (ADR D318).
160
+ *
161
+ * @public
162
+ */
109
163
  type WhatsAppAdapterOptions = {
110
164
  readonly backend: "cloud";
111
165
  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
166
  } | {
117
167
  readonly backend: "web";
118
168
  readonly web: WhatsAppWebConfig;
169
+ } | {
170
+ readonly backend: "baileys";
171
+ readonly baileys: WhatsAppBaileysConfig;
172
+ };
173
+ /**
174
+ * Options that apply whichever backend is in use.
175
+ *
176
+ * @public
177
+ */
178
+ interface WhatsAppAdapterCommonOptions {
179
+ /** D309: require an @mention in groups. Default `true`. */
119
180
  readonly requireMention?: boolean;
120
- /** Phone id to detect mentions of (digits only). Required for groups in web mode. */
181
+ /**
182
+ * Phone id to detect mentions of (digits only).
183
+ *
184
+ * `fromCloud` defaults it to the phone number id. **The web backend has nothing to default
185
+ * from**, so leaving it unset there while `requireMention` is on (its default) drops every
186
+ * group message — the adapter cannot tell whether it was mentioned. That drop is now
187
+ * logged rather than silent.
188
+ */
121
189
  readonly botPhoneId?: string;
122
- };
190
+ /**
191
+ * Comma-separated senders allowed to reach the handler. Absent leaves delivery unchanged;
192
+ * an empty string admits nobody. See `allowlist.ts` for why those differ.
193
+ */
194
+ readonly allowedSenders?: string;
195
+ }
123
196
  /** EC-7: digit-only normalizer for mention comparison (handles `+`, `-`, `()`, spaces). */
124
197
  declare function digitsOnly(s: string): string;
125
198
  /**
126
199
  * Adapter facade. Implements `BasePlatformAdapter` (D172).
127
200
  *
128
- * Use `WhatsAppAdapter.fromCloud(config)` or `WhatsAppAdapter.fromWeb(config)`
129
- * once the backend factories land (or pass `backend` directly in constructor).
201
+ * Use `WhatsAppAdapter.fromCloud(config)` or `WhatsAppAdapter.fromWeb(config)`. The
202
+ * constructor stays available for tests and for a backend of your own.
130
203
  */
131
204
  declare class WhatsAppAdapter extends BasePlatformAdapter {
132
205
  readonly platform: "whatsapp";
133
206
  private readonly backendImpl;
134
207
  private readonly requireMention;
135
208
  private readonly botPhoneId;
209
+ /** `undefined` = no allowlist configured; a set = configured, and enforced fail-closed. */
210
+ private readonly allowedSenders;
136
211
  /** Mirrors the sibling adapters: guards connect() against opening a second session. */
137
212
  private connected;
138
213
  private handler?;
139
214
  private statusHandler?;
140
215
  private inboundUnsubscribe?;
141
216
  private statusUnsubscribe?;
142
- /** Construct from a pre-built backend (used by the static factories + tests). */
143
- constructor(backendImpl: WhatsAppBackend, opts?: {
144
- requireMention?: boolean;
145
- botPhoneId?: string;
146
- });
217
+ /**
218
+ * Build an adapter from a discriminated configuration.
219
+ *
220
+ * The entry point for configuration that arrives as **data** — read from a file, an
221
+ * environment, or a tenant record — where the backend is a string rather than a decision
222
+ * made in code. `fromCloud` / `fromWeb` are the direct forms when the choice is already
223
+ * known at the call site.
224
+ *
225
+ * This is what `WhatsAppAdapterOptions` exists for. Until it had this consumer the union
226
+ * was exported, documented and inert, which is the defect #47 was filed about, and the
227
+ * first attempt at closing that issue left it inert — the factories took the config halves
228
+ * directly and never the union.
229
+ *
230
+ * @throws {ConfigurationError} when a required option is missing or empty.
231
+ * @public
232
+ */
233
+ static from(options: WhatsAppAdapterOptions, common?: WhatsAppAdapterCommonOptions): WhatsAppAdapter;
234
+ /**
235
+ * Build a Baileys adapter.
236
+ *
237
+ * Unofficial, and no amount of code changes that: it automates a WhatsApp Web session,
238
+ * which Meta's terms do not sanction and which can get a number banned. Use a number
239
+ * created for this, never a personal one. Prefer {@link WhatsAppAdapter.fromCloud} unless
240
+ * the number has no Cloud API access.
241
+ *
242
+ * Unlike {@link WhatsAppAdapter.fromWeb} it embeds no browser — it speaks the multi-device
243
+ * protocol over a WebSocket. `baileys` is an optional peer dependency; it is loaded lazily
244
+ * at connect, so a consumer who never calls this never needs it installed.
245
+ *
246
+ * `botPhoneId` has nothing to default from here, so leaving it unset while `requireMention`
247
+ * is on (its default) drops every group message. The adapter logs when it does.
248
+ *
249
+ * @throws {ConfigurationError} when `sessionDir` is missing or empty.
250
+ * @public
251
+ */
252
+ static fromBaileys(baileys: WhatsAppBaileysConfig, opts?: WhatsAppAdapterCommonOptions): WhatsAppAdapter;
253
+ /**
254
+ * Build a Cloud-API adapter.
255
+ *
256
+ * The construction path this package's docblock has named since it was written, and which
257
+ * did not exist until #47 — a consumer following the only guidance the package gave wrote
258
+ * code that would not compile.
259
+ *
260
+ * Prefer it over the constructor: it keeps `WhatsAppCloudBackend` an implementation detail
261
+ * of this package rather than something every consumer imports and assembles.
262
+ *
263
+ * @throws {ConfigurationError} when a required credential is missing or empty.
264
+ * @public
265
+ */
266
+ static fromCloud(cloud: WhatsAppCloudConfig, opts?: WhatsAppAdapterCommonOptions): WhatsAppAdapter;
267
+ /**
268
+ * Build a WhatsApp-Web adapter.
269
+ *
270
+ * Unofficial: it drives a real WhatsApp Web session through a browser, which Meta's terms
271
+ * do not sanction and which can get a number banned. It also needs a browser this package
272
+ * does not install. Prefer {@link WhatsAppAdapter.fromCloud} unless the number has no
273
+ * Cloud API access.
274
+ *
275
+ * @throws {ConfigurationError} when `sessionId` is missing or empty.
276
+ * @public
277
+ */
278
+ static fromWeb(web: WhatsAppWebConfig, opts?: WhatsAppAdapterCommonOptions): WhatsAppAdapter;
279
+ /** Construct from a pre-built backend. Prefer the factories; this is for tests and for a custom backend. */
280
+ constructor(backendImpl: WhatsAppBackend, opts?: WhatsAppAdapterCommonOptions);
147
281
  /** Escape hatch (D180-style) for advanced features. */
148
282
  getBackend(): WhatsAppBackend;
149
283
  connect(): Promise<boolean>;
150
284
  disconnect(): Promise<void>;
151
285
  sendMessage(out: OutboundMessage): Promise<SendResult>;
286
+ /**
287
+ * Is this sender refused by a configured allowlist?
288
+ *
289
+ * Runs before the group/mention filter because it answers a different question: that one asks
290
+ * whether a message was meant for us, this one asks whether the sender may reach us at all.
291
+ *
292
+ * The refusal is logged. A silent drop is indistinguishable from a broken gateway, and the
293
+ * first thing a mistyped allowlist causes is an operator wondering why the bot went mute.
294
+ */
295
+ private isRefusedBySenderAllowlist;
152
296
  /** D309 + EC-7: group filter with digit-only normalization. */
153
297
  private shouldDropGroupMessage;
154
298
  private toMessageEvent;
@@ -158,44 +302,233 @@ declare class WhatsAppAdapter extends BasePlatformAdapter {
158
302
  }
159
303
 
160
304
  /**
161
- * `WhatsAppCloudBackend` — Meta WhatsApp Business Cloud API backend (ADR D304).
305
+ * The socket contract this backend depends on, and the real factory behind it (ADR D319).
162
306
  *
163
- * `connect()` / `disconnect()` are no-ops (HTTP push via webhook is the only
164
- * inbound channel). Outbound delegates to `WhatsAppCloudClient`. Inbound
165
- * dispatch is driven by the user calling `handleWebhookPayload(rawBody, sig)`
166
- * from inside their HTTP route.
307
+ * Three members, not Baileys' whole `WASocket`. Two things follow, and both are the reason
308
+ * the contract is ours rather than the library's.
309
+ *
310
+ * It was five, and two rounds of review took two members off it, both declared and called by
311
+ * nothing. `logout()` went first and mattered most: on WhatsApp it UNPAIRS the device, the
312
+ * opposite of what `disconnect()` means here, so the next person needing a teardown would find
313
+ * it, call it, and lose the session the whole `sessionDir` exists to keep. `ev.off()` went for
314
+ * the plain reason — nothing removed a listener, because a socket is discarded whole rather
315
+ * than unsubscribed from. Neither was a capability we had; both read as one.
316
+ *
317
+ * **The backend is testable with `baileys` absent.** It is an optional peer dependency, so
318
+ * CI does not install it — and a backend that could only be exercised with the real library
319
+ * installed would be exercised by nothing, which is how the `web` backend reached production
320
+ * unable to start (B-002).
321
+ *
322
+ * **The library stays an implementation detail of this file.** A breaking change upstream
323
+ * lands in one place instead of wherever its types had spread. Depending on all of `WASocket`
324
+ * to call three of its members is the interface-segregation problem stated plainly
325
+ * (`rules/architecture.md`).
326
+ *
327
+ * @internal
328
+ */
329
+ /** A Baileys connection-state update, narrowed to what the lifecycle reads. */
330
+ interface BaileysConnectionUpdate {
331
+ readonly connection?: "close" | "connecting" | "open";
332
+ readonly qr?: string;
333
+ readonly lastDisconnect?: {
334
+ readonly error?: unknown;
335
+ };
336
+ }
337
+ /** The events this backend subscribes to. Anything else Baileys emits is ignored. */
338
+ interface BaileysEventMap {
339
+ "connection.update": BaileysConnectionUpdate;
340
+ "messages.upsert": {
341
+ readonly messages: readonly unknown[];
342
+ readonly type?: string;
343
+ };
344
+ "creds.update": unknown;
345
+ }
346
+ /**
347
+ * What this backend needs a socket to be.
348
+ *
349
+ * Deliberately structural: any object with these members satisfies it, which is what lets a
350
+ * test hand over a fake without importing anything from Baileys.
351
+ */
352
+ interface BaileysSocketLike {
353
+ readonly ev: {
354
+ on<K extends keyof BaileysEventMap>(event: K, listener: (payload: BaileysEventMap[K]) => void): void;
355
+ };
356
+ sendMessage(jid: string, content: {
357
+ text: string;
358
+ }): Promise<{
359
+ key?: {
360
+ id?: string;
361
+ };
362
+ } | undefined>;
363
+ end?(error?: Error): void;
364
+ }
365
+ /** How a socket comes into being. Replaced wholesale in tests. */
366
+ type BaileysSocketFactory = (opts: BaileysSocketOptions) => Promise<BaileysSocketLike>;
367
+ /** What the real factory needs to build a socket. */
368
+ interface BaileysSocketOptions {
369
+ /** Directory holding the multi-file auth state — the pairing, persisted. */
370
+ readonly sessionDir: string;
371
+ /** Overrides the module the factory loads. Tests point it at a stub; production never sets it. */
372
+ readonly specifier?: string;
373
+ /**
374
+ * Called with the pairing QR, as often as WhatsApp reissues it.
375
+ *
376
+ * Without somewhere for this to go, a fresh `sessionDir` can only ever time out: there is
377
+ * no other way to pair, and `printQRInTerminal` is off because a library writing to stdout
378
+ * is a library deciding where a host application's output goes. Defaults to writing the
379
+ * code to **stderr**, which is what the `web` bridge does and what keeps stdout free for a
380
+ * host that is using it for something.
381
+ */
382
+ readonly onQr?: (qr: string) => void;
383
+ }
384
+ /**
385
+ * Build a real Baileys socket.
386
+ *
387
+ * The import shape follows what B-002 cost this repository to learn: read the API off the
388
+ * default export first, check each member is callable, and report a structured error naming
389
+ * the one that is missing. A `try/catch` around the import guards the package being absent,
390
+ * not a member being undefined — and that gap is what killed the `web` bridge for months
391
+ * behind a friendly "not installed" message that was false.
392
+ *
393
+ * The socket settings are ADR D322, each for a stated consequence rather than a precedent:
394
+ * `markOnlineOnConnect: false` so the account does not read as permanently online and
395
+ * suppress push notifications on the owner's real phone; `syncFullHistory: false` so a
396
+ * connect does not pull the entire history; an honest `browser` triple; and the protocol
397
+ * version fetched at connect, because a stale one is refused by the server.
398
+ */
399
+ declare function createBaileysSocket(opts: BaileysSocketOptions): Promise<BaileysSocketLike>;
400
+
401
+ /**
402
+ * `WhatsAppBaileysBackend` — the third implementation of `WhatsAppBackend` (B-001).
403
+ *
404
+ * Baileys speaks the WhatsApp Web multi-device protocol over a WebSocket, with no browser.
405
+ * That is the whole difference from the `web` backend, which drives a headless Chromium.
406
+ *
407
+ * **Unofficial, and no amount of code changes that.** It automates a WhatsApp Web session,
408
+ * which Meta's terms do not sanction and which can get a number banned. Use a number created
409
+ * for this, never a personal one. Prefer {@link WhatsAppCloudBackend} unless the number has
410
+ * no Cloud API access.
411
+ *
412
+ * **Added rather than replacing**, for three reasons that a substitution would not give:
413
+ * nobody loses a paired session (a Puppeteer profile and a multi-file auth state are not
414
+ * interchangeable), the comparison against the incumbent becomes measurable rather than
415
+ * asserted, and retreat stays cheap because nobody is forced onto it.
167
416
  *
168
417
  * @public
169
418
  */
170
419
 
171
- interface WhatsAppCloudBackendOptions {
172
- readonly accessToken: string;
173
- readonly phoneNumberId: string;
174
- readonly appSecret: string;
175
- readonly apiVersion?: string;
176
- /** Test seam. */
177
- readonly fetch?: typeof fetch;
420
+ /** Construction options. @public */
421
+ interface WhatsAppBaileysBackendOptions {
422
+ /**
423
+ * Directory holding the multi-file auth state — the pairing, persisted.
424
+ *
425
+ * Treat it like a credential: it is the session, and anyone holding it is the account.
426
+ */
427
+ readonly sessionDir: string;
428
+ /** Give up on `connect()` after this long. Default 60s. */
429
+ readonly connectTimeoutMs?: number;
430
+ /** Give up on one send after this long. Default 30s. */
431
+ readonly sendTimeoutMs?: number;
432
+ /** Test seam: build the socket some other way. Production leaves it unset. */
433
+ readonly socketFactory?: BaileysSocketFactory;
434
+ /**
435
+ * Where the pairing QR goes, as often as WhatsApp reissues it.
436
+ *
437
+ * Defaults to stderr. It is exposed here because a host that is not a terminal — a service, a
438
+ * container, a web app — has no way to read stderr back to the person holding the phone, and
439
+ * without a route out the QR the session can never be paired.
440
+ */
441
+ readonly onQr?: (qr: string) => void;
178
442
  }
179
- declare class WhatsAppCloudBackend implements WhatsAppBackend {
180
- readonly kind: "cloud";
181
- private readonly client;
182
- private readonly appSecret;
443
+ /**
444
+ * A WhatsApp backend that speaks the multi-device protocol directly.
445
+ *
446
+ * No browser: where {@link WhatsAppWebBackend} drives a headless Chromium through
447
+ * `whatsapp-web.js`, this holds a WebSocket. That is the whole difference in kind.
448
+ *
449
+ * **Unofficial, and no amount of code changes that.** It automates a WhatsApp Web session,
450
+ * which Meta's terms do not sanction and which can get a number banned. Use a number created
451
+ * for this and nothing else — never a personal one. Prefer the Cloud API backend unless the
452
+ * number has no Cloud API access.
453
+ *
454
+ * `baileys` is an optional peer dependency, loaded lazily at connect, so a consumer who never
455
+ * constructs this never needs it installed.
456
+ *
457
+ * @public
458
+ */
459
+ declare class WhatsAppBaileysBackend implements WhatsAppBackend {
460
+ private readonly opts;
461
+ readonly kind: "baileys";
462
+ private socket?;
463
+ private connected;
464
+ /** Guards a concurrent second `connect()` from opening a second live session. */
465
+ private connecting?;
466
+ /**
467
+ * Which connection attempt is current.
468
+ *
469
+ * Bumped by every `connect()` and every `disconnect()`. A socket from a superseded attempt
470
+ * checks it before touching any state, which is what stops an abandoned socket delivering
471
+ * inbound or flipping `connected` under a live one.
472
+ */
473
+ private generation;
474
+ /**
475
+ * How to end a connection attempt that is still awaiting `open`.
476
+ *
477
+ * Retirement by generation makes an attempt's listeners silent, which is not the same as
478
+ * making the attempt finish. One entry per in-flight attempt; `disconnect()` calls them so
479
+ * the attempt settles now instead of at its timeout.
480
+ */
481
+ private readonly pendingAttempts;
482
+ /**
483
+ * Why the socket last closed, as Baileys reported it.
484
+ *
485
+ * Kept because `connect()` returning `false` cannot distinguish a network blip from a
486
+ * session the operator unlinked from their phone — and only one of those is worth retrying.
487
+ * `rules/error-handling.md` § 3: fail clear, and log with enough context to act.
488
+ */
489
+ private lastCloseError?;
183
490
  private inboundHandler?;
184
491
  private statusHandler?;
185
- constructor(opts: WhatsAppCloudBackendOptions);
492
+ /**
493
+ * Serialises outbound sends (ADR D320).
494
+ *
495
+ * Both peer gateways studied do this, and one records that concurrent sends on a single
496
+ * socket can misdeliver to the wrong chat. We have NOT measured that in our own code — we
497
+ * have never run a Baileys socket — so this is precaution rather than a reproduction of our
498
+ * own bug, and saying so is the point. It is kept because the cost is one promise chain and
499
+ * the failure it guards against is a message delivered to the wrong person.
500
+ */
501
+ private sendQueue;
502
+ constructor(opts: WhatsAppBaileysBackendOptions);
503
+ /**
504
+ * Open the socket and wait for it to report `open`.
505
+ *
506
+ * Idempotent, and safe against a concurrent second call: the in-flight promise is shared
507
+ * rather than a second socket being built. WhatsApp's own adapter shipped without that
508
+ * guard once and opened two live sessions.
509
+ */
186
510
  connect(): Promise<boolean>;
511
+ /** Close the socket. Idempotent, and safe when never connected. */
187
512
  disconnect(): Promise<void>;
188
- send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult$1>;
513
+ /**
514
+ * Send one text message.
515
+ *
516
+ * Queued behind any send already in flight (D320), and raced against a timeout whose
517
+ * expiry reports **undetermined** delivery rather than failure (D321). A local timeout says
518
+ * the acknowledgement did not arrive, not that the message did not — so this never
519
+ * retries, because a retry after a slow ack duplicates the message.
520
+ */
521
+ send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult>;
522
+ /** Subscribe to inbound events. EC-H: a second call REPLACES the first. */
189
523
  onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void;
190
- onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void;
191
524
  /**
192
- * Webhook entrypoint. The user calls this from inside their POST /webhook
193
- * route after `verifyWebhookSubscription` on GET.
525
+ * Subscribe to delivery receipts. EC-H: a second call REPLACES the first.
194
526
  *
195
- * @returns `true` if signature valid + dispatched (or empty payload).
196
- * `false` if signature invalid (route should return 401).
527
+ * Declared for the interface; Baileys reports receipts on `messages.update`, which v1 does
528
+ * not consume. Registering a handler is accepted and it is never called — stated here
529
+ * rather than left for a consumer to discover from silence.
197
530
  */
198
- handleWebhookPayload(rawBody: Buffer | string, signatureHeader: string | undefined): Promise<boolean>;
531
+ onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void;
199
532
  }
200
533
 
201
534
  /** Inbound webhook payload — the full envelope Meta POSTs. */
@@ -245,6 +578,93 @@ interface MetaStatusUpdate {
245
578
  readonly timestamp: string;
246
579
  readonly recipient_id: string;
247
580
  }
581
+ /** One component of a template — header, body or button — with its parameters. */
582
+ interface MetaTemplateComponent {
583
+ readonly type: string;
584
+ readonly parameters?: ReadonlyArray<Record<string, unknown>>;
585
+ readonly sub_type?: string;
586
+ readonly index?: string;
587
+ }
588
+
589
+ /**
590
+ * `WhatsAppCloudBackend` — Meta WhatsApp Business Cloud API backend (ADR D304).
591
+ *
592
+ * `connect()` / `disconnect()` are no-ops (HTTP push via webhook is the only
593
+ * inbound channel). Outbound delegates to `WhatsAppCloudClient`. Inbound
594
+ * dispatch is driven by the user calling `handleWebhookPayload(rawBody, sig)`
595
+ * from inside their HTTP route.
596
+ *
597
+ * @public
598
+ */
599
+
600
+ interface WhatsAppCloudBackendOptions {
601
+ readonly accessToken: string;
602
+ readonly phoneNumberId: string;
603
+ readonly appSecret: string;
604
+ readonly apiVersion?: string;
605
+ /** Test seam. */
606
+ readonly fetch?: typeof fetch;
607
+ }
608
+ /**
609
+ * WhatsApp backend over Meta's official Cloud API.
610
+ *
611
+ * The supported path: Meta dials in with webhook deliveries, so inbound needs a publicly reachable
612
+ * HTTPS endpoint registered in the Meta console. Outbound is a plain HTTPS call and works anywhere.
613
+ * Business-initiated messages outside the 24-hour customer service window must use an approved
614
+ * template — a plain text send to a cold contact is rejected by the platform, not by this code.
615
+ */
616
+ declare class WhatsAppCloudBackend implements WhatsAppBackend {
617
+ readonly kind: "cloud";
618
+ private readonly client;
619
+ private readonly appSecret;
620
+ private inboundHandler?;
621
+ private statusHandler?;
622
+ constructor(opts: WhatsAppCloudBackendOptions);
623
+ connect(): Promise<boolean>;
624
+ disconnect(): Promise<void>;
625
+ send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult>;
626
+ /**
627
+ * Send an approved template to `to`.
628
+ *
629
+ * Cloud-only, and deliberately absent from the `WhatsAppBackend` interface: WhatsApp Web has no
630
+ * concept of templates, so putting this on the shared contract would hand the web backend a
631
+ * method it could only throw from. A consumer reaches it by holding the backend directly.
632
+ *
633
+ * This is the only way to message someone outside the 24-hour service window — every
634
+ * notification, and every unattended check that this integration still works. Free-form text to
635
+ * a cold recipient comes back as `session_window_expired`.
636
+ *
637
+ * @param templateName Name of a template already approved on the WhatsApp Business account.
638
+ * @param languageCode Locale of the approved template, e.g. `en_US`, `pt_BR`.
639
+ * @param components Values for the template's variables; omit for a template that takes none.
640
+ */
641
+ sendTemplate(to: string, templateName: string, languageCode: string, components?: ReadonlyArray<MetaTemplateComponent>): Promise<WhatsAppSendResult>;
642
+ onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void;
643
+ onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void;
644
+ /**
645
+ * Webhook entrypoint. The user calls this from inside their POST /webhook
646
+ * route after `verifyWebhookSubscription` on GET.
647
+ *
648
+ * @returns `true` if signature valid + dispatched (or empty payload).
649
+ * `false` if signature invalid (route should return 401).
650
+ */
651
+ handleWebhookPayload(rawBody: Buffer | string, signatureHeader: string | undefined): Promise<boolean>;
652
+ /**
653
+ * Parse a signed webhook body, or report `undefined` when it is not JSON.
654
+ *
655
+ * The method's contract is true/false; the route calling it has no reason to expect a throw.
656
+ */
657
+ private parseBody;
658
+ /**
659
+ * Run one user callback and contain its failure.
660
+ *
661
+ * Meta batches several messages, and their delivery receipts, into a single webhook. Awaiting a
662
+ * handler with nothing around it made one throw skip every remaining message in the payload —
663
+ * and reject `handleWebhookPayload`, so the caller's route answered 500 and Meta redelivered the
664
+ * whole batch, replaying the messages that HAD succeeded (#41).
665
+ */
666
+ private dispatchContained;
667
+ }
248
668
 
249
669
  /**
250
670
  * Webhook helpers for Meta WhatsApp Business Cloud API (ADR D306, D312).
@@ -279,6 +699,12 @@ declare function verifyWebhookSubscription(query: Record<string, string | undefi
279
699
  declare function verifyWebhookSignature(rawBody: Buffer | string, signatureHeader: string | undefined, appSecret: string): boolean;
280
700
  /** Parse the raw JSON payload into a typed envelope. Returns `null` if shape is unrecognized. */
281
701
  declare function parseWebhookPayload(json: unknown): MetaWebhookEnvelope | null;
702
+ /**
703
+ * Extract the inbound messages from one Meta webhook envelope.
704
+ *
705
+ * A single delivery batches entries, changes and messages, and may carry none at all — a
706
+ * status-only delivery is normal. Returns an array, empty when there is nothing to hand on.
707
+ */
282
708
  declare function normalizeInboundMessages(envelope: MetaWebhookEnvelope): WhatsAppInboundEvent[];
283
709
  /** Normalize status updates → `WhatsAppStatusReceipt[]`. */
284
710
  declare function normalizeStatusReceipts(envelope: MetaWebhookEnvelope): WhatsAppStatusReceipt[];
@@ -311,6 +737,14 @@ interface WhatsAppWebBackendOptions {
311
737
  /** Test seam: theokit home for PID locks. */
312
738
  readonly theokitHome?: string;
313
739
  }
740
+ /**
741
+ * WhatsApp backend driving `whatsapp-web.js` in a child process.
742
+ *
743
+ * Unofficial: it automates a WhatsApp Web session, which Meta's terms do not sanction and which can
744
+ * get a number banned. It exists for a personal number that has no Cloud API access. The browser
745
+ * runs out-of-process behind a PID lock so a crashed or orphaned bridge cannot be left holding the
746
+ * session.
747
+ */
314
748
  declare class WhatsAppWebBackend implements WhatsAppBackend {
315
749
  private readonly opts;
316
750
  readonly kind: "web";
@@ -319,6 +753,8 @@ declare class WhatsAppWebBackend implements WhatsAppBackend {
319
753
  private inboundHandler?;
320
754
  private statusHandler?;
321
755
  private readonly pending;
756
+ /** Rejects an in-flight `connect()` when the bridge reports it cannot start. */
757
+ private connectRejectors;
322
758
  private msgIdCounter;
323
759
  private botPhone?;
324
760
  private connected;
@@ -329,15 +765,40 @@ declare class WhatsAppWebBackend implements WhatsAppBackend {
329
765
  private cleanupHandle;
330
766
  connect(): Promise<boolean>;
331
767
  disconnect(): Promise<void>;
332
- send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult$1>;
768
+ send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult>;
333
769
  onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void;
334
770
  onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void;
335
771
  private handleReady;
336
772
  private handleMessage;
773
+ /**
774
+ * A bridge that reported a failure has failed — say so now, not in two minutes.
775
+ *
776
+ * This used to write the message to stderr and return. `connect()` races only the `ready`
777
+ * promise against the timeout, so a bridge that told us exactly what was wrong and exited
778
+ * still cost the caller the full `connectTimeoutMs` and surfaced as a timeout — the one
779
+ * error that carries no information. The diagnosis was printed where nothing could act on
780
+ * it, which is the swallowing `rules/error-handling.md` § 5 names.
781
+ */
782
+ private handleBridgeError;
337
783
  private handleSendAck;
338
784
  private handleStatus;
339
785
  private dispatch;
340
786
  }
787
+ /**
788
+ * Where the bridge script lives, for the layout this module is running from.
789
+ *
790
+ * The single hard-coded `../../bridge/...` this replaced was written against the SOURCE
791
+ * tree — `src/backend/web/` up two is `src/`, which is right. The bundle is one flat file
792
+ * at `dist/index.js`, so the same relative path resolved to `packages/bridge/...`, one
793
+ * directory above the package. Nothing caught it: every test injects `spawnFactory`, so the
794
+ * real spawn had never run, and when it did the child died with `MODULE_NOT_FOUND` and
795
+ * `connect()` reported a 120-second timeout — the one error carrying no information about
796
+ * what actually happened.
797
+ *
798
+ * Both layouts are checked, and neither existing is an error rather than a guess: a path
799
+ * that does not exist can only fail later, further from the cause.
800
+ */
801
+ declare function defaultBridgeScriptPath(): string;
341
802
 
342
803
  /**
343
804
  * IPC protocol between adapter and `whatsapp-web.js` subprocess bridge.
@@ -383,6 +844,12 @@ type IpcEvent = {
383
844
  } | {
384
845
  readonly event: "error";
385
846
  readonly message: string;
847
+ /**
848
+ * Machine-readable cause, when the bridge could name one. Absent on older bridges and
849
+ * on failures it cannot classify, which is why every consumer must tolerate it being
850
+ * undefined rather than switching exhaustively.
851
+ */
852
+ readonly code?: string;
386
853
  };
387
854
  /** Parse one JSON-line. Returns null on malformed. */
388
855
  declare function parseEvent(line: string): IpcEvent | null;
@@ -407,12 +874,69 @@ declare class LineBuffer {
407
874
  *
408
875
  * @internal
409
876
  */
877
+
410
878
  type ErrorPayload = Required<WhatsAppSendResult>["error"];
879
+ /**
880
+ * Public input shape for the {@link ConfigurationError} constructor.
881
+ *
882
+ * Aliased from the core rather than redeclared. The base type exists precisely so every
883
+ * adapter stops writing its own copy of the same three fields, and a redeclaration means a
884
+ * field added to the core silently never reaches this package. Four siblings alias it the
885
+ * same way.
886
+ */
887
+ type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;
888
+ /**
889
+ * A required option is missing or empty.
890
+ *
891
+ * Raised where a consumer hands us configuration — the factories — rather than later, when
892
+ * the value is finally used against the network. A factory that returns an adapter which
893
+ * cannot authenticate has moved the error away from its cause: the stack then names a send,
894
+ * and the mistake was in construction.
895
+ *
896
+ * Matches the shape every sibling adapter uses (`gateway-line`, `gateway-email`, …), which
897
+ * is what makes one `catch (e) { if (e instanceof GatewayConfigurationError) }` work across
898
+ * all of them.
899
+ *
900
+ * @public
901
+ */
902
+ declare class ConfigurationError extends GatewayConfigurationError {
903
+ readonly name = "ConfigurationError";
904
+ constructor(opts: ConfigurationErrorOptions);
905
+ }
906
+ /**
907
+ * The bridge reported, on its own protocol, that it cannot start.
908
+ *
909
+ * Distinct from {@link WhatsAppConnectTimeoutError}, which says only that nothing arrived in
910
+ * time. This one carries what the bridge said — and, when it could classify itself, a
911
+ * machine-readable `code` such as `peer_missing`, `peer_incompatible` or `peer_load_failed`.
912
+ * The difference matters to a caller: a timeout may be worth retrying, and a peer dependency
913
+ * that does not export what we need never will be.
914
+ *
915
+ * @public
916
+ */
917
+ declare class WhatsAppBridgeError extends Error {
918
+ readonly name = "WhatsAppBridgeError";
919
+ /** Cause as named by the bridge, when it could name one. */
920
+ readonly code: string | undefined;
921
+ constructor(message: string, code?: string);
922
+ }
411
923
  /** Custom error: `connect()` timed out waiting for "ready" (EC-6). */
412
924
  declare class WhatsAppConnectTimeoutError extends Error {
413
925
  constructor(timeoutMs: number);
414
926
  }
927
+ /**
928
+ * Map a Cloud API HTTP failure into the canonical `{ code, message }` payload.
929
+ *
930
+ * Takes the status alongside the body because Meta returns the same envelope shape for very
931
+ * different faults, and the status is what separates a rejected payload from an expired token.
932
+ */
415
933
  declare function mapWhatsAppCloudError(status: number, body: unknown): ErrorPayload;
934
+ /**
935
+ * Map an error string from the `whatsapp-web.js` bridge into the canonical payload.
936
+ *
937
+ * The bridge speaks over IPC and can only send text, so this is the boundary where a line of stderr
938
+ * becomes a structured error. `undefined` maps to an `unknown` code rather than throwing.
939
+ */
416
940
  declare function mapWhatsAppWebError(ipcError: string | undefined): ErrorPayload;
417
941
 
418
942
  /**
@@ -429,4 +953,4 @@ declare function mapWhatsAppWebError(ipcError: string | undefined): ErrorPayload
429
953
  */
430
954
  declare function splitForWhatsApp(text: string): string[];
431
955
 
432
- 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 };
956
+ export { type BaileysSocketFactory, type BaileysSocketLike, type BaileysSocketOptions, ConfigurationError, type ConfigurationErrorOptions, type IpcCommand, type IpcEvent, LineBuffer, type MetaTemplateComponent, WhatsAppAdapter, type WhatsAppAdapterCommonOptions, type WhatsAppAdapterOptions, type WhatsAppBackend, WhatsAppBaileysBackend, type WhatsAppBaileysBackendOptions, type WhatsAppBaileysConfig, WhatsAppBridgeError, WhatsAppCloudBackend, type WhatsAppCloudBackendOptions, type WhatsAppCloudConfig, WhatsAppConnectTimeoutError, type WhatsAppInboundEvent, type WhatsAppOutboundMessage, type WhatsAppSendResult, type WhatsAppStatusReceipt, WhatsAppWebBackend, type WhatsAppWebBackendOptions, type WhatsAppWebConfig, createBaileysSocket, defaultBridgeScriptPath, digitsOnly, formatCommand, mapWhatsAppCloudError, mapWhatsAppWebError, normalizeInboundMessages, normalizeStatusReceipts, parseEvent, parseWebhookPayload, splitForWhatsApp, verifyWebhookSignature, verifyWebhookSubscription };