@12-apps/messaging 0.0.0-stage → 1.0.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 +133 -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-B5EPo66m.d.ts +414 -0
- package/dist/index.d.ts +97 -0
- package/dist/index.js +988 -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 +117 -0
- package/src/core/memory-store.ts +273 -0
- package/src/core/ports.ts +112 -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
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
import { g as ConversationState, h as ConversationSummary, f as ConnectionView, i as DeliveryStatus, b as ChannelKind, I as InboxDeliveryView, e as ConnectionStatus, C as ConversationView, M as MessageView, l as MessageDirection, m as MessageKind, A as AuthorKind, R as ReceiptStatus, a as ChannelAdapter, o as OutboundContent } from './channel-Cs_vLGl_.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* THE STORE PORT: every read and write the engine makes, as named operations.
|
|
5
|
+
*
|
|
6
|
+
* The engine never builds a query. Two implementations ship:
|
|
7
|
+
* `createPrismaMessagingStore` over the Prisma delegates generated from the
|
|
8
|
+
* shipped partial (what a host mounts), and `createMemoryMessagingStore` (what
|
|
9
|
+
* a test mounts). The same contract suite runs over both — the Prisma one on
|
|
10
|
+
* real Postgres with the shipped migration — so the two cannot drift.
|
|
11
|
+
*
|
|
12
|
+
* Every operation is tenant-scoped where a tenant is known, and every unique
|
|
13
|
+
* key the migration enforces is enforced by both implementations, with the
|
|
14
|
+
* race answered the same way (the existing row wins).
|
|
15
|
+
*/
|
|
16
|
+
interface MessagingStore {
|
|
17
|
+
/** Store one raw delivery, deduped on `(channel, bodyHash)`. `fresh: false` for a redelivery. */
|
|
18
|
+
recordDelivery(input: {
|
|
19
|
+
channel: ChannelKind;
|
|
20
|
+
bodyHash: string;
|
|
21
|
+
rawBody: string;
|
|
22
|
+
receivedAt: Date;
|
|
23
|
+
}): Promise<{
|
|
24
|
+
id: string;
|
|
25
|
+
fresh: boolean;
|
|
26
|
+
}>;
|
|
27
|
+
getDelivery(id: string): Promise<InboxDeliveryView | null>;
|
|
28
|
+
/** Close a delivery out, counting the attempt. */
|
|
29
|
+
settleDelivery(id: string, outcome: {
|
|
30
|
+
state: "PROCESSED" | "FAILED";
|
|
31
|
+
error: string | null;
|
|
32
|
+
at: Date;
|
|
33
|
+
}): Promise<void>;
|
|
34
|
+
/** Deliveries not yet processed, received before `receivedBefore`, under the attempt bound, oldest first. */
|
|
35
|
+
listRetryableDeliveries(input: {
|
|
36
|
+
receivedBefore: Date;
|
|
37
|
+
maxAttempts: number;
|
|
38
|
+
take: number;
|
|
39
|
+
}): Promise<InboxDeliveryView[]>;
|
|
40
|
+
findConnectionByAccount(channel: ChannelKind, externalAccountId: string): Promise<StoredConnection | null>;
|
|
41
|
+
getConnection(tenantId: string, id: string): Promise<StoredConnection | null>;
|
|
42
|
+
listConnections(tenantId: string): Promise<ConnectionView[]>;
|
|
43
|
+
/**
|
|
44
|
+
* Insert, or overwrite the row keyed by `(channel, externalAccountId)` — but
|
|
45
|
+
* only the same tenant's, or one that is REVOKED: the write itself is
|
|
46
|
+
* conditional, so two connects racing for one account cannot both win.
|
|
47
|
+
* `null` when the account is held by another tenant (the engine answers
|
|
48
|
+
* `ACCOUNT_TAKEN`).
|
|
49
|
+
*/
|
|
50
|
+
saveConnection(input: NewConnection): Promise<ConnectionView | null>;
|
|
51
|
+
setConnectionStatus(tenantId: string, id: string, patch: {
|
|
52
|
+
status: ConnectionStatus;
|
|
53
|
+
statusReason: string | null;
|
|
54
|
+
revokedAt: Date | null;
|
|
55
|
+
credentialSealed?: null;
|
|
56
|
+
}): Promise<boolean>;
|
|
57
|
+
findConversation(tenantId: string, channel: ChannelKind, contactId: string): Promise<ConversationView | null>;
|
|
58
|
+
getConversation(tenantId: string, id: string): Promise<ConversationView | null>;
|
|
59
|
+
/** Create one; on a lost race for `(tenant, channel, contact)` the existing row is returned. */
|
|
60
|
+
createConversation(input: NewConversation): Promise<ConversationView>;
|
|
61
|
+
/**
|
|
62
|
+
* Apply `patch` to the tenant's conversation. With a `guard` it is a
|
|
63
|
+
* COMPARE-AND-SET: the write happens only while the row still matches every
|
|
64
|
+
* guarded field (one `updateMany`), and `null` comes back when it does not —
|
|
65
|
+
* the caller re-reads and decides again. Without a guard, `null` only means
|
|
66
|
+
* "no such conversation".
|
|
67
|
+
*/
|
|
68
|
+
updateConversation(tenantId: string, id: string, patch: ConversationPatch, guard?: ConversationGuard): Promise<ConversationView | null>;
|
|
69
|
+
findMessageByExternalId(channel: ChannelKind, externalId: string): Promise<MessageView | null>;
|
|
70
|
+
/** Insert one; a duplicate `(channel, externalId)` is `created: false` and the existing row. */
|
|
71
|
+
insertMessage(input: NewMessage): Promise<{
|
|
72
|
+
created: boolean;
|
|
73
|
+
message: MessageView;
|
|
74
|
+
}>;
|
|
75
|
+
updateMessage(tenantId: string, id: string, patch: MessagePatch): Promise<MessageView | null>;
|
|
76
|
+
listMessages(tenantId: string, conversationId: string): Promise<MessageView[]>;
|
|
77
|
+
/**
|
|
78
|
+
* Stamp a receipt on the tenant's outbound message: the receipt's timestamp
|
|
79
|
+
* column is written only while still null (so `(externalId, status)` is
|
|
80
|
+
* deduped by the row itself), and the delivery status only moves forward.
|
|
81
|
+
* False when no outbound message of that tenant has that id.
|
|
82
|
+
*/
|
|
83
|
+
applyReceipt(input: {
|
|
84
|
+
tenantId: string;
|
|
85
|
+
channel: ChannelKind;
|
|
86
|
+
externalId: string;
|
|
87
|
+
status: ReceiptStatus;
|
|
88
|
+
at: Date;
|
|
89
|
+
error: string | null;
|
|
90
|
+
}): Promise<boolean>;
|
|
91
|
+
/**
|
|
92
|
+
* Delete raw inbox rows past `cutoff`: the PROCESSED ones, and the FAILED
|
|
93
|
+
* ones that reached `maxAttempts` (nothing will retry them). One batch of up
|
|
94
|
+
* to `take` per state, found through the `(state, received_at)` index.
|
|
95
|
+
* Returns how many were deleted. Dedupe survives: a redelivered message
|
|
96
|
+
* still meets `(channel, external_id)` on its message row.
|
|
97
|
+
*/
|
|
98
|
+
purgeExpiredDeliveries(input: {
|
|
99
|
+
cutoff: Date;
|
|
100
|
+
maxAttempts: number;
|
|
101
|
+
take: number;
|
|
102
|
+
}): Promise<number>;
|
|
103
|
+
/**
|
|
104
|
+
* Delete the text of conversations whose last message is older than
|
|
105
|
+
* `cutoff`: ONE indexed query finds up to `take` of them across every tenant
|
|
106
|
+
* (`has_text`, `last_message_at`), then their messages created at or before
|
|
107
|
+
* the cutoff lose `body`, `options` and `transcript`. Conversation rows,
|
|
108
|
+
* states and summaries stay.
|
|
109
|
+
*/
|
|
110
|
+
purgeExpiredText(input: {
|
|
111
|
+
cutoff: Date;
|
|
112
|
+
take: number;
|
|
113
|
+
}): Promise<{
|
|
114
|
+
conversations: number;
|
|
115
|
+
messages: number;
|
|
116
|
+
}>;
|
|
117
|
+
}
|
|
118
|
+
/** A connection with its sealed credential: only the engine sees this shape. */
|
|
119
|
+
interface StoredConnection extends ConnectionView {
|
|
120
|
+
/** Null once the connection was revoked: disconnecting removes the token. */
|
|
121
|
+
credentialSealed: string | null;
|
|
122
|
+
}
|
|
123
|
+
interface NewConnection {
|
|
124
|
+
tenantId: string;
|
|
125
|
+
channel: ChannelKind;
|
|
126
|
+
externalAccountId: string;
|
|
127
|
+
externalParentId: string | null;
|
|
128
|
+
displayAddress: string;
|
|
129
|
+
credentialSealed: string;
|
|
130
|
+
connectedAt: Date;
|
|
131
|
+
}
|
|
132
|
+
interface NewConversation {
|
|
133
|
+
tenantId: string;
|
|
134
|
+
channel: ChannelKind;
|
|
135
|
+
contactId: string;
|
|
136
|
+
contactName: string | null;
|
|
137
|
+
connectionId: string;
|
|
138
|
+
state: ConversationState;
|
|
139
|
+
lastInboundAt: Date | null;
|
|
140
|
+
lastMessageAt: Date | null;
|
|
141
|
+
optedOutAt?: Date | null;
|
|
142
|
+
hasText: boolean;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* What a compare-and-set update requires of the row it writes: every field
|
|
146
|
+
* given must equal the row's current value (`null` matches a null column),
|
|
147
|
+
* and `stateNot` that the state differs.
|
|
148
|
+
*/
|
|
149
|
+
interface ConversationGuard {
|
|
150
|
+
state?: ConversationState;
|
|
151
|
+
stateNot?: ConversationState;
|
|
152
|
+
lastInboundAt?: Date | null;
|
|
153
|
+
lastMessageAt?: Date | null;
|
|
154
|
+
optedOutAt?: Date | null;
|
|
155
|
+
}
|
|
156
|
+
interface ConversationPatch {
|
|
157
|
+
contactName?: string | null;
|
|
158
|
+
connectionId?: string;
|
|
159
|
+
state?: ConversationState;
|
|
160
|
+
lastInboundAt?: Date | null;
|
|
161
|
+
lastMessageAt?: Date | null;
|
|
162
|
+
optedOutAt?: Date | null;
|
|
163
|
+
hasText?: boolean;
|
|
164
|
+
summary?: ConversationSummary;
|
|
165
|
+
summaryUpdatedAt?: Date;
|
|
166
|
+
}
|
|
167
|
+
interface NewMessage {
|
|
168
|
+
conversationId: string;
|
|
169
|
+
tenantId: string;
|
|
170
|
+
channel: ChannelKind;
|
|
171
|
+
direction: MessageDirection;
|
|
172
|
+
kind: MessageKind;
|
|
173
|
+
body: string | null;
|
|
174
|
+
options: string | null;
|
|
175
|
+
attachmentRef: string | null;
|
|
176
|
+
externalId: string | null;
|
|
177
|
+
deliveryStatus: DeliveryStatus;
|
|
178
|
+
authorKind: AuthorKind;
|
|
179
|
+
staffUserId: string | null;
|
|
180
|
+
createdAt: Date;
|
|
181
|
+
}
|
|
182
|
+
interface MessagePatch {
|
|
183
|
+
externalId?: string;
|
|
184
|
+
deliveryStatus?: DeliveryStatus;
|
|
185
|
+
error?: string | null;
|
|
186
|
+
transcript?: string;
|
|
187
|
+
failedAt?: Date;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* What the engine needs FROM its host. The mechanism (the inbox, the tenant
|
|
192
|
+
* resolution, the conversation states, the outbound bookkeeping, the
|
|
193
|
+
* retention) is the engine's and appears nowhere here.
|
|
194
|
+
*/
|
|
195
|
+
/**
|
|
196
|
+
* Sealing and opening a stored credential. The KEY is the host's: the package
|
|
197
|
+
* never sees it. `open` THROWS on a ciphertext that will not open — a row
|
|
198
|
+
* sealed under a rotated key must fail a send loudly, never read as "no
|
|
199
|
+
* credential".
|
|
200
|
+
*/
|
|
201
|
+
interface MessagingSecretsPort {
|
|
202
|
+
seal(plaintext: string): string | Promise<string>;
|
|
203
|
+
open(sealed: string): string | Promise<string>;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Defer one job run by wire name — the shape of `@12-apps/wiring/ports`'
|
|
207
|
+
* `JobsEnqueuePort`. Never throws. The engine enqueues only its own
|
|
208
|
+
* namespaced job (`messaging.process-delivery`).
|
|
209
|
+
*/
|
|
210
|
+
interface MessagingEnqueuePort {
|
|
211
|
+
enqueue(name: string, payload: unknown, options?: {
|
|
212
|
+
dedupeKey?: string;
|
|
213
|
+
}): Promise<{
|
|
214
|
+
enqueued: boolean;
|
|
215
|
+
reason?: string;
|
|
216
|
+
}>;
|
|
217
|
+
}
|
|
218
|
+
/** The clock, so a test or a replay decides what "now" is. */
|
|
219
|
+
interface MessagingClockPort {
|
|
220
|
+
now(): Date;
|
|
221
|
+
}
|
|
222
|
+
/** Where the engine says what it did — the wiring `LoggerPort` shape. Never handed a credential. */
|
|
223
|
+
interface MessagingLogger {
|
|
224
|
+
info(message: string, ...meta: unknown[]): void;
|
|
225
|
+
warn(message: string, ...meta: unknown[]): void;
|
|
226
|
+
error(message: string, ...meta: unknown[]): void;
|
|
227
|
+
}
|
|
228
|
+
/** What `onInboundMessage` is told: the conversation as it now stands, and the stored message. */
|
|
229
|
+
interface InboundMessageNotice {
|
|
230
|
+
conversation: ConversationView;
|
|
231
|
+
message: MessageView;
|
|
232
|
+
}
|
|
233
|
+
/** What a re-opened conversation may become. */
|
|
234
|
+
type ReopenState = Exclude<ConversationState, "OPTED_OUT">;
|
|
235
|
+
/** The host's answers to what only it knows about a conversation. All optional. */
|
|
236
|
+
interface MessagingHooks {
|
|
237
|
+
/**
|
|
238
|
+
* A contact's message was stored. The host's agent (or a person's inbox)
|
|
239
|
+
* picks it up here. Called once per stored message, never for a redelivery,
|
|
240
|
+
* and NOT for a message that opted the contact out — nothing may be said to
|
|
241
|
+
* them. Keep it short (enqueue the host's own job): a throw is logged, never
|
|
242
|
+
* retried, because the message is already stored. Default: nothing.
|
|
243
|
+
*/
|
|
244
|
+
onInboundMessage?(notice: InboundMessageNotice): Promise<void> | void;
|
|
245
|
+
/**
|
|
246
|
+
* The state a CLOSED or OPTED_OUT conversation re-opens into when its
|
|
247
|
+
* contact writes again. Default: `AGENT`. A host never returns `OPTED_OUT`
|
|
248
|
+
* (only the contact's own words put a conversation there): the type refuses
|
|
249
|
+
* it, and an answer that slips through anyway is read as `AGENT`.
|
|
250
|
+
*/
|
|
251
|
+
reopenState?(conversation: ConversationView): ReopenState | Promise<ReopenState>;
|
|
252
|
+
}
|
|
253
|
+
/** Everything a host hands `createMessagingEngine`. */
|
|
254
|
+
interface MessagingEngineConfig {
|
|
255
|
+
store: MessagingStore;
|
|
256
|
+
/** One per channel — `createWhatsAppAdapter(...)` and, later, its siblings. */
|
|
257
|
+
adapters: readonly ChannelAdapter[];
|
|
258
|
+
secrets: MessagingSecretsPort;
|
|
259
|
+
enqueue: MessagingEnqueuePort;
|
|
260
|
+
clock: MessagingClockPort;
|
|
261
|
+
logger: MessagingLogger;
|
|
262
|
+
hooks?: MessagingHooks;
|
|
263
|
+
/**
|
|
264
|
+
* How long a conversation's text is kept after its LAST message, in
|
|
265
|
+
* milliseconds. Default 12 hours: the conversation lives in the contact's
|
|
266
|
+
* own app, not with the tenant.
|
|
267
|
+
*/
|
|
268
|
+
retentionMs?: number;
|
|
269
|
+
/** How many conversations one retention pass purges. Default 500. */
|
|
270
|
+
retentionBatchSize?: number;
|
|
271
|
+
/** How many stored deliveries one reconciliation pass re-runs. Default 50. */
|
|
272
|
+
reconcileBatchSize?: number;
|
|
273
|
+
/** How many times a stored delivery may be processed before it is left for a person. Default 5. */
|
|
274
|
+
maxDeliveryAttempts?: number;
|
|
275
|
+
/**
|
|
276
|
+
* How old an unprocessed delivery must be before the reconciliation sweep
|
|
277
|
+
* re-runs it, so the sweep never races the job the webhook just queued.
|
|
278
|
+
* Default 2 minutes.
|
|
279
|
+
*/
|
|
280
|
+
reconcileAfterMs?: number;
|
|
281
|
+
}
|
|
282
|
+
/** The defaults the config's optional numbers take. */
|
|
283
|
+
declare const MESSAGING_DEFAULTS: {
|
|
284
|
+
readonly retentionMs: number;
|
|
285
|
+
readonly retentionBatchSize: 500;
|
|
286
|
+
readonly reconcileBatchSize: 50;
|
|
287
|
+
readonly maxDeliveryAttempts: 5;
|
|
288
|
+
readonly reconcileAfterMs: number;
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* One normalized event, applied. The tenant is resolved HERE, from the
|
|
293
|
+
* event's channel account against the connections — never from the URL, which
|
|
294
|
+
* for a channel like WhatsApp is one callback shared by every tenant. An
|
|
295
|
+
* account nobody connected, or one revoked or in error, resolves to nobody:
|
|
296
|
+
* the event is dropped (the edge already answered 200, so the channel stops
|
|
297
|
+
* redelivering) and a tenant can never receive another tenant's traffic.
|
|
298
|
+
*/
|
|
299
|
+
type EventOutcome = {
|
|
300
|
+
kind: "dropped";
|
|
301
|
+
reason: "unknown-account" | "not-connected";
|
|
302
|
+
} | {
|
|
303
|
+
kind: "duplicate";
|
|
304
|
+
} | {
|
|
305
|
+
kind: "message";
|
|
306
|
+
conversationId: string;
|
|
307
|
+
messageId: string;
|
|
308
|
+
} | {
|
|
309
|
+
kind: "opted-out";
|
|
310
|
+
conversationId: string;
|
|
311
|
+
} | {
|
|
312
|
+
kind: "receipt";
|
|
313
|
+
applied: boolean;
|
|
314
|
+
};
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* The durable inbox: persist the raw delivery, ACK, then process in a job.
|
|
318
|
+
*
|
|
319
|
+
* Nothing is resolved before the row is written — not the tenant, not even
|
|
320
|
+
* whether the body parses — because the one thing a webhook must never do is
|
|
321
|
+
* lose a delivery to a bug in the code that reads it. The raw bytes are kept
|
|
322
|
+
* so a mapping bug can be replayed once fixed — until the retention sweep
|
|
323
|
+
* deletes them, with the conversation's text, past the retention window.
|
|
324
|
+
*/
|
|
325
|
+
/** The job the engine enqueues per fresh delivery, by wire name. */
|
|
326
|
+
declare const PROCESS_DELIVERY_JOB = "messaging.process-delivery";
|
|
327
|
+
/** What processing one stored delivery did. */
|
|
328
|
+
type DeliveryOutcome = {
|
|
329
|
+
kind: "missing";
|
|
330
|
+
} | {
|
|
331
|
+
kind: "already-processed";
|
|
332
|
+
} | {
|
|
333
|
+
kind: "processed";
|
|
334
|
+
events: EventOutcome[];
|
|
335
|
+
} | {
|
|
336
|
+
kind: "unreadable";
|
|
337
|
+
reason: string;
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
interface ConnectInput {
|
|
341
|
+
tenantId: string;
|
|
342
|
+
channel: string;
|
|
343
|
+
/** The channel's id for the account (WhatsApp's phone_number_id). */
|
|
344
|
+
externalAccountId: string;
|
|
345
|
+
/** The channel's parent account (WhatsApp's WABA id), when it has one. */
|
|
346
|
+
externalParentId?: string | null;
|
|
347
|
+
displayAddress: string;
|
|
348
|
+
/** The credential in clear (a business token). Sealed here; never stored, returned or logged in clear. */
|
|
349
|
+
credential: string;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** Who is sending: the host's agent, or a person on the tenant's staff. */
|
|
353
|
+
type SendAuthor = {
|
|
354
|
+
kind: "AGENT";
|
|
355
|
+
} | {
|
|
356
|
+
kind: "STAFF";
|
|
357
|
+
staffUserId?: string | null;
|
|
358
|
+
};
|
|
359
|
+
interface SendInput {
|
|
360
|
+
tenantId: string;
|
|
361
|
+
conversationId: string;
|
|
362
|
+
content: OutboundContent;
|
|
363
|
+
author: SendAuthor;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Mount the connector: one engine per process, over the host's store and
|
|
368
|
+
* ports, with one adapter per channel.
|
|
369
|
+
*/
|
|
370
|
+
declare function createMessagingEngine(config: MessagingEngineConfig): {
|
|
371
|
+
/** The adapter mounted for a channel, or undefined. */
|
|
372
|
+
adapter: (channel: string) => ChannelAdapter | undefined;
|
|
373
|
+
/** The channels this engine serves. */
|
|
374
|
+
channels: () => string[];
|
|
375
|
+
/** Store a VERIFIED raw delivery and queue its processing. The edge answers 200 after this. */
|
|
376
|
+
receive: (channel: string, rawBody: string) => Promise<{
|
|
377
|
+
deliveryId: string;
|
|
378
|
+
fresh: boolean;
|
|
379
|
+
}>;
|
|
380
|
+
/** The `process-delivery` job's body. */
|
|
381
|
+
processDelivery: (deliveryId: string) => Promise<DeliveryOutcome>;
|
|
382
|
+
/** The `reconcile-inbox` sweep's body. */
|
|
383
|
+
reconcile: () => Promise<{
|
|
384
|
+
retried: number;
|
|
385
|
+
failed: number;
|
|
386
|
+
}>;
|
|
387
|
+
/** The `retention` sweep's body. */
|
|
388
|
+
sweepRetention: () => Promise<{
|
|
389
|
+
conversations: number;
|
|
390
|
+
messages: number;
|
|
391
|
+
deliveries: number;
|
|
392
|
+
more: boolean;
|
|
393
|
+
}>;
|
|
394
|
+
send: (input: SendInput) => Promise<MessageView>;
|
|
395
|
+
connect: (input: ConnectInput) => Promise<ConnectionView>;
|
|
396
|
+
revoke: (tenantId: string, connectionId: string, reason?: string | null) => Promise<boolean>;
|
|
397
|
+
markError: (tenantId: string, connectionId: string, reason: string) => Promise<boolean>;
|
|
398
|
+
listConnections: (tenantId: string) => Promise<ConnectionView[]>;
|
|
399
|
+
getConversation: (tenantId: string, conversationId: string) => Promise<ConversationView | null>;
|
|
400
|
+
listMessages: (tenantId: string, conversationId: string) => Promise<MessageView[]>;
|
|
401
|
+
/**
|
|
402
|
+
* Move a conversation between AGENT, HUMAN and CLOSED (a hand-off). OPTED_OUT
|
|
403
|
+
* is the contact's alone, both ways: an opted-out conversation is not
|
|
404
|
+
* moved (null), and only the contact's next message re-opens it.
|
|
405
|
+
*/
|
|
406
|
+
setState: (tenantId: string, conversationId: string, state: Exclude<ConversationState, "OPTED_OUT">) => Promise<ConversationView | null>;
|
|
407
|
+
/** Replace the structured summary that outlives the text. */
|
|
408
|
+
setSummary: (tenantId: string, conversationId: string, summary: ConversationSummary) => Promise<ConversationView | null>;
|
|
409
|
+
/** Store an audio message's transcript (deleted with the text). */
|
|
410
|
+
setTranscript: (tenantId: string, messageId: string, transcript: string) => Promise<MessageView | null>;
|
|
411
|
+
};
|
|
412
|
+
type MessagingEngine = ReturnType<typeof createMessagingEngine>;
|
|
413
|
+
|
|
414
|
+
export { type ConnectInput as C, type DeliveryOutcome as D, type EventOutcome as E, type InboundMessageNotice as I, type MessagingStore as M, type NewConnection as N, PROCESS_DELIVERY_JOB as P, type StoredConnection as S, type ConversationPatch as a, MESSAGING_DEFAULTS as b, type MessagePatch as c, type MessagingClockPort as d, type MessagingEngine as e, type MessagingEngineConfig as f, type MessagingEnqueuePort as g, type MessagingHooks as h, type MessagingLogger as i, type MessagingSecretsPort as j, type NewConversation as k, type NewMessage as l, type SendAuthor as m, type SendInput as n, createMessagingEngine as o };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { S as StoredConnection, M as MessagingStore } from './engine-B5EPo66m.js';
|
|
2
|
+
export { C as ConnectInput, a as ConversationPatch, D as DeliveryOutcome, E as EventOutcome, I as InboundMessageNotice, b as MESSAGING_DEFAULTS, c as MessagePatch, d as MessagingClockPort, e as MessagingEngine, f as MessagingEngineConfig, g as MessagingEnqueuePort, h as MessagingHooks, i as MessagingLogger, j as MessagingSecretsPort, N as NewConnection, k as NewConversation, l as NewMessage, P as PROCESS_DELIVERY_JOB, m as SendAuthor, n as SendInput, o as createMessagingEngine } from './engine-B5EPo66m.js';
|
|
3
|
+
import { I as InboxDeliveryView, C as ConversationView, M as MessageView } from './channel-Cs_vLGl_.js';
|
|
4
|
+
export { A as AuthorKind, a as ChannelAdapter, b as ChannelKind, c as ChannelSendFailure, d as ChannelSendInput, e as ConnectionStatus, f as ConnectionView, g as ConversationState, h as ConversationSummary, D as DeliveryState, i as DeliveryStatus, H as HandshakeAnswer, j as InboundContent, k as InboundMessageEvent, l as MessageDirection, m as MessageKind, N as NormalizedEvent, O as OPEN_SEND_POLICY, n as OptOutEvent, o as OutboundContent, R as ReceiptStatus, S as SendPolicy, p as SendPolicyContext, q as SendPolicyVerdict, r as StatusEvent, s as isWindowOpen, t as serviceWindowPolicy } from './channel-Cs_vLGl_.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The engine's refusals, as typed errors with machine codes. The sentence a
|
|
8
|
+
* person reads for each is the host's copy, keyed by `code`.
|
|
9
|
+
*/
|
|
10
|
+
/** Why a send was refused or failed. */
|
|
11
|
+
type MessagingSendErrorCode =
|
|
12
|
+
/** The contact opted out; nothing is sent until they write again. */
|
|
13
|
+
"OPTED_OUT"
|
|
14
|
+
/** The channel's service window is closed (WhatsApp: 24 h after the contact's last message). */
|
|
15
|
+
| "WINDOW_CLOSED"
|
|
16
|
+
/** The conversation's connection is not connected (revoked, in error, or gone). */
|
|
17
|
+
| "NOT_CONNECTED"
|
|
18
|
+
/** No such conversation in this tenant. */
|
|
19
|
+
| "NOT_FOUND"
|
|
20
|
+
/** No adapter for the conversation's channel is mounted. */
|
|
21
|
+
| "UNKNOWN_CHANNEL"
|
|
22
|
+
/** The channel was called and refused or failed; the outbound row is FAILED. */
|
|
23
|
+
| "CHANNEL_FAILED";
|
|
24
|
+
declare class MessagingSendError extends Error {
|
|
25
|
+
readonly code: MessagingSendErrorCode;
|
|
26
|
+
/** The outbound row, when one was recorded before the failure. */
|
|
27
|
+
readonly messageId: string | null;
|
|
28
|
+
constructor(code: MessagingSendErrorCode, message: string, messageId?: string | null);
|
|
29
|
+
}
|
|
30
|
+
/** Why a connection could not be saved. */
|
|
31
|
+
type MessagingConnectErrorCode =
|
|
32
|
+
/** The account is connected to another tenant. */
|
|
33
|
+
"ACCOUNT_TAKEN"
|
|
34
|
+
/** No adapter for that channel is mounted. */
|
|
35
|
+
| "UNKNOWN_CHANNEL";
|
|
36
|
+
declare class MessagingConnectError extends Error {
|
|
37
|
+
readonly code: MessagingConnectErrorCode;
|
|
38
|
+
constructor(code: MessagingConnectErrorCode, message: string);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* An in-memory {@link MessagingStore}, for a host's tests and this package's
|
|
43
|
+
* own. It enforces the migration's unique keys the way Postgres does, so a
|
|
44
|
+
* test that passes here exercises the same dedupe a database would.
|
|
45
|
+
*
|
|
46
|
+
* Not for production: it lives in one process and forgets on restart.
|
|
47
|
+
*/
|
|
48
|
+
declare function createMemoryMessagingStore(): MessagingStore & {
|
|
49
|
+
readonly dump: () => MemoryStoreDump;
|
|
50
|
+
};
|
|
51
|
+
/** Everything the memory store holds, for a test to assert on. */
|
|
52
|
+
interface MemoryStoreDump {
|
|
53
|
+
deliveries: StoredDelivery[];
|
|
54
|
+
connections: StoredConnection[];
|
|
55
|
+
conversations: ConversationView[];
|
|
56
|
+
messages: MessageView[];
|
|
57
|
+
}
|
|
58
|
+
type StoredDelivery = InboxDeliveryView & {
|
|
59
|
+
bodyHash: string;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The Prisma delegates the store reads and writes.
|
|
64
|
+
*
|
|
65
|
+
* Structural rather than a `PrismaClient` import: the package must not depend
|
|
66
|
+
* on the host's generated client, and this shape is what any client generated
|
|
67
|
+
* from the shipped partial satisfies. Only the query subset below is used —
|
|
68
|
+
* equality, `in`, `lt`, `lte`, `gte`, `not`, compound unique keys, `increment`,
|
|
69
|
+
* `orderBy`, `take` — which is also what the package's Postgres suite
|
|
70
|
+
* translates, so the suite runs the exact queries a host runs.
|
|
71
|
+
*/
|
|
72
|
+
interface MessagingPrismaDb {
|
|
73
|
+
messagingConnection: Delegate;
|
|
74
|
+
messagingInboxDelivery: Delegate;
|
|
75
|
+
messagingConversation: Delegate;
|
|
76
|
+
messagingMessage: Delegate;
|
|
77
|
+
}
|
|
78
|
+
interface Delegate {
|
|
79
|
+
findUnique(args: unknown): Promise<unknown>;
|
|
80
|
+
findFirst(args: unknown): Promise<unknown>;
|
|
81
|
+
findMany(args: unknown): Promise<unknown[]>;
|
|
82
|
+
create(args: unknown): Promise<unknown>;
|
|
83
|
+
update(args: unknown): Promise<unknown>;
|
|
84
|
+
updateMany(args: unknown): Promise<{
|
|
85
|
+
count: number;
|
|
86
|
+
}>;
|
|
87
|
+
deleteMany(args: unknown): Promise<{
|
|
88
|
+
count: number;
|
|
89
|
+
}>;
|
|
90
|
+
}
|
|
91
|
+
/** A {@link MessagingStore} over a Prisma client generated from the shipped partial. */
|
|
92
|
+
declare function createPrismaMessagingStore(db: MessagingPrismaDb | (() => Promise<MessagingPrismaDb>)): MessagingStore;
|
|
93
|
+
|
|
94
|
+
/** The inbox key of a raw body: its SHA-256, hex. A redelivery is the same bytes, so the same key. */
|
|
95
|
+
declare function bodyHash(rawBody: string): string;
|
|
96
|
+
|
|
97
|
+
export { ConversationView, InboxDeliveryView, type MemoryStoreDump, MessageView, MessagingConnectError, type MessagingConnectErrorCode, type MessagingPrismaDb, MessagingSendError, type MessagingSendErrorCode, MessagingStore, StoredConnection, bodyHash, createMemoryMessagingStore, createPrismaMessagingStore };
|