@12-apps/messaging 1.5.0 → 1.6.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/README.md CHANGED
@@ -177,7 +177,7 @@ with `setTranscript` (it is deleted with the text), and drop the buffer.
177
177
  |---|---|
178
178
  | `@12-apps/messaging` | `createMessagingEngine`, the ports, the store port with `createPrismaMessagingStore` and `createMemoryMessagingStore`, the adapter interface, the errors, the types. |
179
179
  | `@12-apps/messaging/whatsapp` | `createWhatsAppAdapter`, and standalone: `verifyMetaSignature`, `verifyMetaSubscription`, `parseWhatsAppPayload`, `parseWhatsAppStatuses`, `isOptOutText`, the Graph sender, `downloadWhatsAppMedia`, and the Embedded Signup helpers `exchangeSignupCode`, `readSignupAccounts`, `subscribeAppToWaba`. |
180
- | `@12-apps/messaging/whatsapp-web` | UNOFFICIAL. `createWhatsAppWebSession` (a linked device over Baileys), `createWhatsAppWebAdapter` (the same `ChannelAdapter`), `createMemoryAuthStateStore`, and the pure `normalizeUpsert`, `normalizeUpdates`, `encodeEnvelope`, `parseEnvelope`. See below. |
180
+ | `@12-apps/messaging/whatsapp-web` | UNOFFICIAL. `createWhatsAppWebSession` (a linked device over Baileys), `createWhatsAppWebAdapter` (the same `ChannelAdapter`), `createMemoryAuthStateStore`, and the pure `normalizeUpsert`, `normalizeSentElsewhere`, `normalizeUpdates`, `encodeEnvelope`, `parseEnvelope`, and `ChoiceMemory` (the offered-choices memory the session uses, for a host that renders choices outside the session). The session also offers `sendPresence`, `markRead` and `fetchHistory`. See below. |
181
181
  | `@12-apps/messaging/inbound-guard` | `normalizeInbound`, `screenInbound`, `DEFAULT_INBOUND_RULES`, `wrapForAgent`, `parseClassification`: the screen a host runs on untrusted inbound text before a model reads it. Pure, no I/O, no channel. |
