@12-apps/messaging 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ADOPTING.md +119 -0
- package/README.md +157 -2
- package/dist/channel-Cs_vLGl_.d.ts +293 -0
- package/dist/chunk-72TDAQUW.js +136 -0
- package/dist/chunk-72TDAQUW.js.map +1 -0
- package/dist/chunk-7QVYU63E.js +7 -0
- package/dist/chunk-7QVYU63E.js.map +1 -0
- package/dist/chunk-R3DKM2IV.js +42 -0
- package/dist/chunk-R3DKM2IV.js.map +1 -0
- package/dist/chunk-Y7MG2UDQ.js +36 -0
- package/dist/chunk-Y7MG2UDQ.js.map +1 -0
- package/dist/engine-DTnp2zUL.d.ts +431 -0
- package/dist/index.d.ts +97 -0
- package/dist/index.js +999 -0
- package/dist/index.js.map +1 -0
- package/dist/manifest/index.d.ts +36 -0
- package/dist/manifest/index.js +14 -0
- package/dist/manifest/index.js.map +1 -0
- package/dist/manifest/server.d.ts +21 -0
- package/dist/manifest/server.js +17 -0
- package/dist/manifest/server.js.map +1 -0
- package/dist/server/index.d.ts +78 -0
- package/dist/server/index.js +15 -0
- package/dist/server/index.js.map +1 -0
- package/dist/whatsapp/index.d.ts +180 -0
- package/dist/whatsapp/index.js +385 -0
- package/dist/whatsapp/index.js.map +1 -0
- package/package.json +90 -4
- package/prisma/messaging.prisma +140 -0
- package/prisma/migrations/20261114120000_messaging_connector/migration.sql +110 -0
- package/src/core/channel.ts +106 -0
- package/src/core/connections.ts +67 -0
- package/src/core/context.ts +28 -0
- package/src/core/engine.ts +64 -0
- package/src/core/errors.ts +53 -0
- package/src/core/hash.ts +6 -0
- package/src/core/inbound.ts +240 -0
- package/src/core/inbox.ts +139 -0
- package/src/core/memory-store.ts +273 -0
- package/src/core/ports.ts +129 -0
- package/src/core/prisma-store.ts +354 -0
- package/src/core/retention.ts +27 -0
- package/src/core/sender.ts +106 -0
- package/src/core/store.ts +217 -0
- package/src/core/types.ts +189 -0
- package/src/index.ts +54 -0
- package/src/manifest/index.ts +32 -0
- package/src/manifest/server.ts +18 -0
- package/src/server/index.ts +22 -0
- package/src/server/jobs.ts +99 -0
- package/src/server/webhook.ts +92 -0
- package/src/whatsapp/graph.ts +136 -0
- package/src/whatsapp/index.ts +64 -0
- package/src/whatsapp/opt-out.ts +26 -0
- package/src/whatsapp/parse.ts +200 -0
- package/src/whatsapp/signature.ts +52 -0
- package/src/whatsapp/signup.ts +115 -0
package/ADOPTING.md
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# Adopting @12-apps/messaging
|
|
2
|
+
|
|
3
|
+
The engine supplies the mechanism; the host answers what only it knows. Below
|
|
4
|
+
is what a host binds, in the order it binds it.
|
|
5
|
+
|
|
6
|
+
## 1. The database
|
|
7
|
+
|
|
8
|
+
The manifest's `db` capability is `composed`: copy `prisma/messaging.prisma`
|
|
9
|
+
into the host's multi-file schema folder (never a symlink) and apply
|
|
10
|
+
`prisma/migrations/20261114120000_messaging_connector` with the host's own
|
|
11
|
+
migrations. The partial names no host table: `tenant_id` and `staff_user_id`
|
|
12
|
+
are by-value strings with no foreign key. A host that declares domains per
|
|
13
|
+
table places the four tables (`messaging_connections`,
|
|
14
|
+
`messaging_inbox_deliveries`, `messaging_conversations`,
|
|
15
|
+
`messaging_messages`) in one domain of its own.
|
|
16
|
+
|
|
17
|
+
The host's links to its own world (a cart minted by a conversation, a matched
|
|
18
|
+
customer, the sale it led to) go in HOST tables keyed by the conversation id,
|
|
19
|
+
never in these.
|
|
20
|
+
|
|
21
|
+
## 2. The engine and its ports (`MessagingEngineConfig`)
|
|
22
|
+
|
|
23
|
+
| port | type | what the host answers |
|
|
24
|
+
|---|---|---|
|
|
25
|
+
| `store` | `MessagingStore` | `createPrismaMessagingStore(prisma)` over the client generated from a schema that includes the partial (structural: the delegates `messagingConnection`, `messagingInboxDelivery`, `messagingConversation`, `messagingMessage`). `createMemoryMessagingStore()` for tests. |
|
|
26
|
+
| `adapters` | `readonly ChannelAdapter[]` | One per channel: `createWhatsAppAdapter({ appSecret, verifyToken, graph: { fetch, baseUrl, apiVersion } })`. The app secret and verify token are read where the host keeps secrets; an empty one refuses every delivery or handshake. |
|
|
27
|
+
| `secrets` | `{ seal(plain); open(sealed) }` | Seal and open a connection's credential with the host's key (sync or async). `open` THROWS on a blob that will not open. |
|
|
28
|
+
| `enqueue` | `{ enqueue(name, payload, { dedupeKey? }) }` | The wiring `JobsEnqueuePort`. Never throws. The engine queues only `messaging.process-delivery` (`{ deliveryId }`, dedupe key `messaging.process-delivery:<deliveryId>`). |
|
|
29
|
+
| `clock` | `{ now(): Date }` | What time it is. |
|
|
30
|
+
| `logger` | `{ info, warn, error }` | The wiring `LoggerPort`; bind the `messaging` namespace's logger. Never handed a credential. |
|
|
31
|
+
| `hooks.onInboundMessage` | OPTIONAL. `({ conversation, message }) => Promise<void>` | A contact's message was stored: hand it to the host's agent or a person's inbox. Once per message, never for a redelivery, never for an opt-out. Keep it short (enqueue the host's own job): a throw is logged and not retried. Default: nothing. |
|
|
32
|
+
| `hooks.reopenState` | OPTIONAL. `(conversation) => "AGENT" \| "HUMAN" \| "CLOSED"` | The state a `CLOSED` or `OPTED_OUT` conversation re-opens into when its contact writes again (for `OPTED_OUT`, only a message sent AFTER the opt-out re-opens it). Default `AGENT`. The type refuses `OPTED_OUT`: only the contact's own words put a conversation there, and an answer of `OPTED_OUT` from a JavaScript host is read as `AGENT`. |
|
|
33
|
+
| `retentionMs` | OPTIONAL, default 12 h | How long text is kept after a conversation's last message. |
|
|
34
|
+
| `retentionBatchSize`, `reconcileBatchSize`, `maxDeliveryAttempts`, `reconcileAfterMs` | OPTIONAL | 500, 50, 5, 2 minutes. |
|
|
35
|
+
|
|
36
|
+
## 3. The wiring capabilities
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
import { messagingManifest } from "@12-apps/messaging/manifest";
|
|
40
|
+
import { messagingServerManifest } from "@12-apps/messaging/manifest/server";
|
|
41
|
+
|
|
42
|
+
host.adoptServer({
|
|
43
|
+
manifest: messagingManifest,
|
|
44
|
+
server: messagingServerManifest,
|
|
45
|
+
bindings: {
|
|
46
|
+
http: { mountPath: "/api", config: { engine, logger } },
|
|
47
|
+
jobs: { deps: { engine } },
|
|
48
|
+
},
|
|
49
|
+
});
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
- **`http`** — `GET` and `POST /webhooks/messaging/:channel`, both `kind:
|
|
53
|
+
"webhook"` (public: the channel authenticates by signature, per delivery).
|
|
54
|
+
Mounted at `/api`, WhatsApp's callback URL is
|
|
55
|
+
`/api/webhooks/messaging/whatsapp`. ONE URL per channel, for every tenant:
|
|
56
|
+
the tenant is resolved from the event's account, not the path — state that
|
|
57
|
+
routing exception wherever the host documents its webhook layout. The host's
|
|
58
|
+
adapter must populate `request.request` (the raw fetch `Request`): the
|
|
59
|
+
signature is over the raw bytes, which the route reads as bytes and checks
|
|
60
|
+
before decoding. The package puts NO cap on the body it reads before the
|
|
61
|
+
signature is checked, so the host's framework must (a body-size limit in front
|
|
62
|
+
of the route; Meta's payloads are far below 1 MB).
|
|
63
|
+
- **`jobs`** — `messaging.process-delivery` (on demand, 5 attempts),
|
|
64
|
+
`messaging.reconcile-inbox` (every 5 minutes) and `messaging.retention`
|
|
65
|
+
(every 10 minutes), the two sweeps on the single-flight `sweeps` queue with
|
|
66
|
+
a lease. A host with no worker processes nothing, so it should not adopt the
|
|
67
|
+
connector.
|
|
68
|
+
- **`db`** — section 1. **`observability`** — the `messaging` namespace.
|
|
69
|
+
|
|
70
|
+
Declined by the package, with the argument in `.wiring-conformance.json`:
|
|
71
|
+
`permissions` (no authenticated route ships yet; the host gates its own
|
|
72
|
+
connect and conversation routes), `notifications` (the host tells people
|
|
73
|
+
through `onInboundMessage`), `mcp` (conversations and phone numbers are off the
|
|
74
|
+
agent surface by design: a host must not put them back on it), `email`, the
|
|
75
|
+
environment, `e2e` and the web capabilities.
|
|
76
|
+
|
|
77
|
+
## 4. Connecting a WhatsApp number (Embedded Signup)
|
|
78
|
+
|
|
79
|
+
The browser half is Meta's SDK popup; it returns a `code`. The server half:
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
import { exchangeSignupCode, readSignupAccounts, subscribeAppToWaba } from "@12-apps/messaging/whatsapp";
|
|
83
|
+
|
|
84
|
+
const { accessToken } = await exchangeSignupCode(graph, { appId, appSecret, code });
|
|
85
|
+
const [account] = await readSignupAccounts(graph, { appId, appSecret, accessToken });
|
|
86
|
+
const [number] = account.phoneNumbers;
|
|
87
|
+
await subscribeAppToWaba(graph, { wabaId: account.wabaId, accessToken });
|
|
88
|
+
await engine.connect({
|
|
89
|
+
tenantId,
|
|
90
|
+
channel: "whatsapp",
|
|
91
|
+
externalAccountId: number.id,
|
|
92
|
+
externalParentId: account.wabaId,
|
|
93
|
+
displayAddress: number.displayPhoneNumber,
|
|
94
|
+
credential: accessToken, // sealed by the engine; never returned
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
`connect` refuses (`MessagingConnectError`, `ACCOUNT_TAKEN`) a number another
|
|
99
|
+
tenant holds, connected or in error; only a number its tenant revoked
|
|
100
|
+
(`engine.revoke`) can be connected elsewhere. `engine.markError` records a
|
|
101
|
+
token the channel rejects.
|
|
102
|
+
|
|
103
|
+
## 5. What the host calls on the engine
|
|
104
|
+
|
|
105
|
+
| call | when |
|
|
106
|
+
|---|---|
|
|
107
|
+
| `send({ tenantId, conversationId, content, author })` | The agent's or a person's reply. Catch `MessagingSendError` and read `code`: `OPTED_OUT`, `WINDOW_CLOSED`, `NOT_CONNECTED`, `NOT_FOUND`, `UNKNOWN_CHANNEL`, `CHANNEL_FAILED` (the row is `FAILED`; `messageId` names it). A `FAILED` row is NOT proof the message never reached the contact (a timeout, or a reply with no message id, can follow a send Meta made): retrying it can double-send, so a host that retries should say so to the person. An opt-out that lands while a send is in flight cannot recall it. The sentence a person reads is the host's copy. |
|
|
108
|
+
| `setState(tenantId, conversationId, "AGENT" \| "HUMAN" \| "CLOSED")` | A hand-off. Returns null for an opted-out conversation: only the contact re-opens it. |
|
|
109
|
+
| `setSummary(tenantId, conversationId, summary)` | Replace the structured summary that outlives the text. Structured fields only, never free text. |
|
|
110
|
+
| `setTranscript(tenantId, messageId, text)` | An audio message's transcript. Deleted with the text. |
|
|
111
|
+
| `getConversation`, `listMessages`, `listConnections` | The host's own screens. No call returns a credential. |
|
|
112
|
+
| `revoke`, `markError` | Disconnecting a number (the sealed credential is cleared), or recording a token Meta rejects. |
|
|
113
|
+
|
|
114
|
+
## 6. What stays the host's
|
|
115
|
+
|
|
116
|
+
Every sentence a person reads; who may connect a number or reply (the host's
|
|
117
|
+
permissions in front of its own routes); the agent behind `onInboundMessage`;
|
|
118
|
+
matching a contact to the host's own customer record; plan gates and usage
|
|
119
|
+
metering; and the links from a conversation to anything the host sells.
|
package/README.md
CHANGED
|
@@ -1,3 +1,158 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @12-apps/messaging
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A channel-agnostic conversational messaging connector. A tenant connects an
|
|
4
|
+
account on a messaging channel (a WhatsApp number today); the people who write
|
|
5
|
+
to it become **conversations**; what they write is stored, handed to the host,
|
|
6
|
+
and answered through the same channel. Each channel is an **adapter**; the
|
|
7
|
+
engine knows no channel.
|
|
8
|
+
|
|
9
|
+
WhatsApp Cloud API is the first adapter, at `@12-apps/messaging/whatsapp`.
|
|
10
|
+
E-mail, a chat workspace or any other channel joins later as one more object
|
|
11
|
+
of the same shape.
|
|
12
|
+
|
|
13
|
+
How a host adopts it: [ADOPTING.md](./ADOPTING.md).
|
|
14
|
+
|
|
15
|
+
## What the engine holds
|
|
16
|
+
|
|
17
|
+
| | |
|
|
18
|
+
|---|---|
|
|
19
|
+
| **Connections** | One row per account a tenant connected (`messaging_connections`). The channel's account id (WhatsApp's `phone_number_id`) is UNIQUE across tenants: an inbound event names the account, and the account names exactly one tenant. The credential (a business token) is SEALED through the host's encryption port; the package never sees a key, and never returns or logs the credential. Status `CONNECTED`, `REVOKED` or `ERROR`. |
|
|
20
|
+
| **The inbox** | Every verified delivery, raw, stored BEFORE the 200 (`messaging_inbox_deliveries`), unique on the SHA-256 of its body — a channel with no per-delivery id redelivers the same bytes. Processing state `PENDING` / `PROCESSED` / `FAILED`, attempts, the error. |
|
|
21
|
+
| **Conversations** | One per `(tenant, channel, contact)` (`messaging_conversations`). Owner state `AGENT` / `HUMAN` / `CLOSED` / `OPTED_OUT`, `lastInboundAt` (the service window counts from it), `lastMessageAt`, and a structured `summary` (JSON) with `summaryUpdatedAt`, which OUTLIVES the text. |
|
|
22
|
+
| **Messages** | Both directions (`messaging_messages`): kind (`TEXT`, `INTERACTIVE`, `AUDIO`, `OTHER`), body, an interactive message's choices, transcript, the channel's id (UNIQUE per channel: a redelivered message is a no-op), delivery status with one timestamp per receipt, and the author (`CONTACT`, `AGENT`, or `STAFF` with an optional staff user id). |
|
|
23
|
+
|
|
24
|
+
Host-specific links — a cart, a service mode, a customer record, the sale a
|
|
25
|
+
conversation led to — are NOT here. The host keeps them in its own tables,
|
|
26
|
+
keyed by the conversation id.
|
|
27
|
+
|
|
28
|
+
## The pipeline
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
POST /webhooks/messaging/:channel
|
|
32
|
+
├─ unknown channel ............................ 404
|
|
33
|
+
├─ signature over the RAW bytes fails ......... 401, nothing stored (fail closed)
|
|
34
|
+
├─ store the raw body (dedupe on its hash) .... 500 if the store fails, so the channel redelivers
|
|
35
|
+
└─ 200, and queue messaging.process-delivery
|
|
36
|
+
|
|
37
|
+
messaging.process-delivery (a job)
|
|
38
|
+
├─ parse the stored bytes through the channel's adapter
|
|
39
|
+
├─ per event, resolve the tenant: the event's account against the connections
|
|
40
|
+
│ unknown, revoked or in error ............. dropped (the edge already said 200)
|
|
41
|
+
│ unknown only, with hooks.onUnclaimedEvents handed to the host (see below)
|
|
42
|
+
├─ message → create or re-open the conversation, update lastInboundAt,
|
|
43
|
+
│ store the message (a known channel id is a no-op),
|
|
44
|
+
│ then the host's onInboundMessage({ conversation, message })
|
|
45
|
+
├─ status → stamp the outbound row's receipt once; the status only moves forward.
|
|
46
|
+
│ A receipt that finds no message yet (it raced the sender storing
|
|
47
|
+
│ the channel's id) settles the delivery FAILED: the sweep retries it
|
|
48
|
+
└─ opt-out → OPTED_OUT (a keyword message is stored; the hook is not called)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
The tenant is never taken from the URL: a channel like WhatsApp posts every
|
|
52
|
+
connected account's events to the one callback configured on the app.
|
|
53
|
+
|
|
54
|
+
**A number nobody connected.** A host whose OWN number lives on the same app
|
|
55
|
+
(a platform notification number: its confirmation replies, its opt-outs, its
|
|
56
|
+
delivery receipts) passes `hooks.onUnclaimedEvents(channel, events)`. It is
|
|
57
|
+
handed, once per processed delivery, the parsed events of every account no
|
|
58
|
+
connection row names: already signature-checked and persisted, and stored
|
|
59
|
+
nowhere here. A revoked or errored account is a tenant's and is never handed
|
|
60
|
+
over. A throw settles the delivery `FAILED` and the reconciliation sweep runs
|
|
61
|
+
it again, so the handler is idempotent on the provider's message id. Without
|
|
62
|
+
the hook those events are dropped, as before.
|
|
63
|
+
|
|
64
|
+
**Filter on your OWN account id.** The hook is handed every account the app
|
|
65
|
+
posts for that no connection names — not only the platform's number. A host
|
|
66
|
+
that wants its own number's events keeps `event.accountId === <its phone
|
|
67
|
+
number id>` and drops the rest; anything else would act on a stranger's
|
|
68
|
+
messages.
|
|
69
|
+
|
|
70
|
+
**Meta's `wa_id` is not always the stored number.** For many Brazilian mobiles
|
|
71
|
+
Meta reports the sender WITHOUT the 9th digit (`55 11 8765-4321` for
|
|
72
|
+
`+55 11 98765-4321`). A host matching a reply to a stored number (a consent
|
|
73
|
+
reply, `@12-apps/notifications`' `applyInbound`) normalises `from` first: for a
|
|
74
|
+
`55` number with a 2-digit area code and an 8-digit subscriber starting 6–9,
|
|
75
|
+
insert the `9` — or the reply misses the account that sent it.
|
|
76
|
+
|
|
77
|
+
**Opt-out.** On WhatsApp, a message that is exactly `PARAR`, `SAIR`, `STOP` or
|
|
78
|
+
`CANCELAR` — case- and accent-insensitive, ignoring punctuation and emoji
|
|
79
|
+
around it ("PARAR.", "Parar!") — opts the contact out, as does Meta's own
|
|
80
|
+
`user_preferences` stop signal. "parar de enviar" does not. A message the
|
|
81
|
+
contact SENDS after the opt-out re-opens the conversation, in `AGENT` unless
|
|
82
|
+
the host's `reopenState` hook says otherwise (it may not answer `OPTED_OUT`).
|
|
83
|
+
The comparison is on the message's own time (`optedOutAt`), never on when it
|
|
84
|
+
was processed: a message sent before the opt-out and processed after it (a
|
|
85
|
+
retried job, the reconciliation sweep) is stored but does not re-open the
|
|
86
|
+
conversation and does not reach the host's hook. Every state change is a
|
|
87
|
+
compare-and-set against what was read, so two workers, or a staff hand-off,
|
|
88
|
+
racing an opt-out (or a later stop signal) cannot undo it. No staff action can move a conversation out
|
|
89
|
+
of `OPTED_OUT`.
|
|
90
|
+
|
|
91
|
+
**Sending.** `engine.send` refuses (typed `MessagingSendError`, nothing
|
|
92
|
+
recorded) an `OPTED_OUT` conversation, a send the channel's policy refuses
|
|
93
|
+
(WhatsApp: free-form only within 24 hours of the contact's last message;
|
|
94
|
+
`WINDOW_CLOSED` at 24 h exactly and after), and a connection that is not
|
|
95
|
+
connected. Otherwise it records the outbound row `PENDING` BEFORE calling the
|
|
96
|
+
channel, then stores the channel's id (`ACCEPTED`), or marks the row `FAILED`
|
|
97
|
+
with the channel's error and throws `CHANNEL_FAILED`. Two limits of the channel
|
|
98
|
+
boundary, not of the package: an opt-out that lands while a send is already in
|
|
99
|
+
flight cannot recall it (the check runs before the call), and a `FAILED` row is
|
|
100
|
+
not proof the message was not delivered (a timeout, or an answer with no
|
|
101
|
+
message id, can follow a delivery Meta did make), so a host that retries a
|
|
102
|
+
`CHANNEL_FAILED` send may send twice. Templates (the only way to speak outside
|
|
103
|
+
the window) are a later story.
|
|
104
|
+
|
|
105
|
+
**Retention.** A conversation's text lives only while the conversation does:
|
|
106
|
+
12 hours (configurable) after its LAST message, every message's body, choices
|
|
107
|
+
and transcript are deleted. The conversation, its state and its summary stay.
|
|
108
|
+
The `messaging.retention` job finds due conversations with one indexed query
|
|
109
|
+
across every tenant, never a walk over tenants.
|
|
110
|
+
|
|
111
|
+
The raw webhook bodies (Meta's whole payload: the text, the phone number, the
|
|
112
|
+
profile name) go with it: the same sweep DELETES the inbox rows received before
|
|
113
|
+
the cutoff that are `PROCESSED`, and the `FAILED` ones that used up their
|
|
114
|
+
attempts, in batches through the `(state, received_at)` index. A row still
|
|
115
|
+
awaiting a retry keeps its bytes until it is processed or out of attempts —
|
|
116
|
+
minutes, not days. Dedupe survives, because it rests on the message row's
|
|
117
|
+
`(channel, external_id)`: a redelivery after the purge is a duplicate.
|
|
118
|
+
|
|
119
|
+
## The channel adapter
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
interface ChannelAdapter {
|
|
123
|
+
readonly kind: string; // "whatsapp"
|
|
124
|
+
handshake(query): { ok: true; challenge } | { ok: false } | null;
|
|
125
|
+
verify({ rawBody, header }): boolean; // fail closed
|
|
126
|
+
parse(rawBody): NormalizedEvent[]; // message | status | opt_out
|
|
127
|
+
send({ credential, accountId, to, content }): Promise<{ externalId }>;
|
|
128
|
+
readonly policy: SendPolicy; // when free-form sends are allowed
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`NormalizedEvent` carries the channel account the event belongs to
|
|
133
|
+
(`accountId`), so tenant resolution is the engine's and the same for every
|
|
134
|
+
channel. `OutboundContent` is `TEXT`, `BUTTONS` or `LIST`; an adapter maps it
|
|
135
|
+
to its wire. `serviceWindowPolicy(ms)` and `OPEN_SEND_POLICY` cover the two
|
|
136
|
+
policies known so far.
|
|
137
|
+
|
|
138
|
+
## Subpaths
|
|
139
|
+
|
|
140
|
+
| subpath | what |
|
|
141
|
+
|---|---|
|
|
142
|
+
| `@12-apps/messaging` | `createMessagingEngine`, the ports, the store port with `createPrismaMessagingStore` and `createMemoryMessagingStore`, the adapter interface, the errors, the types. |
|
|
143
|
+
| `@12-apps/messaging/whatsapp` | `createWhatsAppAdapter`, and standalone: `verifyMetaSignature`, `verifyMetaSubscription`, `parseWhatsAppPayload`, `parseWhatsAppStatuses`, `isOptOutText`, the Graph sender, and the Embedded Signup helpers `exchangeSignupCode`, `readSignupAccounts`, `subscribeAppToWaba`. |
|
|
144
|
+
| `@12-apps/messaging/server` | `createApiMessaging` (the webhook route pair, in `@12-apps/wiring`'s `WireRoute` shape) and `MESSAGING_JOBS`. |
|
|
145
|
+
| `@12-apps/messaging/manifest`, `/manifest/server` | The wiring manifests. |
|
|
146
|
+
|
|
147
|
+
The signature check and the receipt parser are exported on their own because a
|
|
148
|
+
host that sends WhatsApp messages some other way (a platform notification
|
|
149
|
+
number) needs exactly those two and nothing else.
|
|
150
|
+
|
|
151
|
+
## Tests
|
|
152
|
+
|
|
153
|
+
`src/**/__tests__`, vitest. The pipeline, the sender and the retention sweep
|
|
154
|
+
run over recorded WhatsApp Cloud payloads (`src/__tests__/fixtures.ts`). One
|
|
155
|
+
store contract runs over the memory store and over the Prisma store on PGlite
|
|
156
|
+
with the shipped migration (`store-contract.test.ts`), so the double cannot
|
|
157
|
+
drift from Postgres. The manifest suite runs the wiring producer assertions
|
|
158
|
+
and an adoption by a real wiring host.
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The connector's vocabulary: what every channel adapter normalizes into and
|
|
3
|
+
* what every store reads and writes. Machine words, never copy — a sentence a
|
|
4
|
+
* person reads is the host's.
|
|
5
|
+
*/
|
|
6
|
+
/** A channel's key: `whatsapp` today; `email`, `slack` when their adapters land. Lowercase, dash-separated. */
|
|
7
|
+
type ChannelKind = string;
|
|
8
|
+
/** Whether a connected account can be used. */
|
|
9
|
+
type ConnectionStatus = "CONNECTED" | "REVOKED" | "ERROR";
|
|
10
|
+
/**
|
|
11
|
+
* Who answers a conversation:
|
|
12
|
+
* - `AGENT` — the host's automated agent (the `onInboundMessage` hook);
|
|
13
|
+
* - `HUMAN` — a person on the tenant's staff took it over;
|
|
14
|
+
* - `CLOSED` — nobody, until the contact writes again;
|
|
15
|
+
* - `OPTED_OUT` — the contact asked to stop. Nothing is sent until they write again.
|
|
16
|
+
*/
|
|
17
|
+
type ConversationState = "AGENT" | "HUMAN" | "CLOSED" | "OPTED_OUT";
|
|
18
|
+
type MessageDirection = "INBOUND" | "OUTBOUND";
|
|
19
|
+
/** What a message carries. Templates join when the template story lands. */
|
|
20
|
+
type MessageKind = "TEXT" | "INTERACTIVE" | "AUDIO" | "OTHER";
|
|
21
|
+
/**
|
|
22
|
+
* Where a message stands:
|
|
23
|
+
* - `RECEIVED` — an inbound message;
|
|
24
|
+
* - `PENDING` — an outbound row recorded, the channel not yet called;
|
|
25
|
+
* - `ACCEPTED` — the channel took it and returned its id;
|
|
26
|
+
* - `SENT` / `DELIVERED` / `READ` — the channel's own receipts;
|
|
27
|
+
* - `FAILED` — the call failed, or the channel reported a failure.
|
|
28
|
+
*/
|
|
29
|
+
type DeliveryStatus = "RECEIVED" | "PENDING" | "ACCEPTED" | "SENT" | "DELIVERED" | "READ" | "FAILED";
|
|
30
|
+
/** A receipt a channel reports for an outbound message. */
|
|
31
|
+
type ReceiptStatus = "SENT" | "DELIVERED" | "READ" | "FAILED";
|
|
32
|
+
/**
|
|
33
|
+
* Who wrote a message. `CONTACT` is the person on the other end of the
|
|
34
|
+
* channel — a buyer, a supplier, a support requester: the host decides what
|
|
35
|
+
* that person is to it.
|
|
36
|
+
*/
|
|
37
|
+
type AuthorKind = "CONTACT" | "AGENT" | "STAFF";
|
|
38
|
+
/** The structured summary a host keeps beside a conversation. JSON, never free text by convention. */
|
|
39
|
+
type ConversationSummary = {
|
|
40
|
+
readonly [key: string]: unknown;
|
|
41
|
+
};
|
|
42
|
+
/** What an inbound message carried, normalized across channels. */
|
|
43
|
+
type InboundContent = {
|
|
44
|
+
kind: "TEXT";
|
|
45
|
+
text: string;
|
|
46
|
+
}
|
|
47
|
+
/** A tap on a button or a list row the conversation offered. */
|
|
48
|
+
| {
|
|
49
|
+
kind: "INTERACTIVE";
|
|
50
|
+
replyId: string;
|
|
51
|
+
title: string;
|
|
52
|
+
}
|
|
53
|
+
/** A voice note or an audio file: only the channel's media id, never the bytes. */
|
|
54
|
+
| {
|
|
55
|
+
kind: "AUDIO";
|
|
56
|
+
mediaId: string;
|
|
57
|
+
mimeType: string | null;
|
|
58
|
+
}
|
|
59
|
+
/** Anything else (an image, a location, a sticker): kept as its channel type, not read. */
|
|
60
|
+
| {
|
|
61
|
+
kind: "OTHER";
|
|
62
|
+
channelType: string;
|
|
63
|
+
};
|
|
64
|
+
/** One message a contact sent. */
|
|
65
|
+
interface InboundMessageEvent {
|
|
66
|
+
type: "message";
|
|
67
|
+
/** The channel account it was sent TO (WhatsApp's phone_number_id). */
|
|
68
|
+
accountId: string;
|
|
69
|
+
/** The sender's address on the channel. */
|
|
70
|
+
contactId: string;
|
|
71
|
+
/** The name the channel shows for the sender, when it sends one. */
|
|
72
|
+
contactName: string | null;
|
|
73
|
+
/** The channel's id for the message. */
|
|
74
|
+
externalId: string;
|
|
75
|
+
sentAt: Date;
|
|
76
|
+
content: InboundContent;
|
|
77
|
+
/** The text asked to stop (an opt-out keyword). The message is still stored. */
|
|
78
|
+
optOut: boolean;
|
|
79
|
+
}
|
|
80
|
+
/** A receipt for a message the tenant sent. */
|
|
81
|
+
interface StatusEvent {
|
|
82
|
+
type: "status";
|
|
83
|
+
accountId: string;
|
|
84
|
+
/** The channel's id of the outbound message. */
|
|
85
|
+
externalId: string;
|
|
86
|
+
status: ReceiptStatus;
|
|
87
|
+
at: Date;
|
|
88
|
+
/** The recipient's address, when the channel says. */
|
|
89
|
+
contactId: string | null;
|
|
90
|
+
/** The channel's error code and title, for a failure. */
|
|
91
|
+
error: string | null;
|
|
92
|
+
}
|
|
93
|
+
/** The channel's own signal that a contact stopped messages (not a keyword in a text). */
|
|
94
|
+
interface OptOutEvent {
|
|
95
|
+
type: "opt_out";
|
|
96
|
+
accountId: string;
|
|
97
|
+
contactId: string;
|
|
98
|
+
at: Date;
|
|
99
|
+
}
|
|
100
|
+
type NormalizedEvent = InboundMessageEvent | StatusEvent | OptOutEvent;
|
|
101
|
+
/** A message the tenant sends, normalized across channels. */
|
|
102
|
+
type OutboundContent = {
|
|
103
|
+
kind: "TEXT";
|
|
104
|
+
text: string;
|
|
105
|
+
}
|
|
106
|
+
/** Up to the channel's number of reply buttons under a text. */
|
|
107
|
+
| {
|
|
108
|
+
kind: "BUTTONS";
|
|
109
|
+
text: string;
|
|
110
|
+
buttons: readonly {
|
|
111
|
+
id: string;
|
|
112
|
+
title: string;
|
|
113
|
+
}[];
|
|
114
|
+
}
|
|
115
|
+
/** A text with one button that opens a list of rows in sections. */
|
|
116
|
+
| {
|
|
117
|
+
kind: "LIST";
|
|
118
|
+
text: string;
|
|
119
|
+
/** The words on the button that opens the list — the host's copy. */
|
|
120
|
+
buttonLabel: string;
|
|
121
|
+
sections: readonly {
|
|
122
|
+
title?: string;
|
|
123
|
+
rows: readonly {
|
|
124
|
+
id: string;
|
|
125
|
+
title: string;
|
|
126
|
+
description?: string;
|
|
127
|
+
}[];
|
|
128
|
+
}[];
|
|
129
|
+
};
|
|
130
|
+
/** A connection as the package returns it: never the credential. */
|
|
131
|
+
interface ConnectionView {
|
|
132
|
+
id: string;
|
|
133
|
+
tenantId: string;
|
|
134
|
+
channel: ChannelKind;
|
|
135
|
+
externalAccountId: string;
|
|
136
|
+
externalParentId: string | null;
|
|
137
|
+
displayAddress: string;
|
|
138
|
+
status: ConnectionStatus;
|
|
139
|
+
statusReason: string | null;
|
|
140
|
+
connectedAt: Date;
|
|
141
|
+
revokedAt: Date | null;
|
|
142
|
+
}
|
|
143
|
+
interface ConversationView {
|
|
144
|
+
id: string;
|
|
145
|
+
tenantId: string;
|
|
146
|
+
channel: ChannelKind;
|
|
147
|
+
contactId: string;
|
|
148
|
+
contactName: string | null;
|
|
149
|
+
connectionId: string;
|
|
150
|
+
state: ConversationState;
|
|
151
|
+
lastInboundAt: Date | null;
|
|
152
|
+
lastMessageAt: Date | null;
|
|
153
|
+
/** When the contact last opted out (the message's own time, not the processing time). Kept after a re-open. */
|
|
154
|
+
optedOutAt: Date | null;
|
|
155
|
+
hasText: boolean;
|
|
156
|
+
summary: ConversationSummary | null;
|
|
157
|
+
summaryUpdatedAt: Date | null;
|
|
158
|
+
createdAt: Date;
|
|
159
|
+
}
|
|
160
|
+
interface MessageView {
|
|
161
|
+
id: string;
|
|
162
|
+
conversationId: string;
|
|
163
|
+
tenantId: string;
|
|
164
|
+
channel: ChannelKind;
|
|
165
|
+
direction: MessageDirection;
|
|
166
|
+
kind: MessageKind;
|
|
167
|
+
/** The text, the tapped choice's title, or an outbound prompt. Null once retention ran. */
|
|
168
|
+
body: string | null;
|
|
169
|
+
/** An outbound interactive message's choices, as JSON text. Null once retention ran. */
|
|
170
|
+
options: string | null;
|
|
171
|
+
/** An audio message's transcript, written by the host. Null once retention ran. */
|
|
172
|
+
transcript: string | null;
|
|
173
|
+
/** An attachment's (or a tapped choice's) id on the channel. */
|
|
174
|
+
attachmentRef: string | null;
|
|
175
|
+
externalId: string | null;
|
|
176
|
+
deliveryStatus: DeliveryStatus;
|
|
177
|
+
authorKind: AuthorKind;
|
|
178
|
+
staffUserId: string | null;
|
|
179
|
+
error: string | null;
|
|
180
|
+
createdAt: Date;
|
|
181
|
+
sentAt: Date | null;
|
|
182
|
+
deliveredAt: Date | null;
|
|
183
|
+
readAt: Date | null;
|
|
184
|
+
failedAt: Date | null;
|
|
185
|
+
}
|
|
186
|
+
/** The inbox's processing state. */
|
|
187
|
+
type DeliveryState = "PENDING" | "PROCESSED" | "FAILED";
|
|
188
|
+
interface InboxDeliveryView {
|
|
189
|
+
id: string;
|
|
190
|
+
channel: ChannelKind;
|
|
191
|
+
rawBody: string;
|
|
192
|
+
state: DeliveryState;
|
|
193
|
+
attempts: number;
|
|
194
|
+
error: string | null;
|
|
195
|
+
receivedAt: Date;
|
|
196
|
+
processedAt: Date | null;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* THE CHANNEL ADAPTER: everything the engine needs to know about one
|
|
201
|
+
* messaging channel, and nothing the engine decides.
|
|
202
|
+
*
|
|
203
|
+
* The engine owns the mechanism — the inbox and its dedupe, the tenant
|
|
204
|
+
* resolution, the conversation and its state, the outbound bookkeeping, the
|
|
205
|
+
* retention. An adapter owns the channel's wire: how a delivery proves where
|
|
206
|
+
* it came from, what its body means, how a message goes out, and when the
|
|
207
|
+
* channel lets a tenant speak first. WhatsApp Cloud is the first adapter
|
|
208
|
+
* (`@12-apps/messaging/whatsapp`); e-mail or a chat workspace join the same
|
|
209
|
+
* way, as one more object of this shape.
|
|
210
|
+
*/
|
|
211
|
+
interface ChannelAdapter {
|
|
212
|
+
/** The channel's key, stored on every row: `whatsapp`. Lowercase, dash-separated. */
|
|
213
|
+
readonly kind: ChannelKind;
|
|
214
|
+
/**
|
|
215
|
+
* Answer the channel's subscription handshake (a `GET` with a challenge),
|
|
216
|
+
* or null for a channel that has none. `ok: false` is a refusal (403).
|
|
217
|
+
*/
|
|
218
|
+
handshake(query: Readonly<Record<string, string | undefined>>): HandshakeAnswer | null;
|
|
219
|
+
/**
|
|
220
|
+
* Is this delivery really from the channel? Computed over the RAW body
|
|
221
|
+
* bytes, exactly as received. MUST fail closed: a missing secret, a missing
|
|
222
|
+
* header or a malformed one is `false`, never an exception and never `true`.
|
|
223
|
+
*/
|
|
224
|
+
verify(delivery: {
|
|
225
|
+
rawBody: Uint8Array;
|
|
226
|
+
header(name: string): string | null;
|
|
227
|
+
}): boolean;
|
|
228
|
+
/**
|
|
229
|
+
* Turn a raw body into normalized events, in the order the channel listed
|
|
230
|
+
* them. A body the adapter does not recognize yields `[]`; a body that is not
|
|
231
|
+
* even JSON throws (the inbox records the failure).
|
|
232
|
+
*/
|
|
233
|
+
parse(rawBody: string): NormalizedEvent[];
|
|
234
|
+
/**
|
|
235
|
+
* Send one message from a connected account and report the channel's id
|
|
236
|
+
* for it. Throws {@link ChannelSendFailure} when the channel refuses.
|
|
237
|
+
* `credential` is the OPENED credential: an adapter never logs it, never
|
|
238
|
+
* puts it in an error, never returns it.
|
|
239
|
+
*/
|
|
240
|
+
send(input: ChannelSendInput): Promise<{
|
|
241
|
+
externalId: string;
|
|
242
|
+
}>;
|
|
243
|
+
/** When this channel lets the tenant send free-form messages. */
|
|
244
|
+
readonly policy: SendPolicy;
|
|
245
|
+
}
|
|
246
|
+
type HandshakeAnswer = {
|
|
247
|
+
ok: true;
|
|
248
|
+
challenge: string;
|
|
249
|
+
} | {
|
|
250
|
+
ok: false;
|
|
251
|
+
};
|
|
252
|
+
interface ChannelSendInput {
|
|
253
|
+
/** The opened credential of the connection sending it. */
|
|
254
|
+
credential: string;
|
|
255
|
+
/** The connection's account on the channel (WhatsApp's phone_number_id). */
|
|
256
|
+
accountId: string;
|
|
257
|
+
/** The recipient's address. */
|
|
258
|
+
to: string;
|
|
259
|
+
content: OutboundContent;
|
|
260
|
+
}
|
|
261
|
+
/** A channel refused or failed a send. `code` is the channel's own, as text. */
|
|
262
|
+
declare class ChannelSendFailure extends Error {
|
|
263
|
+
readonly code: string;
|
|
264
|
+
constructor(code: string, message: string);
|
|
265
|
+
}
|
|
266
|
+
/** What a send policy is asked. */
|
|
267
|
+
interface SendPolicyContext {
|
|
268
|
+
/** When the contact last wrote; null if never. */
|
|
269
|
+
lastInboundAt: Date | null;
|
|
270
|
+
now: Date;
|
|
271
|
+
}
|
|
272
|
+
type SendPolicyVerdict = {
|
|
273
|
+
allowed: true;
|
|
274
|
+
} | {
|
|
275
|
+
allowed: false;
|
|
276
|
+
reason: "WINDOW_CLOSED";
|
|
277
|
+
};
|
|
278
|
+
/** A channel's rule for free-form sends. */
|
|
279
|
+
interface SendPolicy {
|
|
280
|
+
check(context: SendPolicyContext): SendPolicyVerdict;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Is a service window still open? Open while LESS than `windowMs` has passed
|
|
284
|
+
* since the contact's last message: at exactly the window's length it is
|
|
285
|
+
* closed. Never open for a contact who never wrote.
|
|
286
|
+
*/
|
|
287
|
+
declare function isWindowOpen(lastInboundAt: Date | null, now: Date, windowMs: number): boolean;
|
|
288
|
+
/** A policy that allows free-form sends only inside a window after the contact's last message. */
|
|
289
|
+
declare function serviceWindowPolicy(windowMs: number): SendPolicy;
|
|
290
|
+
/** A policy for a channel with no window (e-mail): every send is allowed. */
|
|
291
|
+
declare const OPEN_SEND_POLICY: SendPolicy;
|
|
292
|
+
|
|
293
|
+
export { type AuthorKind as A, type ConversationView as C, type DeliveryState as D, type HandshakeAnswer as H, type InboxDeliveryView as I, type MessageView as M, type NormalizedEvent as N, OPEN_SEND_POLICY as O, type ReceiptStatus as R, type SendPolicy as S, type ChannelAdapter as a, type ChannelKind as b, ChannelSendFailure as c, type ChannelSendInput as d, type ConnectionStatus as e, type ConnectionView as f, type ConversationState as g, type ConversationSummary as h, type DeliveryStatus as i, type InboundContent as j, type InboundMessageEvent as k, type MessageDirection as l, type MessageKind as m, type OptOutEvent as n, type OutboundContent as o, type SendPolicyContext as p, type SendPolicyVerdict as q, type StatusEvent as r, isWindowOpen as s, serviceWindowPolicy as t };
|