@theokit/gateway-whatsapp 0.3.2 → 0.4.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 CHANGED
@@ -1,5 +1,99 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - b38172b: **The peer floor on `@theokit/gateway` rises with this release.** Every adapter now implements
8
+ `deliver` over `runHandler`, and neither exists in an older core — an adapter installed against one
9
+ does not build. `dep-check` caught that by building the whole workspace against the floor each
10
+ package claimed, which is the one thing a version range cannot tell you by reading it.
11
+
12
+ The floor is set in the version commit rather than here, because a range cannot name a version that
13
+ does not exist yet: raised in the workspace, the same gate then fails the other way round — every
14
+ adapter declaring a floor above the core installed beside it. That is the shape `fa70153` used when
15
+ these ranges were first written.
16
+
17
+ `deliver(event)` — every adapter can now be handed an event that arrived out of band (#83).
18
+
19
+ `onInbound` was the seam every adapter implemented and it had no public counterpart. Six platforms
20
+ self-deliver once connected — long polling, a gateway socket, Socket Mode, a sync loop, IMAP — so
21
+ the asymmetry stayed invisible: `GatewayRunner` worked for eight platforms and silently did nothing
22
+ for LINE and WhatsApp Cloud, whose payloads arrive on an HTTP route the application owns. Every app
23
+ wired those two by hand, beside the runner rather than through it.
24
+
25
+ ```ts
26
+ const outcome = await adapter.deliver(event); // "ok" | "no_handler" | "handler_threw"
27
+ ```
28
+
29
+ The three outcomes are distinguished because a caller acts on them differently: answering a webhook
30
+ 200 when nobody was subscribed tells the provider to stop retrying a message nothing received.
31
+
32
+ `BasePlatformAdapter.runHandler` holds the containment once, where ten copies of it used to live —
33
+ a handler is user code, its throw is named as the handler's failure rather than the platform's, and
34
+ delivery continues. Each adapter's `deliver` is one line over it.
35
+
36
+ Also: `gateway-sms`'s `createWebhookServer` now signs against the configured `publicUrl` (#90).
37
+ Twilio verifies against the URL it POSTed to, and behind a proxy that rewrites `host` — a tunnel, an
38
+ ingress, a load balancer terminating TLS — the reconstruction from headers yields the internal
39
+ address, so a correct signature fails on every delivery. `publicUrl` is required by all three
40
+ backend option shapes and documented as "used by signature verifier"; until now no source file read
41
+ it. The header reconstruction stays as the fallback for an app served directly.
42
+
43
+ - 348bc02: WhatsApp: send to the address that routes, and answer where the message came from (#82, #84).
44
+
45
+ **A send that WhatsApp discards no longer reports success.** Baileys hands back a
46
+ locally-generated `wamid` whether or not the JID routes anywhere, and the backend treated that id
47
+ as proof of delivery — so a message nobody received was recorded as a success by the caller's log,
48
+ its metrics and its retry logic. Measured on a real account: `5535998838687` and `553598838687` are
49
+ the same Brazilian line, both answered `ok: true`, and only the second arrived.
50
+
51
+ `send` now asks WhatsApp which form it routes to before sending, and refuses a number the server
52
+ does not know with `undeliverable` naming the number. That fixes the Brazilian ninth digit without a
53
+ Brazil-specific rule anywhere in this package — the answer is whatever the server says, for any
54
+ country. The lookup is cached for the life of the session, so it costs one round-trip per recipient.
55
+
56
+ **An inbound event now carries the address it arrived on**, as `whatsapp.channelJid`. `channel.id`
57
+ is normalised to digits — which is what an allowlist compares — and that normalisation strips the
58
+ domain, the part that says whether an address is a phone, a group, or an account's linked identity.
59
+ A note-to-self arrives addressed by LID, so replying to `channel.id` rebuilt `…@s.whatsapp.net`, an
60
+ address that does not exist.
61
+
62
+ **`send` accepts a qualified JID verbatim.** A `to` containing `@` is already an address and is
63
+ passed through untouched, where it used to become `231116569108705@lid@s.whatsapp.net`. So
64
+ answering an inbound event is now:
65
+
66
+ ```ts
67
+ await adapter.sendMessage({
68
+ channel: { id: event.whatsapp.channelJid ?? event.channel.id, type: "dm" },
69
+ text,
70
+ });
71
+ ```
72
+
73
+ Not affected: the Cloud backend. Meta rejects an unroutable recipient with an error code, so the
74
+ same mistake surfaces there instead of vanishing.
75
+
76
+ ## 0.3.3
77
+
78
+ ### Patch Changes
79
+
80
+ - 467af35: The unofficial (Web) bridge now exits on SIGTERM instead of hanging with Chromium still running.
81
+
82
+ Measured 2026-08-30: sending SIGTERM to the bridge did not stop it at all — the `exit` event never
83
+ fired and ten Chromium processes stayed up. puppeteer registers its own SIGTERM/SIGINT/SIGHUP
84
+ handlers by default, and registering any handler replaces Node's terminate-on-signal default; the
85
+ bridge installed none of its own, so it inherited a shutdown that waits on a browser close which
86
+ never arrives while WhatsApp Web is still loading.
87
+
88
+ Anything that supervises a process stops it with SIGTERM — systemd, Docker, pm2, a parent Node
89
+ process. Every such stop left a bridge that would not die and a leaked browser tree, recoverable
90
+ only with SIGKILL, which cannot close anything cleanly. Restarting therefore accumulated Chromium
91
+ processes and session directories.
92
+
93
+ The bridge now owns its termination signals and closes the browser under a five-second deadline,
94
+ then exits regardless. Re-measured on the same probe: the process exits in ~6s with code 0 and zero
95
+ Chromium processes survive.
96
+
3
97
  ## 0.3.2
4
98
 
5
99
  ### Patch Changes
package/README.md CHANGED
@@ -1,6 +1,95 @@
1
1
  # `@theokit/gateway-whatsapp`
2
2
 
3
- WhatsApp platform adapter for `@theokit/gateway`. Multi-backend (Meta WhatsApp Business Cloud API + `whatsapp-web.js` subprocess bridge).
3
+ WhatsApp platform adapter for `@theokit/gateway`. Three backends behind one
4
+ `WhatsAppBackend` interface: the Meta WhatsApp Business Cloud API, a `whatsapp-web.js`
5
+ subprocess bridge, and a `baileys` socket.
4
6
 
5
- Status: **v0.1.0 pre-release**. Pre-1.0 contract per ADR D314 — breaking changes allowed within 0.x.
7
+ Pre-1.0 contract per ADR D314 — breaking changes allowed within 0.x. (This line used to
8
+ pin a version number, and named 0.1.0 while the package shipped 0.3.2.)
6
9
 
10
+
11
+ ## How inbound arrives
12
+
13
+ **It depends on the backend**, and the two are not alike.
14
+
15
+ `cloud` is an **HTTP webhook** the application must authenticate: Meta signs with
16
+ `X-Hub-Signature-256` over the raw body, and `theokit/server/webhook` exports `whatsapp()` and
17
+ `whatsappSubscribe()` for the signature and the GET handshake. Parsed events go to
18
+ `adapter.deliver(event)`.
19
+
20
+ `baileys` and `web` hold **their own socket** — there is no webhook to host, and messages reach
21
+ `onInbound` once `connect()` resolves.
22
+ ## Choosing a backend
23
+
24
+ | Backend | Needs | Exercised against real WhatsApp |
25
+ | --- | --- | --- |
26
+ | `WhatsAppCloudBackend` | a Meta Business account, an access token, a phone number id | **yes** — send accepted by Meta, `wamid` returned. Delivery status arrives by webhook and is not asserted here |
27
+ | `WhatsAppBaileysBackend` | a phone to scan a QR once, then a `sessionDir` | **yes** — paired against a real account 2026-08-30 and sent through it |
28
+ | `WhatsAppWebBackend` | a phone to scan a QR **and a Chrome/Chromium binary** | reaches WhatsApp and issues a QR, given a browser (see below) |
29
+
30
+ The Cloud API is the supported path — it is the one Meta documents, the one with no
31
+ phone tethered to a session, and the only one whose send this repository asserts in a
32
+ test. The other two speak WhatsApp's client protocol, which its terms do not sanction;
33
+ choosing one is a decision about your account, not about this package.
34
+
35
+ Measured 2026-08-29: Baileys produced a pairing QR **1441 ms** after `connect()`, then
36
+ returned `false` — not a throw, and with the reason stated — when the 45 s window closed
37
+ unscanned. The web bridge reached the same point with `PUPPETEER_EXECUTABLE_PATH` set.
38
+
39
+ Measured 2026-08-30: the Baileys backend was **paired against a real WhatsApp account** and sent
40
+ through it, returning a `wamid`. Two things that cost a session each are worth carrying:
41
+
42
+ - **Pairing is QR-only.** `requestPairingCode` exists in Baileys and WhatsApp refuses the codes
43
+ this backend asks for — three attempts, on both the 12- and 13-digit forms of a Brazilian
44
+ number. `WhatsAppBaileysBackend`'s docblock records what is and is not established about why.
45
+ - **A `wamid` is not delivery, and this one loses messages silently.** Two sends to the same
46
+ Brazilian line, one with the ninth digit and one without: both returned `ok: true` with a
47
+ `wamid`, and only `553598838687` — the form without it — arrived. `5535998838687` was accepted
48
+ and vanished. This backend does NOT normalise the Brazilian ninth digit; pass the JID form
49
+ WhatsApp knows, which the account itself reports (WhatsApp Web stores it under `last-wid-md`).
50
+ Tracked as a defect rather than a footnote: a send that reports success for a message nobody
51
+ receives is the swallowed failure `rules/error-handling.md` § 5 names first.
52
+
53
+ The web bridge has still never been paired, so it has no send anyone here can prove.
54
+
55
+ ### Showing the QR: `backend.pairing`
56
+
57
+ `onQr` is push — it fires when WhatsApp issues a code, at a moment the caller does not choose. A
58
+ screen is pull: it loads when someone opens it and has to ask what is true right now. So the
59
+ backend also answers:
60
+
61
+ ```ts
62
+ backend.pairing
63
+ // { status: "idle" | "awaiting_scan" | "connected" | "closed", qr?: string, qrAt?: number }
64
+ ```
65
+
66
+ `qr` is present only while `awaiting_scan`, and is dropped on `connected` and on `closed` —
67
+ WhatsApp reissues roughly every 20 seconds and a screen holding the previous square offers
68
+ something that cannot be scanned. `qrAt` lets a UI show the code's age rather than a stale image.
69
+
70
+ Rendering is the app's job. This package does not encode the image and will not: `qrcode` pulls a
71
+ CLI argument parser, and a consumer using only the Cloud API backend would carry it to pair
72
+ nothing. Two lines where the screen is:
73
+
74
+ ```ts
75
+ import { toDataURL } from "qrcode";
76
+ const src = await toDataURL(backend.pairing.qr);
77
+ ```
78
+
79
+ ### The web backend needs a browser you provide
80
+
81
+ `whatsapp-web.js` drives a real Chrome through Puppeteer, and **this package does not ship
82
+ one**: the repository leaves `puppeteer` out of `pnpm.onlyBuiltDependencies`, so its
83
+ postinstall never downloads a browser. Without one the bridge starts, fails to find Chrome,
84
+ and reports that failure in its own protocol — it does not crash, which is the fix from
85
+ B-002, but it does not connect either.
86
+
87
+ Point it at a browser you already have:
88
+
89
+ ```bash
90
+ PUPPETEER_EXECUTABLE_PATH=/usr/bin/google-chrome node your-app.js
91
+ ```
92
+
93
+ The bridge spawns without an explicit `env`, so it inherits yours and the variable
94
+ reaches Puppeteer. `WhatsAppBaileysBackend` needs no browser at all, which is the reason
95
+ it exists (B-001).
@@ -164,6 +164,42 @@ client.on("disconnected", (reason) => {
164
164
  emitError(`DISCONNECTED: ${reason}`);
165
165
  });
166
166
 
167
+ /**
168
+ * Close the browser and leave, under a deadline.
169
+ *
170
+ * The deadline is the point. `client.destroy()` closes Chromium, and while WhatsApp Web is still
171
+ * loading it can wait forever — so an unbounded shutdown is a process that never exits. Racing it
172
+ * against a timer means the browser is closed properly when that is possible and the bridge leaves
173
+ * regardless, which is what a supervisor waiting on the exit is owed.
174
+ */
175
+ let shuttingDown = false;
176
+ async function shutdown(code) {
177
+ if (shuttingDown) return;
178
+ shuttingDown = true;
179
+ await Promise.race([
180
+ client.destroy().catch(() => undefined),
181
+ new Promise((resolve) => setTimeout(resolve, 5_000)),
182
+ ]);
183
+ process.exit(code);
184
+ }
185
+
186
+ /**
187
+ * Own the termination signals.
188
+ *
189
+ * Measured 2026-08-30: without these, SIGTERM did not stop the bridge at all — the process stayed
190
+ * up and eleven Chromium processes with it. puppeteer registers its own SIGTERM/SIGINT/SIGHUP
191
+ * handlers by default, and registering ANY handler removes Node's terminate-on-signal default; the
192
+ * bridge then inherited a shutdown that could hang and had no deadline of its own.
193
+ *
194
+ * Registering last wins for the exit: puppeteer's handler still runs and closes what it can, and
195
+ * this one guarantees the process actually leaves.
196
+ */
197
+ for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) {
198
+ process.on(signal, () => {
199
+ void shutdown(0);
200
+ });
201
+ }
202
+
167
203
  const rl = createInterface({ input: process.stdin });
168
204
  rl.on("line", async (line) => {
169
205
  let cmd;
@@ -173,12 +209,7 @@ rl.on("line", async (line) => {
173
209
  return;
174
210
  }
175
211
  if (cmd?.cmd === "shutdown") {
176
- try {
177
- await client.destroy();
178
- } catch {
179
- /* ignore */
180
- }
181
- process.exit(0);
212
+ await shutdown(0);
182
213
  }
183
214
  if (cmd?.cmd === "send") {
184
215
  const msgId = cmd.msgId;
package/dist/index.cjs CHANGED
@@ -101,20 +101,31 @@ function resolveParties(key, remoteJid) {
101
101
  const fromPhone = normalizeWhatsAppId(senderJid);
102
102
  const channelId = normalizeWhatsAppId(remoteJid);
103
103
  if (fromPhone.length === 0 || channelId.length === 0) return void 0;
104
- return { fromPhone, channelId, isGroup };
104
+ return { fromPhone, channelId, channelJid: remoteJid, isGroup };
105
105
  }
106
- function isDispatchable(key, remoteJid) {
107
- if (key.fromMe === true) return false;
108
- return remoteJid !== STATUS_BROADCAST_JID;
106
+ function isDispatchable(key, remoteJid, wamid, ctx) {
107
+ if (remoteJid === STATUS_BROADCAST_JID) return "no";
108
+ if (key.fromMe !== true) return "yes";
109
+ const selfJids = ctx?.selfJids;
110
+ if (selfJids === void 0 || selfJids.size === 0) return "no";
111
+ if (!selfJids.has(normalizeWhatsAppId(remoteJid))) return "no";
112
+ return ctx?.sentWamids?.has(wamid) === true ? "no" : "yes-from-self";
109
113
  }
110
- function normalizeBaileysMessage(raw) {
111
- const envelope = asObject(raw);
114
+ function addressingOf(envelope) {
112
115
  const key = envelope === void 0 ? void 0 : asObject(envelope.key);
113
116
  if (key === void 0) return void 0;
114
117
  const remoteJid = asText(key.remoteJid);
115
118
  const wamid = asText(key.id);
116
119
  if (remoteJid === void 0 || wamid === void 0) return void 0;
117
- if (!isDispatchable(key, remoteJid)) return void 0;
120
+ return { key, remoteJid, wamid };
121
+ }
122
+ function normalizeBaileysMessage(raw, ctx) {
123
+ const envelope = asObject(raw);
124
+ const addressed = addressingOf(envelope);
125
+ if (addressed === void 0) return void 0;
126
+ const { key, remoteJid, wamid } = addressed;
127
+ const verdict = isDispatchable(key, remoteJid, wamid, ctx);
128
+ if (verdict === "no") return void 0;
118
129
  const text = extractText(envelope?.message);
119
130
  if (text === void 0) return void 0;
120
131
  const parties = resolveParties(key, remoteJid);
@@ -127,10 +138,12 @@ function normalizeBaileysMessage(raw) {
127
138
  fromPhone: parties.fromPhone,
128
139
  conversationType: parties.isGroup ? "group" : "dm",
129
140
  channelId: parties.channelId,
141
+ channelJid: parties.channelJid,
130
142
  text,
131
143
  receivedAt: seconds * 1e3,
132
144
  backend: "baileys",
133
145
  raw,
146
+ ...verdict === "yes-from-self" ? { fromSelf: true } : {},
134
147
  ...contactName !== void 0 ? { contactName } : {}
135
148
  };
136
149
  }
@@ -300,6 +313,8 @@ function endQuietly(socket) {
300
313
  }
301
314
  var DEFAULT_CONNECT_TIMEOUT_MS = 6e4;
302
315
  var DEFAULT_SEND_TIMEOUT_MS = 3e4;
316
+ var UNROUTABLE = "__unroutable__";
317
+ var SENT_WAMID_WINDOW = 256;
303
318
  var WhatsAppBaileysBackend = class {
304
319
  constructor(opts) {
305
320
  this.opts = opts;
@@ -334,6 +349,54 @@ var WhatsAppBaileysBackend = class {
334
349
  * `rules/error-handling.md` § 3: fail clear, and log with enough context to act.
335
350
  */
336
351
  lastCloseError;
352
+ /** The pairing, as a caller may ask for it. Never handed out mutable. */
353
+ pairingState = { status: "idle" };
354
+ /**
355
+ * The JIDs that ARE this account, normalised. Empty until a socket reports who it logged in as.
356
+ *
357
+ * Empty means "not learned yet", and `isDispatchable` reads that as refusing everything this
358
+ * account sent — the same behaviour as before self-chat support existed. A backend that
359
+ * guessed here would answer in a stranger's conversation.
360
+ */
361
+ selfJids = /* @__PURE__ */ new Set();
362
+ /**
363
+ * Ids this backend sent, most recent last. This is what stops the agent answering itself.
364
+ *
365
+ * Bounded because it is a loop guard, not a log: an unbounded set on a long-lived socket is a
366
+ * leak, and nothing needs to recognise an echo from an hour ago — WhatsApp delivers our own
367
+ * message back within seconds or not at all.
368
+ */
369
+ sentWamids = /* @__PURE__ */ new Set();
370
+ /** Record one id we sent, evicting the oldest once the window is full. @internal */
371
+ rememberSent(wamid) {
372
+ this.sentWamids.add(wamid);
373
+ while (this.sentWamids.size > SENT_WAMID_WINDOW) {
374
+ const oldest = this.sentWamids.values().next();
375
+ if (oldest.done === true) break;
376
+ this.sentWamids.delete(oldest.value);
377
+ }
378
+ }
379
+ /**
380
+ * Learn which JIDs are this account, from the socket that just logged in.
381
+ *
382
+ * Both forms are recorded: the phone JID and the LID. The self-chat is addressed by LID —
383
+ * measured on a real account, where a note-to-self arrived on `231116569108705@lid` while the
384
+ * account's phone JID was `553598838687` — so recording only one leaves the self-chat
385
+ * unrecognised and the feature silently off.
386
+ *
387
+ * @internal
388
+ */
389
+ learnSelfJids(socket) {
390
+ const user = socket.user;
391
+ const ids = [user?.id, user?.lid].filter((id) => typeof id === "string" && id.length > 0).map((id) => normalizeWhatsAppId(id)).filter((id) => id.length > 0);
392
+ this.selfJids = new Set(ids);
393
+ if (process.env.THEOKIT_WHATSAPP_TRACE === "1") {
394
+ process.stderr.write(
395
+ `[whatsapp-baileys][trace] selfJids learned: ${ids.length === 0 ? "(none)" : ids.join(", ")}
396
+ `
397
+ );
398
+ }
399
+ }
337
400
  inboundHandler;
338
401
  statusHandler;
339
402
  /**
@@ -346,6 +409,14 @@ var WhatsAppBaileysBackend = class {
346
409
  * the failure it guards against is a message delivered to the wrong person.
347
410
  */
348
411
  sendQueue = Promise.resolve();
412
+ /**
413
+ * What WhatsApp answered about each recipient, for the life of the session.
414
+ *
415
+ * Holds the routable JID, or {@link UNROUTABLE} for a number the server does not know. Both are
416
+ * worth remembering: a second send to a number that does not exist should refuse as fast as the
417
+ * first, without another round-trip.
418
+ */
419
+ jidCache = /* @__PURE__ */ new Map();
349
420
  /**
350
421
  * Open the socket and wait for it to report `open`.
351
422
  *
@@ -390,20 +461,68 @@ var WhatsAppBaileysBackend = class {
390
461
  }
391
462
  if (this.socket !== void 0 && this.socket !== socket) endQuietly(this.socket);
392
463
  this.socket = socket;
464
+ this.learnSelfJids(socket);
393
465
  this.connected = true;
394
466
  return true;
395
467
  }
468
+ /**
469
+ * What the pairing is doing right now.
470
+ *
471
+ * Read it as often as a screen needs; it is a snapshot, not a subscription.
472
+ */
473
+ get pairing() {
474
+ return this.pairingState;
475
+ }
396
476
  /** Build a socket through the injected factory, or the real one. @internal */
397
477
  async buildSocket() {
398
478
  const factory = this.opts.socketFactory ?? createBaileysSocket;
399
479
  return factory({
400
480
  sessionDir: this.opts.sessionDir,
401
- ...this.opts.onQr !== void 0 ? { onQr: this.opts.onQr } : {}
481
+ // ALWAYS supplied, even when the caller wants none: a backend that only forwards cannot
482
+ // answer `pairing`, and the caller's own handler still runs, so wiring one costs nothing.
483
+ onQr: (qr) => {
484
+ this.pairingState = { status: "awaiting_scan", qr, qrAt: Date.now() };
485
+ this.opts.onQr?.(qr);
486
+ }
487
+ });
488
+ }
489
+ /**
490
+ * Trace one inbound batch BEFORE any filter, when `THEOKIT_WHATSAPP_TRACE=1`.
491
+ *
492
+ * Two independent filters can discard an envelope — the batch `type` here and `fromMe` inside
493
+ * `normalizeBaileysMessage` — and from outside, both look identical: nothing happens. Telling
494
+ * them apart by reading the code is guessing; this is how you find out which one fired.
495
+ *
496
+ * Deliberately content-free. A Baileys session pairs a REAL account carrying real
497
+ * conversations, so the trace records shape (type, direction, group, has-text) and the last
498
+ * four digits of the jid, never the message and never a full contact number.
499
+ *
500
+ * @internal
501
+ */
502
+ traceBatch(payload) {
503
+ if (process.env.THEOKIT_WHATSAPP_TRACE !== "1") return;
504
+ const messages = payload.messages ?? [];
505
+ const rows = messages.map((raw) => {
506
+ const key = raw?.key ?? {};
507
+ const jid = typeof key.remoteJid === "string" ? key.remoteJid : "";
508
+ const message = raw?.message;
509
+ return [
510
+ `fromMe=${String(key.fromMe === true)}`,
511
+ `jid=\u2026${jid.replace(/\D/g, "").slice(-4)}`,
512
+ `group=${String(jid.endsWith("@g.us"))}`,
513
+ `hasMessage=${String(message !== null && message !== void 0)}`
514
+ ].join(" ");
402
515
  });
516
+ process.stderr.write(
517
+ `[whatsapp-baileys][trace] upsert type=${payload.type ?? "(none)"} n=${messages.length}` + (rows.length === 0 ? "\n" : `
518
+ ${rows.join("\n ")}
519
+ `)
520
+ );
403
521
  }
404
522
  /** Route this socket's inbound batches into the handler, while it is still current. @internal */
405
523
  subscribeInbound(socket, isCurrent) {
406
524
  socket.ev.on("messages.upsert", (payload) => {
525
+ this.traceBatch(payload);
407
526
  if (payload.type !== void 0 && payload.type !== "notify") return;
408
527
  if (!isCurrent()) return;
409
528
  for (const raw of payload.messages ?? []) this.dispatchInbound(raw);
@@ -430,12 +549,14 @@ var WhatsAppBaileysBackend = class {
430
549
  socket.ev.on("connection.update", (update) => {
431
550
  if (!isCurrent()) return;
432
551
  if (update.connection === "open") {
552
+ this.pairingState = { status: "connected" };
433
553
  settle(true);
434
554
  return;
435
555
  }
436
556
  if (update.connection !== "close") return;
437
557
  this.lastCloseError = update.lastDisconnect?.error;
438
558
  this.connected = false;
559
+ this.pairingState = { status: "closed" };
439
560
  if (this.socket === socket) this.socket = void 0;
440
561
  endQuietly(socket);
441
562
  settle(false);
@@ -544,10 +665,20 @@ var WhatsAppBaileysBackend = class {
544
665
  inFlight: Promise.resolve()
545
666
  };
546
667
  }
547
- const jid = `${message.to}@${message.isGroup ? "g.us" : "s.whatsapp.net"}`;
548
668
  const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;
549
- const inFlight = socket.sendMessage(jid, { text: message.text });
550
- const result = this.raceSend(inFlight, timeoutMs).then((outcome) => {
669
+ const send = this.resolveJid(socket, message).then(
670
+ async (jid) => jid === void 0 ? UNROUTABLE : await socket.sendMessage(jid, { text: message.text })
671
+ );
672
+ const result = this.raceSend(send, timeoutMs).then((outcome) => {
673
+ if (outcome === UNROUTABLE) {
674
+ return {
675
+ ok: false,
676
+ error: {
677
+ code: "undeliverable",
678
+ message: `WhatsApp does not route to "${message.to}" \u2014 the number is not registered, or not in the form this account can reach. Nothing was sent.`
679
+ }
680
+ };
681
+ }
551
682
  if (outcome === "timeout") {
552
683
  return {
553
684
  ok: false,
@@ -558,6 +689,7 @@ var WhatsAppBaileysBackend = class {
558
689
  };
559
690
  }
560
691
  const wamid = outcome?.key?.id;
692
+ if (wamid !== void 0) this.rememberSent(wamid);
561
693
  return wamid !== void 0 ? { ok: true, wamid } : { ok: true };
562
694
  }).catch((err) => ({
563
695
  ok: false,
@@ -566,7 +698,41 @@ var WhatsAppBaileysBackend = class {
566
698
  message: err instanceof Error ? err.message : String(err)
567
699
  }
568
700
  }));
569
- return { result, inFlight };
701
+ return { result, inFlight: send };
702
+ }
703
+ /**
704
+ * The JID WhatsApp routes this message to, or `undefined` when it routes to nobody.
705
+ *
706
+ * A group id is not a phone number and `onWhatsApp` answers about numbers, so groups pass
707
+ * straight through — asking would refuse every group message.
708
+ *
709
+ * The answer is cached for the life of the session. It is a fact about a number's registration,
710
+ * which does not change while a socket lives, and paying a round-trip per message would make
711
+ * every send slower for something already known.
712
+ *
713
+ * A socket without `onWhatsApp` — an older Baileys, or a fake predating this — sends to the
714
+ * number as given, which is the behaviour from before #82. Refusing on a missing capability
715
+ * would turn an upgrade problem into an outage.
716
+ */
717
+ async resolveJid(socket, message) {
718
+ if (message.to.includes("@")) return message.to;
719
+ if (message.isGroup) return `${message.to}@g.us`;
720
+ if (socket.onWhatsApp === void 0) return `${message.to}@s.whatsapp.net`;
721
+ const cached = this.jidCache.get(message.to);
722
+ if (cached !== void 0) return cached === UNROUTABLE ? void 0 : cached;
723
+ let answer;
724
+ try {
725
+ answer = await socket.onWhatsApp(message.to);
726
+ } catch {
727
+ return `${message.to}@s.whatsapp.net`;
728
+ }
729
+ const entry = answer?.[0];
730
+ if (entry?.exists !== true || entry.jid === void 0 || entry.jid === "") {
731
+ this.jidCache.set(message.to, UNROUTABLE);
732
+ return void 0;
733
+ }
734
+ this.jidCache.set(message.to, entry.jid);
735
+ return entry.jid;
570
736
  }
571
737
  /** Subscribe to inbound events. EC-H: a second call REPLACES the first. */
572
738
  onInbound(handler) {
@@ -601,7 +767,10 @@ var WhatsAppBaileysBackend = class {
601
767
  dispatchInbound(raw) {
602
768
  const handler = this.inboundHandler;
603
769
  if (handler === void 0) return;
604
- const event = normalizeBaileysMessage(raw);
770
+ const event = normalizeBaileysMessage(raw, {
771
+ selfJids: this.selfJids,
772
+ sentWamids: this.sentWamids
773
+ });
605
774
  if (event === void 0) return;
606
775
  void handler(event).catch((err) => {
607
776
  const message = err instanceof Error ? err.message : String(err);
@@ -1491,6 +1660,30 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter
1491
1660
  connected = false;
1492
1661
  handler;
1493
1662
  statusHandler;
1663
+ /** Whether the "this platform carries no format flag" warning has already been emitted. */
1664
+ warnedAboutFormat = false;
1665
+ /**
1666
+ * Say, once, that a declared `format` has nowhere to go on this platform.
1667
+ *
1668
+ * WhatsApp's emphasis is INLINE — `*bold*`, `_italic_` — carried in the message text itself,
1669
+ * with no field on the request to set and no escape sequence to suppress it. So a caller
1670
+ * declaring `markdown` has already put the syntax in the text, and one declaring `html` is
1671
+ * asking for something the platform does not have.
1672
+ *
1673
+ * Reading the field is what turns a silent discard into a stated one — the swallowed-error
1674
+ * shape `rules/error-handling.md` refuses.
1675
+ *
1676
+ * @internal
1677
+ */
1678
+ warnFormatUnsupported(format) {
1679
+ if (format === void 0 || format === "plain") return;
1680
+ if (this.warnedAboutFormat) return;
1681
+ this.warnedAboutFormat = true;
1682
+ process.stderr.write(
1683
+ `[whatsapp] format="${format}" was declared, and WhatsApp cannot carry it as a flag \u2014 its emphasis is inline in the text. Sending as-is; this is logged once.
1684
+ `
1685
+ );
1686
+ }
1494
1687
  // EC-H: track unsubscribe handles so onInbound REPLACES instead of stacks.
1495
1688
  inboundUnsubscribe;
1496
1689
  statusUnsubscribe;
@@ -1634,6 +1827,7 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter
1634
1827
  if (out.text.length === 0) {
1635
1828
  return { ok: false, error: { code: "empty_text", message: "Empty text rejected." } };
1636
1829
  }
1830
+ this.warnFormatUnsupported(out.format);
1637
1831
  const parts = splitForWhatsApp(out.text);
1638
1832
  if (parts.length === 0) {
1639
1833
  return {
@@ -1665,6 +1859,7 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter
1665
1859
  * first thing a mistyped allowlist causes is an operator wondering why the bot went mute.
1666
1860
  */
1667
1861
  isRefusedBySenderAllowlist(inbound) {
1862
+ if (inbound.fromSelf === true) return false;
1668
1863
  if (this.allowedSenders === void 0) return false;
1669
1864
  if (isSenderAllowed(inbound.fromPhone, this.allowedSenders)) return false;
1670
1865
  process.stderr.write(
@@ -1696,6 +1891,7 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter
1696
1891
  wamid: inbound.wamid,
1697
1892
  phoneNumberId: inbound.phoneNumberId,
1698
1893
  contactName: inbound.contactName,
1894
+ channelJid: inbound.channelJid,
1699
1895
  backend: inbound.backend,
1700
1896
  raw: inbound.raw
1701
1897
  }
@@ -1735,6 +1931,15 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter
1735
1931
  }
1736
1932
  };
1737
1933
  }
1934
+ /**
1935
+ * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
1936
+ *
1937
+ * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
1938
+ * named as the handler's failure rather than the platform's, and delivery continues.
1939
+ */
1940
+ async deliver(event) {
1941
+ return this.runHandler(this.handler, event);
1942
+ }
1738
1943
  };
1739
1944
 
1740
1945
  exports.ConfigurationError = ConfigurationError;