182
182
  | `@12-apps/messaging/server` | `createApiMessaging` (the webhook route pair, in `@12-apps/wiring`'s `WireRoute` shape) and `MESSAGING_JOBS`. |
183
183
  | `@12-apps/messaging/manifest`, `/manifest/server` | The wiring manifests. |
@@ -214,15 +214,18 @@ const engine = createMessagingEngine({ adapters: [createWhatsAppWebAdapter({ ses
214
214
  | | |
215
215
  |---|---|
216
216
  | **Pairing** | `onStatus` reports `qr`: show it on the phone under *Linked devices › Link a device*. With `pairingPhoneNumber`, the session asks ONCE for a code instead (`pairing-code`). After pairing, `creds.update` is saved on every change, and the next `start()` resumes without pairing. |
217
- | **Inbound** | Each live socket event is normalized into the SAME `NormalizedEvent`s the Cloud parser produces, then handed to `deliver` as a small JSON envelope, in socket order. The envelope holds no Baileys objects and no media keys. The inbox, dedupe, processing job and retention are the engine's, unchanged. A failed `deliver` is reported through `onError`, because a socket does not redeliver. |
218
- | **What is skipped** | Groups, broadcasts, Status, channels, the account's own messages (`fromMe`), history sync (`append`) and protocol messages. The engine's conversation is one contact. |
219
- | **Outbound** | `send` goes through the session's socket. Personal accounts have no buttons or lists, so `BUTTONS` and `LIST` become numbered lines under the text, and the answer arrives as `TEXT`. Failures are `ChannelSendFailure`: `NOT_CONNECTED`, the socket's code, or `NO_MESSAGE_ID`. |
217
+ | **Inbound** | Each live socket event is normalized into the SAME `NormalizedEvent`s the Cloud parser produces, then handed to `deliver` as a small JSON envelope, one at a time and in socket order, except a phone-sent message held while a send was in flight (see *Sent from another device*), which is handed on when it is judged, after events that arrived later. The envelope holds no Baileys objects and no media keys. The inbox, dedupe, processing job and retention are the engine's, unchanged. A failed `deliver` is reported through `onError`, because a socket does not redeliver. |
218
+ | **What is skipped** | Groups, broadcasts, Status, channels, history sync (`append`, `messaging-history.set`) and protocol messages. The engine's conversation is one contact. The account's own messages are not inbound, but see *Sent from another device*. |
219
+ | **Outbound** | `send` goes through the session's socket. Personal accounts have no buttons or lists, so `BUTTONS` and `LIST` become numbered lines under the text. The session remembers the last choices offered to each contact (500 contacts, 2 h; `choiceMemorySize`, `choiceTtlMs`), keyed by the address the reply will carry (`+55 11 98765-4321`, `5511987654321:12@s.whatsapp.net` and a LID with its phone number all match the inbound contact), and a TEXT answer that is exactly a listed number (`1`, `1.`, ` 2 `) or exactly a choice's title (case and accents ignored) arrives as `INTERACTIVE { replyId, title }`, as a tap would on the Cloud adapter. Any other answer stays `TEXT` and clears nothing; a match uses the offer up. An offer maps only the first reply after it: any later message to that contact, a plain text from the session or a message from the phone, clears it. Failures are `ChannelSendFailure`: `NOT_CONNECTED`, the socket's code, or `NO_MESSAGE_ID`. |
220
220
  | **Receipts** | `messages.update` on our own messages maps to `SENT` / `DELIVERED` / `READ` / `FAILED`. |
221
221
  | **Media** | The last `mediaCacheSize` (200) audio messages stay in memory. `fetchMedia` downloads by message id, with the size cap and the deadline. After a restart an older audio is `NOT_FOUND`. |
222
222
  | **Reconnects** | An unexpected close reconnects with exponential backoff (5 attempts from 2 s), and 515 (restart after pairing) reconnects at once. 401 (logged out) clears the keys and stops. 440 (replaced) and 403 stop. |
223
223
  | **Webhook** | None. `verify` fails closed, so the webhook route answers 401 to any POST for the channel. |
224
224
  | **Policy** | No service window by default (`OPEN_SEND_POLICY`); the 24 h window is a Business API rule. |
225
225
  | **Channel key** | `whatsapp` by default, so the switch keeps the connections and conversations. Pass `kind: "whatsapp-web"` to run both side by side. The connection's credential is unused: the keys live in the auth store. |
226
+ | **Sent from another device** | A message the account sent from its OTHER device (`fromMe` on a live `notify`) becomes a `sent_elsewhere` event: `contactId`, `externalId`, `sentAt`, and `content` (the text; anything else is `OTHER`, never media keys). The engine stores it ONLY when the contact already has a conversation on that connection, as an `OUTBOUND` message of it, `authorKind: "STAFF"`, `SENT`, once (deduped on its id), and calls `hooks.onStaffReply({ conversation, message })`. A message to anyone else (the owner's family and friends on the store's phone) is dropped (`no-conversation`): never stored, and it never opens a conversation. It changes no state: a host that steps its agent aside does it there. It is never emitted for the echo of a send the session itself made: the session remembers the ids it sent, and holds a `fromMe` event that arrives while sends are in flight (Baileys can emit the echo before `sendMessage` resolves), judging it once THOSE sends settle. A held event waits at most 30 s and at most 200 are held (the oldest is judged first); a close or `stop` releases them all, judged against the ids known then. Accepted edge: a send that throws AFTER its message left (the socket failed before returning the id) has no id to remember, so its echo is reported as a staff reply. |
227
+ | **Presence and read marks** | `session.sendPresence(contactId, "composing" \| "paused")` and `session.markRead(contactId, externalIds)` call the socket's `sendPresenceUpdate` and `readMessages`. They never reject: a failure, or a session that is not open (`ChannelSendFailure` `NOT_CONNECTED`), goes to `onError` with `presence` or `mark-read`. |
228
+ | **History on demand** | `session.fetchHistory(contactId, { externalId, sentAt, fromMe }, count, timeoutMs)` asks the phone (`fetchMessageHistory`) for up to `count` messages before the anchor and resolves with that chat's messages from the `messaging-history.set` answer: `{ externalId, fromMe, sentAt, text, kind }`, oldest first, both sides. Text only: media is a placeholder `kind` (`image`, `audio`, …) with `text: null`, never keys. It resolves `[]` when the session is not open, on timeout, or on failure (`history` in `onError`); a late answer is dropped. Nothing reaches the inbox or the engine, and the session keeps no message after the request settles: what the host does with them (not storing them) is its decision. |
226
229
 
227
230
  ## Screening inbound text before a model reads it
228
231
 
@@ -103,7 +103,27 @@ interface OptOutEvent {
103
103
  contactId: string;
104
104
  at: Date;
105
105
  }
106
- type NormalizedEvent = InboundMessageEvent | StatusEvent | OptOutEvent;
106
+ /**
107
+ * A message the account itself sent from ANOTHER device (the owner's phone,
108
+ * typed in the app), seen on a linked-device channel. The engine stores it as
109
+ * an OUTBOUND message of the conversation authored by `STAFF` and tells the
110
+ * host (`hooks.onStaffReply`), so the host can step its agent aside.
111
+ *
112
+ * Never the echo of a send the engine made: the channel adapter dedupes those
113
+ * before they become events. `content` is the text, or `OTHER` for media.
114
+ */
115
+ interface SentElsewhereEvent {
116
+ type: "sent_elsewhere";
117
+ /** The channel account that sent it. */
118
+ accountId: string;
119
+ /** The recipient's address on the channel. */
120
+ contactId: string;
121
+ /** The channel's id for the message. */
122
+ externalId: string;
123
+ sentAt: Date;
124
+ content: InboundContent;
125
+ }
126
+ type NormalizedEvent = InboundMessageEvent | StatusEvent | OptOutEvent | SentElsewhereEvent;
107
127
  /** A message the tenant sends, normalized across channels. */
108
128
  type OutboundContent = {
109
129
  kind: "TEXT";
@@ -340,4 +360,4 @@ declare function serviceWindowPolicy(windowMs: number): SendPolicy;
340
360
  /** A policy for a channel with no window (e-mail): every send is allowed. */
341
361
  declare const OPEN_SEND_POLICY: SendPolicy;
342
362
 
343
- export { type AuthorKind as A, type ConversationView as C, DEFAULT_MEDIA_TIMEOUT_MS 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, type ChannelMedia as c, ChannelMediaFailure as d, type ChannelMediaInput as e, ChannelSendFailure as f, type ChannelSendInput as g, type ConnectionStatus as h, type ConnectionView as i, type ConversationState as j, type ConversationSummary as k, type DeliveryState as l, type DeliveryStatus as m, type InboundContent as n, type InboundMessageEvent as o, type MessageDirection as p, type MessageKind as q, type OptOutEvent as r, type OutboundContent as s, type SendPolicyContext as t, type SendPolicyVerdict as u, type StatusEvent as v, isWindowOpen as w, serviceWindowPolicy as x };
363
+ export { type AuthorKind as A, type ConversationView as C, DEFAULT_MEDIA_TIMEOUT_MS 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, type ChannelMedia as c, ChannelMediaFailure as d, type ChannelMediaInput as e, ChannelSendFailure as f, type ChannelSendInput as g, type ConnectionStatus as h, type ConnectionView as i, type ConversationState as j, type ConversationSummary as k, type DeliveryState as l, type DeliveryStatus as m, type InboundContent as n, type InboundMessageEvent as o, type MessageDirection as p, type MessageKind as q, type OptOutEvent as r, type OutboundContent as s, type SendPolicyContext as t, type SendPolicyVerdict as u, type SentElsewhereEvent as v, type StatusEvent as w, isWindowOpen as x, serviceWindowPolicy as y };
@@ -1,4 +1,4 @@
1
- import { j as ConversationState, k as ConversationSummary, i as ConnectionView, m as DeliveryStatus, b as ChannelKind, I as InboxDeliveryView, h as ConnectionStatus, C as ConversationView, M as MessageView, p as MessageDirection, q as MessageKind, A as AuthorKind, R as ReceiptStatus, a as ChannelAdapter, N as NormalizedEvent, s as OutboundContent, c as ChannelMedia } from './channel-CZjNEBLC.js';
1
+ import { j as ConversationState, k as ConversationSummary, i as ConnectionView, m as DeliveryStatus, b as ChannelKind, I as InboxDeliveryView, h as ConnectionStatus, C as ConversationView, M as MessageView, p as MessageDirection, q as MessageKind, A as AuthorKind, R as ReceiptStatus, a as ChannelAdapter, N as NormalizedEvent, s as OutboundContent, c as ChannelMedia } from './channel-BWhnnuip.js';
2
2
 
3
3
  /**
4
4
  * THE STORE PORT: every read and write the engine makes, as named operations.
@@ -236,6 +236,11 @@ interface InboundMessageNotice {
236
236
  conversation: ConversationView;
237
237
  message: MessageView;
238
238
  }
239
+ /** What `onStaffReply` is told: the conversation, and the stored message the owner sent from another device. */
240
+ interface StaffReplyNotice {
241
+ conversation: ConversationView;
242
+ message: MessageView;
243
+ }
239
244
  /** What a re-opened conversation may become. */
240
245
  type ReopenState = Exclude<ConversationState, "OPTED_OUT">;
241
246
  /** The host's answers to what only it knows about a conversation. All optional. */
@@ -248,6 +253,16 @@ interface MessagingHooks {
248
253
  * retried, because the message is already stored. Default: nothing.
249
254
  */
250
255
  onInboundMessage?(notice: InboundMessageNotice): Promise<void> | void;
256
+ /**
257
+ * The account's owner answered a contact from ANOTHER device (their phone),
258
+ * on a channel that shows it (WhatsApp Web's `sent_elsewhere` event). The
259
+ * message is stored first, as an outbound `STAFF` message, and this runs once
260
+ * per stored message, never for a redelivery and never for the echo of a send
261
+ * the engine made. The engine changes no state itself: a host that wants its
262
+ * agent to step aside does it here (`setState(..., "HUMAN")`, a timer).
263
+ * A throw is logged, never retried. Default: nothing.
264
+ */
265
+ onStaffReply?(notice: StaffReplyNotice): Promise<void> | void;
251
266
  /**
252
267
  * The state a CLOSED or OPTED_OUT conversation re-opens into when its
253
268
  * contact writes again. Default: `AGENT`. A host never returns `OPTED_OUT`
@@ -319,9 +334,11 @@ declare const MESSAGING_DEFAULTS: {
319
334
  * the event is dropped (the edge already answered 200, so the channel stops
320
335
  * redelivering) and a tenant can never receive another tenant's traffic.
321
336
  */
322
- type EventOutcome = {
337
+ type EventOutcome =
338
+ /** `no-conversation`: a message the owner sent from their phone to a contact the store has no conversation with here. */
339
+ {
323
340
  kind: "dropped";
324
- reason: "unknown-account" | "not-connected";
341
+ reason: "unknown-account" | "not-connected" | "no-conversation";
325
342
  } | {
326
343
  kind: "duplicate";
327
344
  } | {
@@ -331,6 +348,12 @@ type EventOutcome = {
331
348
  } | {
332
349
  kind: "opted-out";
333
350
  conversationId: string;
351
+ }
352
+ /** A message the owner sent from another device, stored as the store's own. */
353
+ | {
354
+ kind: "staff-message";
355
+ conversationId: string;
356
+ messageId: string;
334
357
  } | {
335
358
  kind: "receipt";
336
359
  applied: boolean;
@@ -448,4 +471,4 @@ declare function createMessagingEngine(config: MessagingEngineConfig): {
448
471
  };
449
472
  type MessagingEngine = ReturnType<typeof createMessagingEngine>;
450
473
 
451
- export { type ConnectInput as C, DEFAULT_MEDIA_MAX_BYTES 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, type DeliveryOutcome as b, type DownloadMediaOptions as c, MESSAGING_DEFAULTS as d, type MessagePatch as e, type MessagingClockPort as f, type MessagingEngine as g, type MessagingEngineConfig as h, type MessagingEnqueuePort as i, type MessagingHooks as j, type MessagingLogger as k, type MessagingSecretsPort as l, type NewConversation as m, type NewMessage as n, type SendAuthor as o, type SendInput as p, createMessagingEngine as q };
474
+ export { type ConnectInput as C, DEFAULT_MEDIA_MAX_BYTES 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, type DeliveryOutcome as b, type DownloadMediaOptions as c, MESSAGING_DEFAULTS as d, type MessagePatch as e, type MessagingClockPort as f, type MessagingEngine as g, type MessagingEngineConfig as h, type MessagingEnqueuePort as i, type MessagingHooks as j, type MessagingLogger as k, type MessagingSecretsPort as l, type NewConversation as m, type NewMessage as n, type SendAuthor as o, type SendInput as p, type StaffReplyNotice as q, createMessagingEngine as r };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { S as StoredConnection, M as MessagingStore } from './engine-BJse1HAX.js';
2
- export { C as ConnectInput, a as ConversationPatch, D as DEFAULT_MEDIA_MAX_BYTES, b as DeliveryOutcome, c as DownloadMediaOptions, E as EventOutcome, I as InboundMessageNotice, d as MESSAGING_DEFAULTS, e as MessagePatch, f as MessagingClockPort, g as MessagingEngine, h as MessagingEngineConfig, i as MessagingEnqueuePort, j as MessagingHooks, k as MessagingLogger, l as MessagingSecretsPort, N as NewConnection, m as NewConversation, n as NewMessage, P as PROCESS_DELIVERY_JOB, o as SendAuthor, p as SendInput, q as createMessagingEngine } from './engine-BJse1HAX.js';
3
- import { I as InboxDeliveryView, C as ConversationView, M as MessageView } from './channel-CZjNEBLC.js';
4
- export { A as AuthorKind, a as ChannelAdapter, b as ChannelKind, c as ChannelMedia, d as ChannelMediaFailure, e as ChannelMediaInput, f as ChannelSendFailure, g as ChannelSendInput, h as ConnectionStatus, i as ConnectionView, j as ConversationState, k as ConversationSummary, D as DEFAULT_MEDIA_TIMEOUT_MS, l as DeliveryState, m as DeliveryStatus, H as HandshakeAnswer, n as InboundContent, o as InboundMessageEvent, p as MessageDirection, q as MessageKind, N as NormalizedEvent, O as OPEN_SEND_POLICY, r as OptOutEvent, s as OutboundContent, R as ReceiptStatus, S as SendPolicy, t as SendPolicyContext, u as SendPolicyVerdict, v as StatusEvent, w as isWindowOpen, x as serviceWindowPolicy } from './channel-CZjNEBLC.js';
1
+ import { S as StoredConnection, M as MessagingStore } from './engine-BybESJ7p.js';
2
+ export { C as ConnectInput, a as ConversationPatch, D as DEFAULT_MEDIA_MAX_BYTES, b as DeliveryOutcome, c as DownloadMediaOptions, E as EventOutcome, I as InboundMessageNotice, d as MESSAGING_DEFAULTS, e as MessagePatch, f as MessagingClockPort, g as MessagingEngine, h as MessagingEngineConfig, i as MessagingEnqueuePort, j as MessagingHooks, k as MessagingLogger, l as MessagingSecretsPort, N as NewConnection, m as NewConversation, n as NewMessage, P as PROCESS_DELIVERY_JOB, o as SendAuthor, p as SendInput, q as StaffReplyNotice, r as createMessagingEngine } from './engine-BybESJ7p.js';
3
+ import { I as InboxDeliveryView, C as ConversationView, M as MessageView } from './channel-BWhnnuip.js';
4
+ export { A as AuthorKind, a as ChannelAdapter, b as ChannelKind, c as ChannelMedia, d as ChannelMediaFailure, e as ChannelMediaInput, f as ChannelSendFailure, g as ChannelSendInput, h as ConnectionStatus, i as ConnectionView, j as ConversationState, k as ConversationSummary, D as DEFAULT_MEDIA_TIMEOUT_MS, l as DeliveryState, m as DeliveryStatus, H as HandshakeAnswer, n as InboundContent, o as InboundMessageEvent, p as MessageDirection, q as MessageKind, N as NormalizedEvent, O as OPEN_SEND_POLICY, r as OptOutEvent, s as OutboundContent, R as ReceiptStatus, S as SendPolicy, t as SendPolicyContext, u as SendPolicyVerdict, v as SentElsewhereEvent, w as StatusEvent, x as isWindowOpen, y as serviceWindowPolicy } from './channel-BWhnnuip.js';
5
5
 
6
6
  /**
7
7
  * The engine's refusals, as typed errors with machine codes. The sentence a
package/dist/index.js CHANGED
@@ -95,6 +95,62 @@ function bodyHash(rawBody) {
95
95
  }
96
96
  __name(bodyHash, "bodyHash");
97
97
 
98
+ // src/core/sent-elsewhere.ts
99
+ var later = /* @__PURE__ */ __name((a, b) => a && a > b ? a : b, "later");
100
+ var MAX_WRITE_ATTEMPTS = 6;
101
+ async function handleSentElsewhere(ctx, connection, event) {
102
+ const { store } = ctx.config;
103
+ if (await store.findMessageByExternalId(connection.channel, event.externalId)) return { kind: "duplicate" };
104
+ const body = event.content.kind === "TEXT" ? event.content.text : null;
105
+ const conversation = await touchConversation(ctx, connection, event, body !== null);
106
+ if (!conversation) return { kind: "dropped", reason: "no-conversation" };
107
+ const inserted = await store.insertMessage({
108
+ conversationId: conversation.id,
109
+ tenantId: connection.tenantId,
110
+ channel: connection.channel,
111
+ direction: "OUTBOUND",
112
+ kind: body === null ? "OTHER" : "TEXT",
113
+ body,
114
+ options: null,
115
+ attachmentRef: null,
116
+ externalId: event.externalId,
117
+ deliveryStatus: "SENT",
118
+ authorKind: "STAFF",
119
+ staffUserId: null,
120
+ createdAt: event.sentAt
121
+ });
122
+ if (!inserted.created) return { kind: "duplicate" };
123
+ await notifyStaffReply(ctx, conversation, inserted.message);
124
+ return { kind: "staff-message", conversationId: conversation.id, messageId: inserted.message.id };
125
+ }
126
+ __name(handleSentElsewhere, "handleSentElsewhere");
127
+ async function touchConversation(ctx, connection, event, carriesText) {
128
+ const { store } = ctx.config;
129
+ for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt += 1) {
130
+ const existing = await store.findConversation(connection.tenantId, connection.channel, event.contactId);
131
+ if (!existing || existing.connectionId !== connection.id) return null;
132
+ const updated = await store.updateConversation(
133
+ connection.tenantId,
134
+ existing.id,
135
+ { lastMessageAt: later(existing.lastMessageAt, event.sentAt), ...carriesText ? { hasText: true } : {} },
136
+ { state: existing.state, lastInboundAt: existing.lastInboundAt, lastMessageAt: existing.lastMessageAt, optedOutAt: existing.optedOutAt }
137
+ );
138
+ if (updated) return updated;
139
+ }
140
+ throw new Error(`conversation ${event.contactId} kept changing under this message; retry`);
141
+ }
142
+ __name(touchConversation, "touchConversation");
143
+ async function notifyStaffReply(ctx, conversation, message) {
144
+ const hook = ctx.config.hooks?.onStaffReply;
145
+ if (!hook) return;
146
+ try {
147
+ await hook({ conversation, message });
148
+ } catch (error) {
149
+ ctx.config.logger.error(`messaging.inbound: onStaffReply failed for ${conversation.id}: ${errorText(error)}`, { error });
150
+ }
151
+ }
152
+ __name(notifyStaffReply, "notifyStaffReply");
153
+
98
154
  // src/core/inbound.ts
99
155
  async function handleEvent(ctx, channel, event) {
100
156
  const connection = await ctx.config.store.findConnectionByAccount(channel, event.accountId);
@@ -102,6 +158,7 @@ async function handleEvent(ctx, channel, event) {
102
158
  if (connection.status !== "CONNECTED") return { kind: "dropped", reason: "not-connected" };
103
159
  if (event.type === "message") return handleMessage(ctx, connection, event);
104
160
  if (event.type === "opt_out") return handleOptOut(ctx, connection, event);
161
+ if (event.type === "sent_elsewhere") return handleSentElsewhere(ctx, connection, event);
105
162
  const applied = await ctx.config.store.applyReceipt({
106
163
  tenantId: connection.tenantId,
107
164
  channel,
@@ -126,8 +183,8 @@ function columnsOf(content) {
126
183
  }
127
184
  }
128
185
  __name(columnsOf, "columnsOf");
129
- var later = /* @__PURE__ */ __name((a, b) => a && a > b ? a : b, "later");
130
- var MAX_WRITE_ATTEMPTS = 6;
186
+ var later2 = /* @__PURE__ */ __name((a, b) => a && a > b ? a : b, "later");
187
+ var MAX_WRITE_ATTEMPTS2 = 6;
131
188
  async function handleMessage(ctx, connection, event) {
132
189
  const { store } = ctx.config;
133
190
  if (await store.findMessageByExternalId(connection.channel, event.externalId)) return { kind: "duplicate" };
@@ -154,7 +211,7 @@ async function handleMessage(ctx, connection, event) {
154
211
  __name(handleMessage, "handleMessage");
155
212
  async function openConversation(ctx, connection, event, carriesText) {
156
213
  const { store } = ctx.config;
157
- for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt += 1) {
214
+ for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS2; attempt += 1) {
158
215
  const existing = await store.findConversation(connection.tenantId, connection.channel, event.contactId);
159
216
  const result = existing ? await updateExisting(ctx, connection, existing, event, carriesText) : await createFirst(ctx, connection, event, carriesText);
160
217
  if (result) return result;
@@ -187,10 +244,10 @@ async function updateExisting(ctx, connection, existing, event, carriesText) {
187
244
  {
188
245
  // Left out when unchanged: the write never carries a state it did not decide.
189
246
  ...state !== existing.state ? { state } : {},
190
- ...event.optOut ? { optedOutAt: later(existing.optedOutAt, event.sentAt) } : {},
247
+ ...event.optOut ? { optedOutAt: later2(existing.optedOutAt, event.sentAt) } : {},
191
248
  ...connection.id !== existing.connectionId ? { connectionId: connection.id } : {},
192
- lastInboundAt: later(existing.lastInboundAt, event.sentAt),
193
- lastMessageAt: later(existing.lastMessageAt, event.sentAt),
249
+ lastInboundAt: later2(existing.lastInboundAt, event.sentAt),
250
+ lastMessageAt: later2(existing.lastMessageAt, event.sentAt),
194
251
  ...event.contactName ? { contactName: event.contactName } : {},
195
252
  ...carriesText ? { hasText: true } : {}
196
253
  },
@@ -221,7 +278,7 @@ async function notifyHost(ctx, conversation, message) {
221
278
  __name(notifyHost, "notifyHost");
222
279
  async function handleOptOut(ctx, connection, event) {
223
280
  const { store } = ctx.config;
224
- for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt += 1) {
281
+ for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS2; attempt += 1) {
225
282
  const existing = await store.findConversation(connection.tenantId, connection.channel, event.contactId);
226
283
  if (!existing) {
227
284
  const created = await store.createConversation({
@@ -244,7 +301,7 @@ async function handleOptOut(ctx, connection, event) {
244
301
  existing.id,
245
302
  {
246
303
  ...existing.state !== "OPTED_OUT" ? { state: "OPTED_OUT" } : {},
247
- optedOutAt: later(existing.optedOutAt, event.at)
304
+ optedOutAt: later2(existing.optedOutAt, event.at)
248
305
  },
249
306
  { state: existing.state, lastInboundAt: existing.lastInboundAt, lastMessageAt: existing.lastMessageAt, optedOutAt: existing.optedOutAt }
250
307
  );