@adatechnology/meta-whatsapp-module 0.12.0 → 0.14.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
@@ -224,6 +224,14 @@ whatsapp.flows!.registerDynamicChoiceProvider('free_slots', async ({ context, pa
224
224
  `'duplicate'` sem reenviar nem reavisar a equipe. Erro depois dessa escrita **não sobe** — vai para
225
225
  `onFlowRunnerError` (ou é descartado sem o gancho) e a conversa fica no último ponto gravado. Erro
226
226
  antes dela (leitura do grafo, banco fora) sobe, e a retentativa é segura.
227
+ - **Retentativa do envio (`sendRetry`).** Cada mensagem do turno é retentada sozinha (padrão 3 tentativas, espera
228
+ 500 ms e 1 s, teto de 5 s), então o que já saiu nunca é reenviado. Só repete falha de rede antes de a Meta receber
229
+ a mensagem (`isTransientSendError`); recusa da Meta, erro de banco depois do envio e janela expirada sobem na
230
+ primeira vez. Timeout **não** repete por padrão (a Meta pode ter aceitado e a Cloud API não tem chave de
231
+ idempotência); quem prefere repetir passa `sendRetry.shouldRetry`. As esperas rodam com o lock da conversa preso,
232
+ por isso o total é curto. Esgotadas as tentativas, o erro segue para `onFlowRunnerError`, agora com
233
+ `details.send = { attempts, messageKind, isTransient }` para o host avisar a equipe. Não cobre a mensagem do
234
+ encaminhamento (`handoff`) nem mídia de ação.
227
235
  - **Fuso obrigatório.** `timeZone` (ou `handoff.businessHours.timeZone`, quando fixo) define "hoje";
228
236
  sem ele o módulo falha na montagem. Servidor em UTC aceitaria "hoje" errado entre 21h e meia-noite.
229
237
  - **Variáveis do host vencem.** Em `{{chave}}`, `resolveVariables`, `contactName` e `contactFirstName`
package/dist/index.cjs CHANGED
@@ -84,8 +84,8 @@ __export(index_exports, {
84
84
  TakeoverConversationUseCase: () => TakeoverConversationUseCase,
85
85
  TranscribeAudioUseCase: () => TranscribeAudioUseCase,
86
86
  UpdateQuickReplyUseCase: () => UpdateQuickReplyUseCase,
87
- WEBHOOK_CLAIM_TTL_SECONDS: () => import_meta_graph_core3.WEBHOOK_CLAIM_TTL_SECONDS,
88
- WEBHOOK_NONCE_TTL_SECONDS: () => import_meta_graph_core3.WEBHOOK_NONCE_TTL_SECONDS,
87
+ WEBHOOK_CLAIM_TTL_SECONDS: () => import_meta_graph_core4.WEBHOOK_CLAIM_TTL_SECONDS,
88
+ WEBHOOK_NONCE_TTL_SECONDS: () => import_meta_graph_core4.WEBHOOK_NONCE_TTL_SECONDS,
89
89
  WhatsAppChannelAdapter: () => WhatsAppChannelAdapter,
90
90
  buildFlowChoiceMessage: () => buildFlowChoiceMessage,
91
91
  buildInboundJobId: () => buildInboundJobId,
@@ -103,6 +103,7 @@ __export(index_exports, {
103
103
  isAudioMimeType: () => isAudioMimeType,
104
104
  isChoiceNode: () => isChoiceNode,
105
105
  isRetriableTranscriptionError: () => isRetriableTranscriptionError,
106
+ isTransientSendError: () => isTransientSendError,
106
107
  isUnsupportedTranscriptionError: () => isUnsupportedTranscriptionError,
107
108
  issueSseTicket: () => issueSseTicket,
108
109
  messages: () => messages,
@@ -698,6 +699,7 @@ var import_drizzle_orm3 = require("drizzle-orm");
698
699
  var INBOUND_LOCATION_CONTENT = "\u{1F4CD} Localiza\xE7\xE3o";
699
700
 
700
701
  // src/repositories/MessageRepository.ts
702
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
701
703
  var DEFAULT_LIMIT2 = 50;
702
704
  var MessageRepository = class {
703
705
  static {
@@ -870,7 +872,15 @@ var MessageRepository = class {
870
872
  (0, import_drizzle_orm3.eq)(messages.companyId, params.companyId),
871
873
  (0, import_drizzle_orm3.eq)(messages.sessionId, params.sessionId)
872
874
  ];
873
- if (params.before) conditions.push((0, import_drizzle_orm3.lt)(messages.createdAt, new Date(params.before)));
875
+ if (params.beforeId && UUID_PATTERN.test(params.beforeId)) {
876
+ const compositeCursor = import_drizzle_orm3.sql`(${messages.createdAt}, ${messages.id}) < (
877
+ select cursor_row.created_at, cursor_row.id from ${messages} as cursor_row
878
+ where cursor_row.id = ${params.beforeId}
879
+ and cursor_row.company_id = ${params.companyId}
880
+ and cursor_row.session_id = ${params.sessionId}
881
+ )`;
882
+ conditions.push(params.before ? import_drizzle_orm3.sql`coalesce(${compositeCursor}, ${(0, import_drizzle_orm3.lt)(messages.createdAt, new Date(params.before))})` : compositeCursor);
883
+ } else if (params.before) conditions.push((0, import_drizzle_orm3.lt)(messages.createdAt, new Date(params.before)));
874
884
  const newestFirst = await this.db.select().from(messages).where((0, import_drizzle_orm3.and)(...conditions)).orderBy((0, import_drizzle_orm3.desc)(messages.createdAt), (0, import_drizzle_orm3.desc)(messages.id)).limit(params.limit ?? DEFAULT_LIMIT2);
875
885
  return newestFirst.reverse();
876
886
  }
@@ -1658,7 +1668,8 @@ var ListMessagesUseCase = class {
1658
1668
  companyId: params.companyId,
1659
1669
  sessionId: session.id,
1660
1670
  limit: params.limit,
1661
- before: params.before
1671
+ before: params.before,
1672
+ beforeId: params.beforeId
1662
1673
  };
1663
1674
  return this.messageRepository.listByConversation(repoParams);
1664
1675
  }
@@ -2457,6 +2468,9 @@ var import_meta_whatsapp_contracts12 = require("@adatechnology/meta-whatsapp-con
2457
2468
  var DEFAULT_START_FLOW_KEY = "main";
2458
2469
  var DEFAULT_MAX_INVALID_ANSWERS = 2;
2459
2470
  var DEFAULT_MAX_CROSS_FLOW_JUMPS = 5;
2471
+ var DEFAULT_SEND_RETRY_MAX_ATTEMPTS = 3;
2472
+ var DEFAULT_SEND_RETRY_BASE_DELAY_MS = 500;
2473
+ var DEFAULT_SEND_RETRY_MAX_DELAY_MS = 5e3;
2460
2474
  var DEFAULT_FLOW_TEXT = {
2461
2475
  FALLBACK: "N\xE3o entendi. Pode responder de novo?",
2462
2476
  CHOICE_PROMPT: "Escolha uma op\xE7\xE3o:",
@@ -2837,6 +2851,47 @@ async function resolveFlowConfigText(params) {
2837
2851
  }
2838
2852
  __name(resolveFlowConfigText, "resolveFlowConfigText");
2839
2853
 
2854
+ // src/flows/sendWithRetry.ts
2855
+ var import_meta_graph_core2 = require("@adatechnology/meta-graph-core");
2856
+ function isTransientSendError(error) {
2857
+ return error instanceof import_meta_graph_core2.WhatsAppConnectionError;
2858
+ }
2859
+ __name(isTransientSendError, "isTransientSendError");
2860
+ var sleepFor = /* @__PURE__ */ __name((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)), "sleepFor");
2861
+ var SendRetriesExhausted = class {
2862
+ static {
2863
+ __name(this, "SendRetriesExhausted");
2864
+ }
2865
+ error;
2866
+ attempts;
2867
+ isTransient;
2868
+ constructor(error, attempts, isTransient) {
2869
+ this.error = error;
2870
+ this.attempts = attempts;
2871
+ this.isTransient = isTransient;
2872
+ }
2873
+ };
2874
+ async function sendWithRetry(send, config = {}) {
2875
+ const maxAttempts = Math.max(1, config.maxAttempts ?? DEFAULT_SEND_RETRY_MAX_ATTEMPTS);
2876
+ const baseDelay = config.baseDelayMs ?? DEFAULT_SEND_RETRY_BASE_DELAY_MS;
2877
+ const maxDelay = config.maxDelayMs ?? DEFAULT_SEND_RETRY_MAX_DELAY_MS;
2878
+ const shouldRetry = config.shouldRetry ?? isTransientSendError;
2879
+ const sleep = config.sleep ?? sleepFor;
2880
+ for (let attempt = 1; ; attempt++) {
2881
+ try {
2882
+ await send();
2883
+ return {
2884
+ attempts: attempt
2885
+ };
2886
+ } catch (error) {
2887
+ const isTransient = shouldRetry(error);
2888
+ if (!isTransient || attempt >= maxAttempts) throw new SendRetriesExhausted(error, attempt, isTransient);
2889
+ await sleep(Math.min(baseDelay * 2 ** (attempt - 1), maxDelay));
2890
+ }
2891
+ }
2892
+ }
2893
+ __name(sendWithRetry, "sendWithRetry");
2894
+
2840
2895
  // src/flows/FlowRunner.ts
2841
2896
  function contactVariables(profileName) {
2842
2897
  if (!profileName) return {};
@@ -2866,6 +2921,8 @@ var FlowRunner = class {
2866
2921
  // Variáveis da mensagem em curso, por sessão: é como a action `handoff` (que só recebe a sessão)
2867
2922
  // enxerga o nome do contato sem que ele precise ir para o contexto gravado.
2868
2923
  turnVariables = /* @__PURE__ */ new WeakMap();
2924
+ // Erro de envio já sem retentativa → o que se tentou, para `report` entregar ao host sem trocar o erro.
2925
+ sendFailures = /* @__PURE__ */ new WeakMap();
2869
2926
  constructor(dependencies) {
2870
2927
  this.dependencies = dependencies;
2871
2928
  this.renderer = new FlowQuestionRenderer(dependencies.config);
@@ -3360,6 +3417,10 @@ var FlowRunner = class {
3360
3417
  body
3361
3418
  });
3362
3419
  }
3420
+ /**
3421
+ * Cada mensagem é retentada sozinha (ver `sendWithRetry`): o que já saiu neste turno não é reenviado.
3422
+ * Esgotadas as tentativas, o erro original sobe como antes e o `report` ganha `details.send`.
3423
+ */
3363
3424
  async send(turn, message) {
3364
3425
  const common = {
3365
3426
  companyId: turn.companyId,
@@ -3367,14 +3428,29 @@ var FlowRunner = class {
3367
3428
  sender: "bot",
3368
3429
  startState: this.dependencies.startState
3369
3430
  };
3370
- if (message.kind === "text") await this.dependencies.sendMessage.sendText({
3371
- ...common,
3372
- body: message.body
3373
- });
3374
- else await this.dependencies.sendMessage.sendInteractive({
3375
- ...common,
3376
- interactive: message.interactive
3377
- });
3431
+ const deliver = /* @__PURE__ */ __name(async () => {
3432
+ if (message.kind === "text") await this.dependencies.sendMessage.sendText({
3433
+ ...common,
3434
+ body: message.body
3435
+ });
3436
+ else await this.dependencies.sendMessage.sendInteractive({
3437
+ ...common,
3438
+ interactive: message.interactive
3439
+ });
3440
+ }, "deliver");
3441
+ try {
3442
+ await sendWithRetry(deliver, this.dependencies.config.sendRetry);
3443
+ } catch (failure) {
3444
+ if (!(failure instanceof SendRetriesExhausted)) throw failure;
3445
+ if (typeof failure.error === "object" && failure.error !== null) {
3446
+ this.sendFailures.set(failure.error, {
3447
+ attempts: failure.attempts,
3448
+ messageKind: message.kind,
3449
+ isTransient: failure.isTransient
3450
+ });
3451
+ }
3452
+ throw failure.error;
3453
+ }
3378
3454
  }
3379
3455
  save(turn, progress) {
3380
3456
  const runtime = runtimeOf(progress.context);
@@ -3402,12 +3478,16 @@ var FlowRunner = class {
3402
3478
  * ponto gravado e a próxima mensagem do cliente segue dali); gancho que falha também não derruba.
3403
3479
  */
3404
3480
  async report(turn, flowKey, nodeId, stage, error) {
3481
+ const send = typeof error === "object" && error !== null ? this.sendFailures.get(error) : void 0;
3405
3482
  const details = {
3406
3483
  companyId: turn.companyId,
3407
3484
  whatsappNumber: turn.session.whatsappNumber,
3408
3485
  flowKey,
3409
3486
  nodeId,
3410
- stage
3487
+ stage,
3488
+ ...send ? {
3489
+ send
3490
+ } : {}
3411
3491
  };
3412
3492
  try {
3413
3493
  await this.dependencies.hooks?.onFlowRunnerError?.(error, details);
@@ -3850,7 +3930,7 @@ var FlowMediaIdRepository = class {
3850
3930
  };
3851
3931
 
3852
3932
  // src/channel/WhatsAppChannelAdapter.ts
3853
- var import_meta_graph_core2 = require("@adatechnology/meta-graph-core");
3933
+ var import_meta_graph_core3 = require("@adatechnology/meta-graph-core");
3854
3934
  var import_meta_whatsapp_contracts19 = require("@adatechnology/meta-whatsapp-contracts");
3855
3935
 
3856
3936
  // src/channel/previewMedia.ts
@@ -3878,7 +3958,7 @@ var WhatsAppChannelAdapter = class {
3878
3958
  try {
3879
3959
  return await operation();
3880
3960
  } catch (error) {
3881
- if (error instanceof import_meta_graph_core2.WhatsAppWindowExpiredError) throw new import_meta_whatsapp_contracts19.WindowExpiredError();
3961
+ if (error instanceof import_meta_graph_core3.WhatsAppWindowExpiredError) throw new import_meta_whatsapp_contracts19.WindowExpiredError();
3882
3962
  throw error;
3883
3963
  }
3884
3964
  }
@@ -3997,31 +4077,31 @@ var WhatsAppChannelAdapter = class {
3997
4077
  var import_meta_whatsapp_contracts22 = require("@adatechnology/meta-whatsapp-contracts");
3998
4078
 
3999
4079
  // src/channel/webhookSecurity.ts
4000
- var import_meta_graph_core3 = require("@adatechnology/meta-graph-core");
4080
+ var import_meta_graph_core4 = require("@adatechnology/meta-graph-core");
4001
4081
  var import_meta_whatsapp_contracts20 = require("@adatechnology/meta-whatsapp-contracts");
4002
4082
  var WEBHOOK_NONCE_NAMESPACE = "meta-whatsapp";
4003
4083
  function verifyWebhookChallenge(params) {
4004
- if (!(0, import_meta_graph_core3.isValidWebhookChallenge)(params)) throw new import_meta_whatsapp_contracts20.InvalidWebhookSignatureError();
4084
+ if (!(0, import_meta_graph_core4.isValidWebhookChallenge)(params)) throw new import_meta_whatsapp_contracts20.InvalidWebhookSignatureError();
4005
4085
  return params.challenge;
4006
4086
  }
4007
4087
  __name(verifyWebhookChallenge, "verifyWebhookChallenge");
4008
4088
  function verifyWebhookSignature(params) {
4009
- if (!(0, import_meta_graph_core3.isValidWebhookSignature)(params)) throw new import_meta_whatsapp_contracts20.InvalidWebhookSignatureError();
4089
+ if (!(0, import_meta_graph_core4.isValidWebhookSignature)(params)) throw new import_meta_whatsapp_contracts20.InvalidWebhookSignatureError();
4010
4090
  }
4011
4091
  __name(verifyWebhookSignature, "verifyWebhookSignature");
4012
4092
  function deliveryKey(signatureHeader) {
4013
- return (0, import_meta_graph_core3.buildWebhookDeliveryKey)({
4093
+ return (0, import_meta_graph_core4.buildWebhookDeliveryKey)({
4014
4094
  namespace: WEBHOOK_NONCE_NAMESPACE,
4015
4095
  signatureHeader
4016
4096
  });
4017
4097
  }
4018
4098
  __name(deliveryKey, "deliveryKey");
4019
4099
  async function claimWebhookDelivery(params) {
4020
- return params.nonceStore.setIfAbsent(deliveryKey(params.signatureHeader), params.ttlSeconds ?? import_meta_graph_core3.WEBHOOK_CLAIM_TTL_SECONDS);
4100
+ return params.nonceStore.setIfAbsent(deliveryKey(params.signatureHeader), params.ttlSeconds ?? import_meta_graph_core4.WEBHOOK_CLAIM_TTL_SECONDS);
4021
4101
  }
4022
4102
  __name(claimWebhookDelivery, "claimWebhookDelivery");
4023
4103
  async function confirmWebhookDelivery(params) {
4024
- await params.nonceStore.confirm?.(deliveryKey(params.signatureHeader), params.ttlSeconds ?? import_meta_graph_core3.WEBHOOK_NONCE_TTL_SECONDS);
4104
+ await params.nonceStore.confirm?.(deliveryKey(params.signatureHeader), params.ttlSeconds ?? import_meta_graph_core4.WEBHOOK_NONCE_TTL_SECONDS);
4025
4105
  }
4026
4106
  __name(confirmWebhookDelivery, "confirmWebhookDelivery");
4027
4107
 
@@ -5230,6 +5310,7 @@ __name(createMetaWhatsAppQuickReplyRoutes, "createMetaWhatsAppQuickReplyRoutes")
5230
5310
  isAudioMimeType,
5231
5311
  isChoiceNode,
5232
5312
  isRetriableTranscriptionError,
5313
+ isTransientSendError,
5233
5314
  isUnsupportedTranscriptionError,
5234
5315
  issueSseTicket,
5235
5316
  messages,