@theokit/gateway-whatsapp 0.1.0 → 0.1.2
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 +34 -0
- package/LICENSE +201 -0
- package/README.md +0 -1
- package/dist/index.cjs +20 -29
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -5
- package/dist/index.d.ts +9 -5
- package/dist/index.js +21 -30
- package/dist/index.js.map +1 -1
- package/package.json +14 -13
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,39 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- b8ef098: **Every package now ships the licence it declares.** All twelve manifests in this repository declare `Apache-2.0`, and the repository had no `LICENSE` file at all — not at the root, and not in any package directory except `gateway-email`. So each published tarball asserted a licence while carrying none of its terms, and §4(a) of that licence requires a copy to travel with the distribution. Worse than a missing file: with no licence text anywhere, everything outside the manifests fell back to default copyright, which grants a recipient nothing.
|
|
8
|
+
|
|
9
|
+
The text is now at the repository root and inside every publishable package, byte-identical to the canonical Apache License 2.0 with the appendix filled in (`Copyright 2026 usetheo.dev`). The one pre-existing copy, in `gateway-email`, was replaced along with the rest: it carried the same truncated paragraph 4(d) found across the ecosystem, dropping "reasonable and customary use" from the NOTICE clause — a modified body under an unmodified SPDX identifier.
|
|
10
|
+
|
|
11
|
+
**The repository moved to the official `usetheokit` organization.** Existing clones and published URLs keep working through GitHub's permanent redirect; the root manifest now declares `Apache-2.0` explicitly rather than leaving the workspace root silent.
|
|
12
|
+
|
|
13
|
+
- 5bae032: Six defects that broke real conversations, found by testing the adapters against the live platforms instead of against fakes.
|
|
14
|
+
|
|
15
|
+
**LINE — no outbound message was ever delivered.** The adapter called the v9 SDK client with positional arguments while that client takes a single request object, so LINE received an empty request and rejected every send with a 400. Upgrade if you use this adapter at all: nothing it sent reached anyone.
|
|
16
|
+
|
|
17
|
+
**Telegram — the bot froze on long replies.** Any message over 4096 characters that began with an unclosed code span (a stray backtick) put the splitter into an infinite loop, hanging the process until it ran out of memory. Long agent answers now split correctly whatever markdown they contain.
|
|
18
|
+
|
|
19
|
+
**Mattermost — long messages silently vanished.** The adapter never split anything, so any reply over 16,383 characters was rejected by the server and the user simply saw nothing. Long replies are now split into parts Mattermost accepts.
|
|
20
|
+
|
|
21
|
+
**SMS — long messages were rejected from the hundredth part onward.** The `(i/N)` prefix outgrew the space reserved for it, pushing every later part past the provider's limit.
|
|
22
|
+
|
|
23
|
+
**Matrix and LINE — `connect()` reported success with an invalid token.** Both now verify the credential with the server before returning `true`, so a wrong token fails at startup instead of silently receiving nothing forever.
|
|
24
|
+
|
|
25
|
+
**Email and Teams — the bot could go permanently deaf.** Replacing an inbound handler and then disposing of the previous one removed the new handler as well, and the gateway stopped receiving messages with nothing logged.
|
|
26
|
+
|
|
27
|
+
Also: a `pre_inbound` hook that threw put its raw error text into the user's chat, which could expose internal details such as connection strings or tokens. Users now see only which hook failed; the detail goes to the server log, redacted.
|
|
28
|
+
|
|
29
|
+
WhatsApp additionally stops opening a second session when `connect()` is called twice, and its group mention filter no longer treats unrelated digits scattered through a message as a mention of the bot.
|
|
30
|
+
|
|
31
|
+
## 0.1.1
|
|
32
|
+
|
|
33
|
+
### Patch Changes
|
|
34
|
+
|
|
35
|
+
- e926cd9: Align the gateway cluster to the hardened `@theokit/sdk` 2.18.0 Harness (ecosystem M6). Bumped the `@theokit/sdk` peer + dev dependency from `^1.9.0` to `^2.18.0` across all 11 packages. The only consumed SDK surface is `Security.redact` (in the gateway core runner) — a stable public API (ADR D68) unchanged across 1.x→2.x — so the alignment is a pin bump, not a migration. Validated: all 11 packages typecheck + build + test green against 2.18.0 (543 tests passed). No dead/unwired surfaces (`no-stubs-no-mocks-no-wired` checklist clean).
|
|
36
|
+
|
|
3
37
|
## 2.0.0
|
|
4
38
|
|
|
5
39
|
### Patch Changes
|
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 usetheo.dev
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
package/dist/index.cjs
CHANGED
|
@@ -30,45 +30,33 @@ var path__namespace = /*#__PURE__*/_interopNamespace(path);
|
|
|
30
30
|
var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
|
|
31
31
|
|
|
32
32
|
// src/adapter.ts
|
|
33
|
-
|
|
34
|
-
// src/split.ts
|
|
35
33
|
var WHATSAPP_MAX_TEXT = 4096;
|
|
36
|
-
function findWhatsAppCutPoint(remaining) {
|
|
37
|
-
let cut = remaining.lastIndexOf("\n\n", WHATSAPP_MAX_TEXT);
|
|
38
|
-
if (cut < WHATSAPP_MAX_TEXT * 0.5) cut = remaining.lastIndexOf("\n", WHATSAPP_MAX_TEXT);
|
|
39
|
-
if (cut < WHATSAPP_MAX_TEXT * 0.5) cut = remaining.lastIndexOf(" ", WHATSAPP_MAX_TEXT);
|
|
40
|
-
if (cut <= 0) cut = WHATSAPP_MAX_TEXT;
|
|
41
|
-
if (cut < remaining.length) {
|
|
42
|
-
const code = remaining.charCodeAt(cut);
|
|
43
|
-
if (code >= 56320 && code <= 57343) cut -= 1;
|
|
44
|
-
}
|
|
45
|
-
return cut <= 0 ? WHATSAPP_MAX_TEXT : cut;
|
|
46
|
-
}
|
|
47
34
|
function splitForWhatsApp(text) {
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
chunks.push(remaining.slice(0, cut));
|
|
57
|
-
remaining = remaining.slice(cut).replace(/^[\s]+/, "");
|
|
58
|
-
}
|
|
59
|
-
if (remaining.length > 0) chunks.push(remaining);
|
|
60
|
-
return chunks.map((p) => p.trim()).filter((p) => p.length > 0);
|
|
35
|
+
return gateway.chunkText(text, {
|
|
36
|
+
limit: WHATSAPP_MAX_TEXT,
|
|
37
|
+
boundaries: ["\n\n", "\n", " "],
|
|
38
|
+
lastResort: "last-boundary",
|
|
39
|
+
surrogateGuard: true,
|
|
40
|
+
stripLeading: /^\s+/,
|
|
41
|
+
trimParts: true
|
|
42
|
+
});
|
|
61
43
|
}
|
|
62
44
|
|
|
63
45
|
// src/adapter.ts
|
|
64
46
|
function digitsOnly(s) {
|
|
65
47
|
return s.replace(/[^\d]/g, "");
|
|
66
48
|
}
|
|
49
|
+
var PHONE_RUN = /[\d][\d+\-(). ]*[\d]|[\d]/g;
|
|
50
|
+
function phoneRuns(s) {
|
|
51
|
+
return (s.match(PHONE_RUN) ?? []).map(digitsOnly).filter((d) => d.length > 0);
|
|
52
|
+
}
|
|
67
53
|
var WhatsAppAdapter = class extends gateway.BasePlatformAdapter {
|
|
68
54
|
platform = "whatsapp";
|
|
69
55
|
backendImpl;
|
|
70
56
|
requireMention;
|
|
71
57
|
botPhoneId;
|
|
58
|
+
/** Mirrors the sibling adapters: guards connect() against opening a second session. */
|
|
59
|
+
connected = false;
|
|
72
60
|
handler;
|
|
73
61
|
statusHandler;
|
|
74
62
|
// EC-H: track unsubscribe handles so onInbound REPLACES instead of stacks.
|
|
@@ -86,9 +74,13 @@ var WhatsAppAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
86
74
|
return this.backendImpl;
|
|
87
75
|
}
|
|
88
76
|
async connect() {
|
|
89
|
-
|
|
77
|
+
if (this.connected) return true;
|
|
78
|
+
const ok = await this.backendImpl.connect();
|
|
79
|
+
this.connected = ok;
|
|
80
|
+
return ok;
|
|
90
81
|
}
|
|
91
82
|
async disconnect() {
|
|
83
|
+
this.connected = false;
|
|
92
84
|
this.inboundUnsubscribe?.();
|
|
93
85
|
this.inboundUnsubscribe = void 0;
|
|
94
86
|
this.statusUnsubscribe?.();
|
|
@@ -126,8 +118,7 @@ var WhatsAppAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
126
118
|
shouldDropGroupMessage(inbound) {
|
|
127
119
|
if (inbound.conversationType !== "group" || !this.requireMention) return false;
|
|
128
120
|
if (this.botPhoneId.length === 0) return true;
|
|
129
|
-
|
|
130
|
-
return !textDigits.includes(this.botPhoneId);
|
|
121
|
+
return !phoneRuns(inbound.text).some((run) => run.includes(this.botPhoneId));
|
|
131
122
|
}
|
|
132
123
|
toMessageEvent(inbound) {
|
|
133
124
|
return {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +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,CA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,EAAyB,KAAA,CAAM,OAAO;AAAA,CAAI,CAAA;AAC/D,QAAA;AAAA;AACJ,EACF;AACF;AAEA,SAAS,uBAAA,GAAkC;AAGzC,EAAA,OAAYC,eAAA,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"]}
|
|
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":["chunkText","BasePlatformAdapter","crypto","path","fs","execSync","spawn","resolve","path2"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,IAAM,iBAAA,GAAoB,IAAA;AAEnB,SAAS,iBAAiB,IAAA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ourcesContent":["/**\n * Split a long string into ≤4096-char chunks for WhatsApp messages (ADR D310).\n *\n * Thin wrapper over core `chunkText` (roadmap M1). WhatsApp family: fixed 4096\n * window, `\\n\\n` → `\\n` → ` ` boundary preference, UTF-16 surrogate-pair guard,\n * leading-whitespace strip. `trimParts` reproduces EC-8 (empty parts filtered\n * so consecutive newlines don't yield empty `sendMessage` calls Meta rejects).\n * Output is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\nconst WHATSAPP_MAX_TEXT = 4096;\n\nexport function splitForWhatsApp(text: string): string[] {\n return chunkText(text, {\n limit: WHATSAPP_MAX_TEXT,\n boundaries: [\"\\n\\n\", \"\\n\", \" \"],\n lastResort: \"last-boundary\",\n surrogateGuard: true,\n stripLeading: /^\\s+/,\n trimParts: true,\n });\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 * Characters that may appear INSIDE a written phone number: digits and the\n * separators people type around them. Anything else — a letter, a comma, a\n * newline — ends the run.\n */\nconst PHONE_RUN = /[\\d][\\d+\\-(). ]*[\\d]|[\\d]/g;\n\n/**\n * EC-7: the phone-like runs in a message, each normalized to digits.\n *\n * The filter used to normalize the WHOLE message and ask whether the result\n * contained the bot's number. That accepts the four documented formats, but it\n * also concatenates digits from unrelated words: with a bot at 5511999999999,\n * `\"pedido 55 chegou 11, ref 99999-9999 ok\"` normalized to a string containing\n * exactly that number, and the bot answered a message about an order. Every\n * group message carrying scattered digits woke it.\n *\n * Scanning runs instead keeps the separators irrelevant WITHIN a number — which\n * is what EC-7 asks for, and what `\"+55 (11) 99999-9999\"` needs — while letting\n * a letter or a comma do what it visually does: end the number.\n */\nexport function phoneRuns(s: string): string[] {\n return (s.match(PHONE_RUN) ?? []).map(digitsOnly).filter((d) => d.length > 0);\n}\n\n/**\n * Adapter facade. 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 /** Mirrors the sibling adapters: guards connect() against opening a second session. */\n private connected = false;\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 // Guard added 2026-08-17: this was the only adapter without one, so a second\n // connect() opened a second live WhatsApp session. Teams, SMS and Slack all\n // short-circuit here. Note it latches on SUCCESS only — a refused connect\n // must stay retryable, or one network blip becomes permanent.\n if (this.connected) return true;\n const ok = await this.backendImpl.connect();\n this.connected = ok;\n return ok;\n }\n\n async disconnect(): Promise<void> {\n this.connected = false;\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 return !phoneRuns(inbound.text).some((run) => run.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
CHANGED
|
@@ -123,7 +123,7 @@ type WhatsAppAdapterOptions = {
|
|
|
123
123
|
/** EC-7: digit-only normalizer for mention comparison (handles `+`, `-`, `()`, spaces). */
|
|
124
124
|
declare function digitsOnly(s: string): string;
|
|
125
125
|
/**
|
|
126
|
-
* Adapter
|
|
126
|
+
* Adapter facade. Implements `BasePlatformAdapter` (D172).
|
|
127
127
|
*
|
|
128
128
|
* Use `WhatsAppAdapter.fromCloud(config)` or `WhatsAppAdapter.fromWeb(config)`
|
|
129
129
|
* once the backend factories land (or pass `backend` directly in constructor).
|
|
@@ -133,6 +133,8 @@ declare class WhatsAppAdapter extends BasePlatformAdapter {
|
|
|
133
133
|
private readonly backendImpl;
|
|
134
134
|
private readonly requireMention;
|
|
135
135
|
private readonly botPhoneId;
|
|
136
|
+
/** Mirrors the sibling adapters: guards connect() against opening a second session. */
|
|
137
|
+
private connected;
|
|
136
138
|
private handler?;
|
|
137
139
|
private statusHandler?;
|
|
138
140
|
private inboundUnsubscribe?;
|
|
@@ -416,10 +418,12 @@ declare function mapWhatsAppWebError(ipcError: string | undefined): ErrorPayload
|
|
|
416
418
|
/**
|
|
417
419
|
* Split a long string into ≤4096-char chunks for WhatsApp messages (ADR D310).
|
|
418
420
|
*
|
|
419
|
-
*
|
|
420
|
-
*
|
|
421
|
-
* EC-8
|
|
422
|
-
* newlines don't
|
|
421
|
+
* Thin wrapper over core `chunkText` (roadmap M1). WhatsApp family: fixed 4096
|
|
422
|
+
* window, `\n\n` → `\n` → ` ` boundary preference, UTF-16 surrogate-pair guard,
|
|
423
|
+
* leading-whitespace strip. `trimParts` reproduces EC-8 (empty parts filtered
|
|
424
|
+
* so consecutive newlines don't yield empty `sendMessage` calls Meta rejects).
|
|
425
|
+
* Output is byte-identical to the previous implementation (pinned by
|
|
426
|
+
* `tests/split.test.ts`).
|
|
423
427
|
*
|
|
424
428
|
* @internal
|
|
425
429
|
*/
|
package/dist/index.d.ts
CHANGED
|
@@ -123,7 +123,7 @@ type WhatsAppAdapterOptions = {
|
|
|
123
123
|
/** EC-7: digit-only normalizer for mention comparison (handles `+`, `-`, `()`, spaces). */
|
|
124
124
|
declare function digitsOnly(s: string): string;
|
|
125
125
|
/**
|
|
126
|
-
* Adapter
|
|
126
|
+
* Adapter facade. Implements `BasePlatformAdapter` (D172).
|
|
127
127
|
*
|
|
128
128
|
* Use `WhatsAppAdapter.fromCloud(config)` or `WhatsAppAdapter.fromWeb(config)`
|
|
129
129
|
* once the backend factories land (or pass `backend` directly in constructor).
|
|
@@ -133,6 +133,8 @@ declare class WhatsAppAdapter extends BasePlatformAdapter {
|
|
|
133
133
|
private readonly backendImpl;
|
|
134
134
|
private readonly requireMention;
|
|
135
135
|
private readonly botPhoneId;
|
|
136
|
+
/** Mirrors the sibling adapters: guards connect() against opening a second session. */
|
|
137
|
+
private connected;
|
|
136
138
|
private handler?;
|
|
137
139
|
private statusHandler?;
|
|
138
140
|
private inboundUnsubscribe?;
|
|
@@ -416,10 +418,12 @@ declare function mapWhatsAppWebError(ipcError: string | undefined): ErrorPayload
|
|
|
416
418
|
/**
|
|
417
419
|
* Split a long string into ≤4096-char chunks for WhatsApp messages (ADR D310).
|
|
418
420
|
*
|
|
419
|
-
*
|
|
420
|
-
*
|
|
421
|
-
* EC-8
|
|
422
|
-
* newlines don't
|
|
421
|
+
* Thin wrapper over core `chunkText` (roadmap M1). WhatsApp family: fixed 4096
|
|
422
|
+
* window, `\n\n` → `\n` → ` ` boundary preference, UTF-16 surrogate-pair guard,
|
|
423
|
+
* leading-whitespace strip. `trimParts` reproduces EC-8 (empty parts filtered
|
|
424
|
+
* so consecutive newlines don't yield empty `sendMessage` calls Meta rejects).
|
|
425
|
+
* Output is byte-identical to the previous implementation (pinned by
|
|
426
|
+
* `tests/split.test.ts`).
|
|
423
427
|
*
|
|
424
428
|
* @internal
|
|
425
429
|
*/
|
package/dist/index.js
CHANGED
|
@@ -1,49 +1,37 @@
|
|
|
1
|
-
import { BasePlatformAdapter } from '@theokit/gateway';
|
|
1
|
+
import { chunkText, BasePlatformAdapter } from '@theokit/gateway';
|
|
2
2
|
import * as crypto from 'crypto';
|
|
3
3
|
import * as path from 'path';
|
|
4
4
|
import { spawn, execSync } from 'child_process';
|
|
5
5
|
import * as fs from 'fs';
|
|
6
6
|
|
|
7
7
|
// src/adapter.ts
|
|
8
|
-
|
|
9
|
-
// src/split.ts
|
|
10
8
|
var WHATSAPP_MAX_TEXT = 4096;
|
|
11
|
-
function findWhatsAppCutPoint(remaining) {
|
|
12
|
-
let cut = remaining.lastIndexOf("\n\n", WHATSAPP_MAX_TEXT);
|
|
13
|
-
if (cut < WHATSAPP_MAX_TEXT * 0.5) cut = remaining.lastIndexOf("\n", WHATSAPP_MAX_TEXT);
|
|
14
|
-
if (cut < WHATSAPP_MAX_TEXT * 0.5) cut = remaining.lastIndexOf(" ", WHATSAPP_MAX_TEXT);
|
|
15
|
-
if (cut <= 0) cut = WHATSAPP_MAX_TEXT;
|
|
16
|
-
if (cut < remaining.length) {
|
|
17
|
-
const code = remaining.charCodeAt(cut);
|
|
18
|
-
if (code >= 56320 && code <= 57343) cut -= 1;
|
|
19
|
-
}
|
|
20
|
-
return cut <= 0 ? WHATSAPP_MAX_TEXT : cut;
|
|
21
|
-
}
|
|
22
9
|
function splitForWhatsApp(text) {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
chunks.push(remaining.slice(0, cut));
|
|
32
|
-
remaining = remaining.slice(cut).replace(/^[\s]+/, "");
|
|
33
|
-
}
|
|
34
|
-
if (remaining.length > 0) chunks.push(remaining);
|
|
35
|
-
return chunks.map((p) => p.trim()).filter((p) => p.length > 0);
|
|
10
|
+
return chunkText(text, {
|
|
11
|
+
limit: WHATSAPP_MAX_TEXT,
|
|
12
|
+
boundaries: ["\n\n", "\n", " "],
|
|
13
|
+
lastResort: "last-boundary",
|
|
14
|
+
surrogateGuard: true,
|
|
15
|
+
stripLeading: /^\s+/,
|
|
16
|
+
trimParts: true
|
|
17
|
+
});
|
|
36
18
|
}
|
|
37
19
|
|
|
38
20
|
// src/adapter.ts
|
|
39
21
|
function digitsOnly(s) {
|
|
40
22
|
return s.replace(/[^\d]/g, "");
|
|
41
23
|
}
|
|
24
|
+
var PHONE_RUN = /[\d][\d+\-(). ]*[\d]|[\d]/g;
|
|
25
|
+
function phoneRuns(s) {
|
|
26
|
+
return (s.match(PHONE_RUN) ?? []).map(digitsOnly).filter((d) => d.length > 0);
|
|
27
|
+
}
|
|
42
28
|
var WhatsAppAdapter = class extends BasePlatformAdapter {
|
|
43
29
|
platform = "whatsapp";
|
|
44
30
|
backendImpl;
|
|
45
31
|
requireMention;
|
|
46
32
|
botPhoneId;
|
|
33
|
+
/** Mirrors the sibling adapters: guards connect() against opening a second session. */
|
|
34
|
+
connected = false;
|
|
47
35
|
handler;
|
|
48
36
|
statusHandler;
|
|
49
37
|
// EC-H: track unsubscribe handles so onInbound REPLACES instead of stacks.
|
|
@@ -61,9 +49,13 @@ var WhatsAppAdapter = class extends BasePlatformAdapter {
|
|
|
61
49
|
return this.backendImpl;
|
|
62
50
|
}
|
|
63
51
|
async connect() {
|
|
64
|
-
|
|
52
|
+
if (this.connected) return true;
|
|
53
|
+
const ok = await this.backendImpl.connect();
|
|
54
|
+
this.connected = ok;
|
|
55
|
+
return ok;
|
|
65
56
|
}
|
|
66
57
|
async disconnect() {
|
|
58
|
+
this.connected = false;
|
|
67
59
|
this.inboundUnsubscribe?.();
|
|
68
60
|
this.inboundUnsubscribe = void 0;
|
|
69
61
|
this.statusUnsubscribe?.();
|
|
@@ -101,8 +93,7 @@ var WhatsAppAdapter = class extends BasePlatformAdapter {
|
|
|
101
93
|
shouldDropGroupMessage(inbound) {
|
|
102
94
|
if (inbound.conversationType !== "group" || !this.requireMention) return false;
|
|
103
95
|
if (this.botPhoneId.length === 0) return true;
|
|
104
|
-
|
|
105
|
-
return !textDigits.includes(this.botPhoneId);
|
|
96
|
+
return !phoneRuns(inbound.text).some((run) => run.includes(this.botPhoneId));
|
|
106
97
|
}
|
|
107
98
|
toMessageEvent(inbound) {
|
|
108
99
|
return {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +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":["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,OAAO,GAAA,IAAO,IAAI,iBAAA,GAAoB,GAAA;AACxC;AAEO,SAAS,iBAAiB,IAAA,EAAwB;AACvD,EAAA,IAAI,IAAA,CAAK,UAAU,iBAAA,EAAmB;AACpC,IAAA,MAAM,MAAA,GAAS,KAAK,IAAA,EAAK;AACzB,IAAA,OAAO,OAAO,MAAA,GAAS,CAAA,GAAI,CAAC,MAAM,IAAI,EAAC;AAAA,EACzC;AACA,EAAA,MAAM,SAAmB,EAAC;AAC1B,EAAA,IAAI,SAAA,GAAY,IAAA;AAChB,EAAA,OAAO,SAAA,CAAU,SAAS,iBAAA,EAAmB;AAC3C,IAAA,MAAM,GAAA,GAAM,qBAAqB,SAAS,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AAAA,MACtB,OAAO,KAAA,CAAM,KAAA;AAAA,MACb,QAAQ,KAAA,CAAM,MAAA;AAAA,MACd,WAAW,KAAA,CAAM,SAAA;AAAA,MACjB,SAAA,EAAW,KAAA,CAAM,SAAA,IAAa,IAAA,CAAK,GAAA;AAAI,KACxC,CAAA;AAAA,EACH;AAAA,EAEQ,SAAS,KAAA,EAAuB;AACtC,IAAA,QAAQ,MAAM,KAAA;AAAO,MACnB,KAAK,OAAA;AACH,QAAA,IAAA,CAAK,YAAY,KAAK,CAAA;AACtB,QAAA;AAAA,MACF,KAAK,SAAA;AACH,QAAA,IAAA,CAAK,cAAc,KAAK,CAAA;AACxB,QAAA;AAAA,MACF,KAAK,UAAA;AACH,QAAA,IAAA,CAAK,cAAc,KAAK,CAAA;AACxB,QAAA;AAAA,MACF,KAAK,QAAA;AACH,QAAA,IAAA,CAAK,aAAa,KAAK,CAAA;AACvB,QAAA;AAAA,MACF,KAAK,OAAA;AACH,QAAA,OAAA,CAAQ,MAAA,CAAO,KAAA,CAAM,CAAA,sBAAA,EAAyB,KAAA,CAAM,OAAO;AAAA,CAAI,CAAA;AAC/D,QAAA;AAAA;AACJ,EACF;AACF;AAEA,SAAS,uBAAA,GAAkC;AAGzC,EAAA,OAAYC,IAAA,CAAA,OAAA;AAAA,IACLA,aAAQ,IAAI,GAAA,CAAI,MAAA,CAAA,IAAA,CAAY,GAAG,EAAE,QAAQ,CAAA;AAAA,IAC9C;AAAA,GACF;AACF","file":"index.js","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"]}
|
|
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":["resolve","path2"],"mappings":";;;;;;;AAeA,IAAM,iBAAA,GAAoB,IAAA;AAEnB,SAAS,iBAAiB,IAAA,EAAwB;AACvD,EAAA,OAAO,UAAU,IAAA,EAAM;AAAA,IACrB,KAAA,EAAO,iBAAA;AAAA,IACP,UAAA,EAAY,CAAC,MAAA,EAAQ,IAAA,EAAM,GAAG,CAAA;AAAA,IAC9B,UAAA,EAAY,eAAA;AAAA,IACZ,cAAA,EAAgB,IAAA;AAAA,IAChB,YAAA,EAAc,MAAA;AAAA,IACd,SAAA,EAAW;AAAA,GACZ,CAAA;AACH;;;ACuCO,SAAS,WAAW,CAAA,EAAmB;AAC5C,EAAA,OAAO,CAAA,CAAE,OAAA,CAAQ,QAAA,EAAU,EAAE,CAAA;AAC/B;AAOA,IAAM,SAAA,GAAY,6BAAA;AAgBX,SAAS,UAAU,CAAA,EAAqB;AAC7C,EAAA,OAAA,CAAQ,CAAA,CAAE,KAAA,CAAM,SAAS,CAAA,IAAK,EAAC,EAAG,GAAA,CAAI,UAAU,CAAA,CAAE,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,SAAS,CAAC,CAAA;AAC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,CAAA;AACtB,QAAA;AAAA,MACF,KAAK,SAAA;AACH,QAAA,IAAA,CAAK,cAAc,KAAK,CAAA;AACxB,QAAA;AAAA,MACF,KAAK,UAAA;AACH,QAAA,IAAA,CAAK,cAAc,KAAK,CAAA;AACxB,QAAA;AAAA,MACF,KAAK,QAAA;AACH,QAAA,IAAA,CAAK,aAAa,KAAK,CAAA;AACvB,QAAA;AAAA,MACF,KAAK,OAAA;AACH,QAAA,OAAA,CAAQ,MAAA,CAAO,KAAA,CAAM,CAAA,sBAAA,EAAyB,KAAA,CAAM,OAAO;AAAA,CAAI,CAAA;AAC/D,QAAA;AAAA;AACJ,EACF;AACF;AAEA,SAAS,uBAAA,GAAkC;AAGzC,EAAA,OAAYC,IAAA,CAAA,OAAA;AAAA,IACLA,aAAQ,IAAI,GAAA,CAAI,MAAA,CAAA,IAAA,CAAY,GAAG,EAAE,QAAQ,CAAA;AAAA,IAC9C;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\n * Split a long string into ≤4096-char chunks for WhatsApp messages (ADR D310).\n *\n * Thin wrapper over core `chunkText` (roadmap M1). WhatsApp family: fixed 4096\n * window, `\\n\\n` → `\\n` → ` ` boundary preference, UTF-16 surrogate-pair guard,\n * leading-whitespace strip. `trimParts` reproduces EC-8 (empty parts filtered\n * so consecutive newlines don't yield empty `sendMessage` calls Meta rejects).\n * Output is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\nconst WHATSAPP_MAX_TEXT = 4096;\n\nexport function splitForWhatsApp(text: string): string[] {\n return chunkText(text, {\n limit: WHATSAPP_MAX_TEXT,\n boundaries: [\"\\n\\n\", \"\\n\", \" \"],\n lastResort: \"last-boundary\",\n surrogateGuard: true,\n stripLeading: /^\\s+/,\n trimParts: true,\n });\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 * Characters that may appear INSIDE a written phone number: digits and the\n * separators people type around them. Anything else — a letter, a comma, a\n * newline — ends the run.\n */\nconst PHONE_RUN = /[\\d][\\d+\\-(). ]*[\\d]|[\\d]/g;\n\n/**\n * EC-7: the phone-like runs in a message, each normalized to digits.\n *\n * The filter used to normalize the WHOLE message and ask whether the result\n * contained the bot's number. That accepts the four documented formats, but it\n * also concatenates digits from unrelated words: with a bot at 5511999999999,\n * `\"pedido 55 chegou 11, ref 99999-9999 ok\"` normalized to a string containing\n * exactly that number, and the bot answered a message about an order. Every\n * group message carrying scattered digits woke it.\n *\n * Scanning runs instead keeps the separators irrelevant WITHIN a number — which\n * is what EC-7 asks for, and what `\"+55 (11) 99999-9999\"` needs — while letting\n * a letter or a comma do what it visually does: end the number.\n */\nexport function phoneRuns(s: string): string[] {\n return (s.match(PHONE_RUN) ?? []).map(digitsOnly).filter((d) => d.length > 0);\n}\n\n/**\n * Adapter facade. 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 /** Mirrors the sibling adapters: guards connect() against opening a second session. */\n private connected = false;\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 // Guard added 2026-08-17: this was the only adapter without one, so a second\n // connect() opened a second live WhatsApp session. Teams, SMS and Slack all\n // short-circuit here. Note it latches on SUCCESS only — a refused connect\n // must stay retryable, or one network blip becomes permanent.\n if (this.connected) return true;\n const ok = await this.backendImpl.connect();\n this.connected = ok;\n return ok;\n }\n\n async disconnect(): Promise<void> {\n this.connected = false;\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 return !phoneRuns(inbound.text).some((run) => run.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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/gateway-whatsapp",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "WhatsApp platform adapter for @theokit/gateway. Multi-backend (Meta Cloud API + whatsapp-web.js bridge). ADRs D303-D314.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -29,15 +29,10 @@
|
|
|
29
29
|
"LICENSE",
|
|
30
30
|
"CHANGELOG.md"
|
|
31
31
|
],
|
|
32
|
-
"scripts": {
|
|
33
|
-
"build": "tsup",
|
|
34
|
-
"typecheck": "tsc --noEmit",
|
|
35
|
-
"test": "vitest run"
|
|
36
|
-
},
|
|
37
32
|
"peerDependencies": {
|
|
38
|
-
"@theokit/
|
|
39
|
-
"
|
|
40
|
-
"
|
|
33
|
+
"@theokit/sdk": "^2.18.0",
|
|
34
|
+
"whatsapp-web.js": "^1.23.0",
|
|
35
|
+
"@theokit/gateway": "^0.5.1"
|
|
41
36
|
},
|
|
42
37
|
"peerDependenciesMeta": {
|
|
43
38
|
"whatsapp-web.js": {
|
|
@@ -45,10 +40,16 @@
|
|
|
45
40
|
}
|
|
46
41
|
},
|
|
47
42
|
"devDependencies": {
|
|
48
|
-
"@theokit/
|
|
49
|
-
"@theokit/sdk": "workspace:*",
|
|
43
|
+
"@theokit/sdk": "^2.18.0",
|
|
50
44
|
"tsup": "^8.5.0",
|
|
51
45
|
"typescript": "^5.8.0",
|
|
52
|
-
"vitest": "^
|
|
46
|
+
"vitest": "^4.1.8",
|
|
47
|
+
"zod": "^4.0.0",
|
|
48
|
+
"@theokit/gateway": "0.5.1"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"build": "tsup",
|
|
52
|
+
"typecheck": "tsc --noEmit",
|
|
53
|
+
"test": "vitest run"
|
|
53
54
|
}
|
|
54
|
-
}
|
|
55
|
+
}
|