@adatechnology/meta-whatsapp-module 0.8.1 → 0.10.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/dist/index.cjs CHANGED
@@ -23,19 +23,28 @@ var index_exports = {};
23
23
  __export(index_exports, {
24
24
  CountInboundLocationsUseCase: () => CountInboundLocationsUseCase,
25
25
  CreateFlowGraphUseCase: () => CreateFlowGraphUseCase,
26
+ DEFAULT_FALLBACK_LIST_LABEL: () => DEFAULT_FALLBACK_LIST_LABEL,
26
27
  DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS: () => DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS,
28
+ DEFAULT_FLOW_TEXT: () => DEFAULT_FLOW_TEXT,
29
+ DEFAULT_MAX_INVALID_ANSWERS: () => DEFAULT_MAX_INVALID_ANSWERS,
30
+ DEFAULT_START_FLOW_KEY: () => DEFAULT_START_FLOW_KEY,
31
+ DYNAMIC_CHOICE_MORE_ID: () => DYNAMIC_CHOICE_MORE_ID,
27
32
  DeleteConversationUseCase: () => DeleteConversationUseCase,
28
33
  DeleteFlowGraphUseCase: () => DeleteFlowGraphUseCase,
29
34
  DocumentRepository: () => DocumentRepository,
30
35
  ExportConversationUseCase: () => ExportConversationUseCase,
36
+ FLOW_RUNTIME_CONTEXT_KEY: () => FLOW_RUNTIME_CONTEXT_KEY,
31
37
  FlowGraphCache: () => FlowGraphCache,
32
38
  FlowGraphRepository: () => FlowGraphRepository,
39
+ FlowHandoff: () => FlowHandoff,
33
40
  FlowInterpreter: () => FlowInterpreter,
34
41
  FlowMediaIdRepository: () => FlowMediaIdRepository,
35
42
  FlowMediaRepository: () => FlowMediaRepository,
43
+ FlowRunner: () => FlowRunner,
36
44
  GetFlowGraphUseCase: () => GetFlowGraphUseCase,
37
45
  GetLiveFlowPositionsUseCase: () => GetLiveFlowPositionsUseCase,
38
46
  INBOUND_LOCATION_CONTENT: () => INBOUND_LOCATION_CONTENT,
47
+ InProcessFlowTurnLock: () => InProcessFlowTurnLock,
39
48
  InboundEffectsDispatcher: () => InboundEffectsDispatcher,
40
49
  IngestInboundMediaUseCase: () => IngestInboundMediaUseCase,
41
50
  InvalidFlowGraphError: () => InvalidFlowGraphError,
@@ -48,13 +57,15 @@ __export(index_exports, {
48
57
  META_WHATSAPP_MIGRATIONS_TABLE: () => META_WHATSAPP_MIGRATIONS_TABLE,
49
58
  MessageRepository: () => MessageRepository,
50
59
  OptimisticLockError: () => OptimisticLockError,
51
- PREVIEW_MEDIA_ID_PREFIX: () => import_meta_whatsapp_contracts8.PREVIEW_MEDIA_ID_PREFIX,
60
+ PREVIEW_MEDIA_ID_PREFIX: () => import_meta_whatsapp_contracts14.PREVIEW_MEDIA_ID_PREFIX,
52
61
  PRODUCT_LIST_LIMIT: () => PRODUCT_LIST_LIMIT,
62
+ PostgresAdvisoryFlowTurnLock: () => PostgresAdvisoryFlowTurnLock,
53
63
  ProcessInboundDispatchUseCase: () => ProcessInboundDispatchUseCase,
54
64
  PurgeExpiredDocumentsUseCase: () => PurgeExpiredDocumentsUseCase,
55
65
  ReceiveWebhookUseCase: () => ReceiveWebhookUseCase,
56
66
  RedactInboundLocationsUseCase: () => RedactInboundLocationsUseCase,
57
67
  ReleaseConversationUseCase: () => ReleaseConversationUseCase,
68
+ RequestHumanConversationUseCase: () => RequestHumanConversationUseCase,
58
69
  SaveFlowGraphUseCase: () => SaveFlowGraphUseCase,
59
70
  SendMessageUseCase: () => SendMessageUseCase,
60
71
  SessionRepository: () => SessionRepository,
@@ -65,9 +76,10 @@ __export(index_exports, {
65
76
  TRANSCRIPTION_STATUS: () => TRANSCRIPTION_STATUS,
66
77
  TakeoverConversationUseCase: () => TakeoverConversationUseCase,
67
78
  TranscribeAudioUseCase: () => TranscribeAudioUseCase,
68
- WEBHOOK_CLAIM_TTL_SECONDS: () => import_meta_graph_core2.WEBHOOK_CLAIM_TTL_SECONDS,
69
- WEBHOOK_NONCE_TTL_SECONDS: () => import_meta_graph_core2.WEBHOOK_NONCE_TTL_SECONDS,
79
+ WEBHOOK_CLAIM_TTL_SECONDS: () => import_meta_graph_core3.WEBHOOK_CLAIM_TTL_SECONDS,
80
+ WEBHOOK_NONCE_TTL_SECONDS: () => import_meta_graph_core3.WEBHOOK_NONCE_TTL_SECONDS,
70
81
  WhatsAppChannelAdapter: () => WhatsAppChannelAdapter,
82
+ buildFlowChoiceMessage: () => buildFlowChoiceMessage,
71
83
  buildInboundJobId: () => buildInboundJobId,
72
84
  claimWebhookDelivery: () => claimWebhookDelivery,
73
85
  confirmWebhookDelivery: () => confirmWebhookDelivery,
@@ -80,19 +92,23 @@ __export(index_exports, {
80
92
  flowGraphs: () => flowGraphs,
81
93
  flowMedia: () => flowMedia,
82
94
  isAudioMimeType: () => isAudioMimeType,
95
+ isChoiceNode: () => isChoiceNode,
83
96
  isRetriableTranscriptionError: () => isRetriableTranscriptionError,
84
97
  isUnsupportedTranscriptionError: () => isUnsupportedTranscriptionError,
85
98
  issueSseTicket: () => issueSseTicket,
86
99
  messages: () => messages,
87
100
  metaWhatsAppMigrationsFolder: () => metaWhatsAppMigrationsFolder,
88
101
  metaWhatsAppSchema: () => metaWhatsAppSchema,
102
+ readFlowInbound: () => readFlowInbound,
89
103
  redeemSseTicket: () => redeemSseTicket,
90
104
  resolveFailureStatus: () => resolveFailureStatus,
91
- resolvePreviewUploadId: () => import_meta_whatsapp_contracts8.resolvePreviewUploadId,
105
+ resolveFlowAnswer: () => resolveFlowAnswer,
106
+ resolveFlowTimeZone: () => resolveFlowTimeZone,
107
+ resolvePreviewUploadId: () => import_meta_whatsapp_contracts14.resolvePreviewUploadId,
92
108
  runMetaWhatsAppMigrations: () => runMetaWhatsAppMigrations,
93
109
  sessions: () => sessions,
94
110
  settings: () => settings,
95
- toPreviewMediaId: () => import_meta_whatsapp_contracts8.toPreviewMediaId,
111
+ toPreviewMediaId: () => import_meta_whatsapp_contracts14.toPreviewMediaId,
96
112
  toSessionContract: () => toSessionContract,
97
113
  transcriptionRetryAfterSeconds: () => transcriptionRetryAfterSeconds,
98
114
  verifyWebhookChallenge: () => verifyWebhookChallenge,
@@ -102,7 +118,8 @@ module.exports = __toCommonJS(index_exports);
102
118
 
103
119
  // src/createMetaWhatsAppModule.ts
104
120
  var import_meta_whatsapp_provider = require("@adatechnology/meta-whatsapp-provider");
105
- var import_meta_whatsapp_contracts13 = require("@adatechnology/meta-whatsapp-contracts");
121
+ var import_testing = require("@adatechnology/meta-whatsapp-contracts/testing");
122
+ var import_meta_whatsapp_contracts19 = require("@adatechnology/meta-whatsapp-contracts");
106
123
 
107
124
  // src/repositories/SessionRepository.ts
108
125
  var import_drizzle_orm2 = require("drizzle-orm");
@@ -491,6 +508,21 @@ var SessionRepository = class {
491
508
  updatedAt: import_drizzle_orm2.sql`now()`
492
509
  }).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(sessions.companyId, companyId), (0, import_drizzle_orm2.eq)(sessions.whatsappNumber, whatsappNumber)));
493
510
  }
511
+ /**
512
+ * Posição no grafo e contexto numa escrita só — é o que o runner grava a cada mensagem. Em duas
513
+ * escritas, uma falha no meio deixaria a conversa num nó novo com as respostas do anterior.
514
+ * Não toca em `currentState`, `mode` nem `humanRequestedAt`: uma ação de encaminhamento que rodou
515
+ * no mesmo passo já os mudou, e regravá-los desfaria isso.
516
+ */
517
+ async saveFlowProgress(companyId, whatsappNumber, progress) {
518
+ await this.db.update(sessions).set({
519
+ flowKey: progress.flowKey,
520
+ currentNodeId: progress.currentNodeId,
521
+ context: progress.context,
522
+ lastActivity: import_drizzle_orm2.sql`now()`,
523
+ updatedAt: import_drizzle_orm2.sql`now()`
524
+ }).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(sessions.companyId, companyId), (0, import_drizzle_orm2.eq)(sessions.whatsappNumber, whatsappNumber)));
525
+ }
494
526
  // Marca a chegada de uma mensagem DO CLIENTE. É este carimbo — e não lastActivity, que também
495
527
  // se move em ações do atendente/bot — que define a janela de 24h do WhatsApp: fora dela, só
496
528
  // template aprovado reabre a conversa (ver WindowExpiredError nos contracts).
@@ -1104,6 +1136,7 @@ var LogMessageUseCase = class {
1104
1136
  // src/use-cases/SendMessage.use-case.ts
1105
1137
  var import_meta_whatsapp_contracts2 = require("@adatechnology/meta-whatsapp-contracts");
1106
1138
  var WHATSAPP_WINDOW_HOURS = 24;
1139
+ var DEFAULT_FALLBACK_LIST_LABEL = "Op\xE7\xF5es";
1107
1140
  var SendMessageUseCase = class {
1108
1141
  static {
1109
1142
  __name(this, "SendMessageUseCase");
@@ -1188,6 +1221,54 @@ var SendMessageUseCase = class {
1188
1221
  }
1189
1222
  return saved;
1190
1223
  }
1224
+ /**
1225
+ * Botões ou lista, pelo mesmo caminho do `sendText`: janela, envio, transcript (idempotente pelo
1226
+ * `waMessageId`). Os limites da Meta são conferidos ANTES de tudo — mensagem fora do teto a Graph
1227
+ * API recusa inteira, e o erro local (`InteractiveLimitExceededError`) diz qual campo corrigir.
1228
+ *
1229
+ * O transcript guarda `type: 'interactive'`, o corpo em `content` e a mensagem inteira (ids e
1230
+ * títulos das opções) em `payload.interactive`, para o histórico mostrar o que foi oferecido.
1231
+ */
1232
+ async sendInteractive(params) {
1233
+ (0, import_meta_whatsapp_contracts2.assertInteractiveWithinLimits)(params.interactive);
1234
+ await this.assertWithinWindow(params.companyId, params.whatsappNumber);
1235
+ const { externalMessageId } = await this.sendInteractiveThroughChannel(params);
1236
+ return this.logMessage.execute({
1237
+ companyId: params.companyId,
1238
+ whatsappNumber: params.whatsappNumber,
1239
+ direction: "outbound",
1240
+ sender: params.sender,
1241
+ agentUserId: params.agentUserId ?? null,
1242
+ type: "interactive",
1243
+ content: params.interactive.body,
1244
+ payload: {
1245
+ interactive: params.interactive
1246
+ },
1247
+ waMessageId: externalMessageId,
1248
+ status: "sent",
1249
+ startState: params.startState
1250
+ });
1251
+ }
1252
+ sendInteractiveThroughChannel(params) {
1253
+ const interactive = params.interactive;
1254
+ const to = params.whatsappNumber;
1255
+ if (interactive.kind === "list") {
1256
+ return this.channel.sendInteractiveList({
1257
+ to,
1258
+ body: interactive.body,
1259
+ buttonLabel: interactive.buttonLabel,
1260
+ sections: interactive.sections
1261
+ });
1262
+ }
1263
+ if (this.channel.sendInteractiveButtons) {
1264
+ return this.channel.sendInteractiveButtons({
1265
+ to,
1266
+ body: interactive.body,
1267
+ buttons: interactive.buttons
1268
+ });
1269
+ }
1270
+ return this.channel.sendInteractiveList(buttonsAsList(interactive, to, params.fallbackListLabel));
1271
+ }
1191
1272
  // Template é o único envio que ignora a janela — é justamente o mecanismo que a Meta oferece
1192
1273
  // para reabri-la.
1193
1274
  async sendTemplate(params) {
@@ -1215,6 +1296,15 @@ var SendMessageUseCase = class {
1215
1296
  });
1216
1297
  }
1217
1298
  };
1299
+ function buttonsAsList(interactive, to, label) {
1300
+ return {
1301
+ to,
1302
+ body: interactive.body,
1303
+ buttonLabel: label ?? DEFAULT_FALLBACK_LIST_LABEL,
1304
+ rows: interactive.buttons
1305
+ };
1306
+ }
1307
+ __name(buttonsAsList, "buttonsAsList");
1218
1308
  function mediaTypeFor(mimeType) {
1219
1309
  if (mimeType.startsWith("image/")) return "image";
1220
1310
  if (mimeType.startsWith("audio/")) return "audio";
@@ -1230,9 +1320,11 @@ var TakeoverConversationUseCase = class {
1230
1320
  }
1231
1321
  sessionRepository;
1232
1322
  realtime;
1233
- constructor(sessionRepository, realtime) {
1323
+ hooks;
1324
+ constructor(sessionRepository, realtime, hooks) {
1234
1325
  this.sessionRepository = sessionRepository;
1235
1326
  this.realtime = realtime;
1327
+ this.hooks = hooks;
1236
1328
  }
1237
1329
  async execute(params) {
1238
1330
  await this.sessionRepository.takeover(params.companyId, params.whatsappNumber, params.agentUserId);
@@ -1241,6 +1333,15 @@ var TakeoverConversationUseCase = class {
1241
1333
  assignedUserId: params.agentUserId
1242
1334
  });
1243
1335
  this.realtime?.emit("global", "data-changed", {});
1336
+ await this.hooks?.onConversationModeChanged?.({
1337
+ companyId: params.companyId,
1338
+ whatsappNumber: params.whatsappNumber,
1339
+ kind: "takeover",
1340
+ mode: "human",
1341
+ assignedUserId: params.agentUserId,
1342
+ actorId: params.actorId ?? params.agentUserId,
1343
+ occurredAt: /* @__PURE__ */ new Date()
1344
+ });
1244
1345
  }
1245
1346
  };
1246
1347
 
@@ -1251,9 +1352,11 @@ var ReleaseConversationUseCase = class {
1251
1352
  }
1252
1353
  sessionRepository;
1253
1354
  realtime;
1254
- constructor(sessionRepository, realtime) {
1355
+ hooks;
1356
+ constructor(sessionRepository, realtime, hooks) {
1255
1357
  this.sessionRepository = sessionRepository;
1256
1358
  this.realtime = realtime;
1359
+ this.hooks = hooks;
1257
1360
  }
1258
1361
  async execute(params) {
1259
1362
  await this.sessionRepository.release(params.companyId, params.whatsappNumber);
@@ -1262,6 +1365,165 @@ var ReleaseConversationUseCase = class {
1262
1365
  assignedUserId: null
1263
1366
  });
1264
1367
  this.realtime?.emit("global", "data-changed", {});
1368
+ await this.hooks?.onConversationModeChanged?.({
1369
+ companyId: params.companyId,
1370
+ whatsappNumber: params.whatsappNumber,
1371
+ kind: "release",
1372
+ mode: "bot",
1373
+ assignedUserId: null,
1374
+ actorId: params.actorId ?? null,
1375
+ occurredAt: /* @__PURE__ */ new Date()
1376
+ });
1377
+ }
1378
+ };
1379
+
1380
+ // src/use-cases/RequestHumanConversation.use-case.ts
1381
+ var import_meta_whatsapp_contracts3 = require("@adatechnology/meta-whatsapp-contracts");
1382
+
1383
+ // src/channel/inboundDispatch.ts
1384
+ var import_meta_graph_core = require("@adatechnology/meta-graph-core");
1385
+ function buildInboundJobId(job) {
1386
+ return job.kind === "message" ? `wa-inbound-message:${job.message.id}` : `wa-inbound-status:${job.status.id}:${job.status.status}`;
1387
+ }
1388
+ __name(buildInboundJobId, "buildInboundJobId");
1389
+ function toSessionContract(row) {
1390
+ return {
1391
+ id: row.id,
1392
+ companyId: row.companyId,
1393
+ whatsappNumber: row.whatsappNumber,
1394
+ currentState: row.currentState,
1395
+ flowKey: row.flowKey,
1396
+ currentNodeId: row.currentNodeId,
1397
+ context: row.context,
1398
+ mode: row.mode,
1399
+ assignedUserId: row.assignedUserId,
1400
+ humanRequestedAt: row.humanRequestedAt?.toISOString() ?? null,
1401
+ lastInboundAt: row.lastInboundAt?.toISOString() ?? null,
1402
+ lastAgentReadAt: row.lastAgentReadAt?.toISOString() ?? null,
1403
+ lastActivity: row.lastActivity.toISOString(),
1404
+ createdAt: row.createdAt.toISOString(),
1405
+ updatedAt: row.updatedAt.toISOString()
1406
+ };
1407
+ }
1408
+ __name(toSessionContract, "toSessionContract");
1409
+ var InboundEffectsDispatcher = class {
1410
+ static {
1411
+ __name(this, "InboundEffectsDispatcher");
1412
+ }
1413
+ params;
1414
+ constructor(params) {
1415
+ this.params = params;
1416
+ }
1417
+ async run(job) {
1418
+ if (job.kind === "message") return this.runMessageEffects(job);
1419
+ return this.runStatusEffects(job);
1420
+ }
1421
+ async runMessageEffects(job) {
1422
+ const { companyId, message, savedMessageId, media } = job;
1423
+ if (media) {
1424
+ await this.params.hooks?.onMediaReceived?.({
1425
+ companyId,
1426
+ messageId: savedMessageId,
1427
+ whatsappNumber: message.from,
1428
+ sourceMediaId: media.sourceMediaId,
1429
+ mimeType: media.mimeType,
1430
+ ...media.filename ? {
1431
+ filename: media.filename
1432
+ } : {}
1433
+ });
1434
+ }
1435
+ const sessionRow = await this.params.sessionRepository.getContext(companyId, message.from);
1436
+ if (!sessionRow) return;
1437
+ if (sessionRow.mode === "human") return;
1438
+ const outcome = await this.params.hooks?.onMessageReceived?.(message, toSessionContract(sessionRow), job.profileName === void 0 ? {} : {
1439
+ profileName: job.profileName
1440
+ });
1441
+ if (outcome?.outcome === "handled") return;
1442
+ await this.params.flowRunner?.handle({
1443
+ companyId,
1444
+ message,
1445
+ ...job.profileName === void 0 ? {} : {
1446
+ profileName: job.profileName
1447
+ }
1448
+ });
1449
+ }
1450
+ async runStatusEffects(job) {
1451
+ const sessionRow = await this.params.sessionRepository.getContext(job.companyId, job.whatsappNumber);
1452
+ await this.params.hooks?.onStatusUpdate?.(job.status, sessionRow ? toSessionContract(sessionRow) : null);
1453
+ }
1454
+ };
1455
+ var ProcessInboundDispatchUseCase = class {
1456
+ static {
1457
+ __name(this, "ProcessInboundDispatchUseCase");
1458
+ }
1459
+ dispatcher;
1460
+ hooks;
1461
+ constructor(dispatcher, hooks) {
1462
+ this.dispatcher = dispatcher;
1463
+ this.hooks = hooks;
1464
+ }
1465
+ async execute(job) {
1466
+ await runInboundEffects({
1467
+ dispatcher: this.dispatcher,
1468
+ job,
1469
+ ...this.hooks ? {
1470
+ hooks: this.hooks
1471
+ } : {}
1472
+ });
1473
+ }
1474
+ };
1475
+ async function runInboundEffects(params) {
1476
+ const { job } = params;
1477
+ try {
1478
+ await params.dispatcher.run(job);
1479
+ } catch (error) {
1480
+ if (!(0, import_meta_graph_core.isDeterministicMetaRejection)(error)) throw error;
1481
+ await params.hooks?.onInboundEffectRejected?.({
1482
+ companyId: job.companyId,
1483
+ kind: job.kind,
1484
+ whatsappNumber: job.kind === "message" ? job.message.from : job.whatsappNumber,
1485
+ code: error.code,
1486
+ error
1487
+ });
1488
+ }
1489
+ }
1490
+ __name(runInboundEffects, "runInboundEffects");
1491
+
1492
+ // src/use-cases/RequestHumanConversation.use-case.ts
1493
+ var RequestHumanConversationUseCase = class {
1494
+ static {
1495
+ __name(this, "RequestHumanConversationUseCase");
1496
+ }
1497
+ sessionRepository;
1498
+ realtime;
1499
+ hooks;
1500
+ constructor(sessionRepository, realtime, hooks) {
1501
+ this.sessionRepository = sessionRepository;
1502
+ this.realtime = realtime;
1503
+ this.hooks = hooks;
1504
+ }
1505
+ async execute(params) {
1506
+ await this.sessionRepository.requestHuman(params.companyId, params.whatsappNumber);
1507
+ const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
1508
+ if (!session) throw new import_meta_whatsapp_contracts3.SessionNotFoundError(params.whatsappNumber);
1509
+ this.realtime?.emit(`conv:${params.whatsappNumber}`, "human-requested", {
1510
+ humanRequestedAt: session.humanRequestedAt?.toISOString() ?? null
1511
+ });
1512
+ this.realtime?.emit("global", "data-changed", {});
1513
+ const outcomes = await Promise.allSettled([
1514
+ (async () => this.hooks?.onHumanRequested?.(toSessionContract(session)))(),
1515
+ (async () => this.hooks?.onConversationModeChanged?.({
1516
+ companyId: params.companyId,
1517
+ whatsappNumber: params.whatsappNumber,
1518
+ kind: "human-requested",
1519
+ mode: session.mode,
1520
+ assignedUserId: session.assignedUserId,
1521
+ actorId: params.actorId ?? null,
1522
+ occurredAt: /* @__PURE__ */ new Date()
1523
+ }))()
1524
+ ]);
1525
+ const failure = outcomes.find((outcome) => outcome.status === "rejected");
1526
+ if (failure) throw failure.reason;
1265
1527
  }
1266
1528
  };
1267
1529
 
@@ -1280,7 +1542,7 @@ var ListConversationsUseCase = class {
1280
1542
  };
1281
1543
 
1282
1544
  // src/use-cases/ListMessages.use-case.ts
1283
- var import_meta_whatsapp_contracts3 = require("@adatechnology/meta-whatsapp-contracts");
1545
+ var import_meta_whatsapp_contracts4 = require("@adatechnology/meta-whatsapp-contracts");
1284
1546
  var ListMessagesUseCase = class {
1285
1547
  static {
1286
1548
  __name(this, "ListMessagesUseCase");
@@ -1293,7 +1555,7 @@ var ListMessagesUseCase = class {
1293
1555
  }
1294
1556
  async execute(params) {
1295
1557
  const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
1296
- if (!session) throw new import_meta_whatsapp_contracts3.SessionNotFoundError(params.whatsappNumber);
1558
+ if (!session) throw new import_meta_whatsapp_contracts4.SessionNotFoundError(params.whatsappNumber);
1297
1559
  const repoParams = {
1298
1560
  companyId: params.companyId,
1299
1561
  sessionId: session.id,
@@ -1305,7 +1567,7 @@ var ListMessagesUseCase = class {
1305
1567
  };
1306
1568
 
1307
1569
  // src/use-cases/ListConversationDocuments.use-case.ts
1308
- var import_meta_whatsapp_contracts4 = require("@adatechnology/meta-whatsapp-contracts");
1570
+ var import_meta_whatsapp_contracts5 = require("@adatechnology/meta-whatsapp-contracts");
1309
1571
  var ListConversationDocumentsUseCase = class {
1310
1572
  static {
1311
1573
  __name(this, "ListConversationDocumentsUseCase");
@@ -1318,7 +1580,7 @@ var ListConversationDocumentsUseCase = class {
1318
1580
  }
1319
1581
  async execute(params) {
1320
1582
  const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
1321
- if (!session) throw new import_meta_whatsapp_contracts4.SessionNotFoundError(params.whatsappNumber);
1583
+ if (!session) throw new import_meta_whatsapp_contracts5.SessionNotFoundError(params.whatsappNumber);
1322
1584
  const { rows, total } = await this.documentRepository.listByConversation({
1323
1585
  companyId: params.companyId,
1324
1586
  sessionId: session.id,
@@ -1396,7 +1658,7 @@ var ListCompanyDocumentsUseCase = class {
1396
1658
  };
1397
1659
 
1398
1660
  // src/use-cases/DeleteConversation.use-case.ts
1399
- var import_meta_whatsapp_contracts5 = require("@adatechnology/meta-whatsapp-contracts");
1661
+ var import_meta_whatsapp_contracts6 = require("@adatechnology/meta-whatsapp-contracts");
1400
1662
  var DeleteConversationUseCase = class {
1401
1663
  static {
1402
1664
  __name(this, "DeleteConversationUseCase");
@@ -1411,7 +1673,7 @@ var DeleteConversationUseCase = class {
1411
1673
  }
1412
1674
  async execute(params) {
1413
1675
  const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
1414
- if (!session) throw new import_meta_whatsapp_contracts5.SessionNotFoundError(params.whatsappNumber);
1676
+ if (!session) throw new import_meta_whatsapp_contracts6.SessionNotFoundError(params.whatsappNumber);
1415
1677
  const uploadIds = await this.documentRepository.listUploadIdsBySession(params.companyId, session.id);
1416
1678
  if (uploadIds.length > 0 && !this.objectStorage?.delete) {
1417
1679
  throw new Error("storage_delete_unsupported: a conversa tem arquivos e o storage injetado n\xE3o implementa delete");
@@ -1657,7 +1919,7 @@ var DocumentRepository = class {
1657
1919
  };
1658
1920
 
1659
1921
  // src/use-cases/ExportConversation.use-case.ts
1660
- var import_meta_whatsapp_contracts6 = require("@adatechnology/meta-whatsapp-contracts");
1922
+ var import_meta_whatsapp_contracts7 = require("@adatechnology/meta-whatsapp-contracts");
1661
1923
  var ExportConversationUseCase = class {
1662
1924
  static {
1663
1925
  __name(this, "ExportConversationUseCase");
@@ -1668,7 +1930,7 @@ var ExportConversationUseCase = class {
1668
1930
  }
1669
1931
  async execute(params) {
1670
1932
  const result = await this.sessionRepository.exportConversation(params.companyId, params.whatsappNumber);
1671
- if (!result) throw new import_meta_whatsapp_contracts6.SessionNotFoundError(params.whatsappNumber);
1933
+ if (!result) throw new import_meta_whatsapp_contracts7.SessionNotFoundError(params.whatsappNumber);
1672
1934
  return result;
1673
1935
  }
1674
1936
  };
@@ -1748,7 +2010,7 @@ var GetLiveFlowPositionsUseCase = class {
1748
2010
  };
1749
2011
 
1750
2012
  // src/flows/FlowInterpreter.ts
1751
- var import_meta_whatsapp_contracts7 = require("@adatechnology/meta-whatsapp-contracts");
2013
+ var import_meta_whatsapp_contracts8 = require("@adatechnology/meta-whatsapp-contracts");
1752
2014
  var DEFAULT_MAX_STEPS = 50;
1753
2015
  function evaluateCondition(node, context) {
1754
2016
  if (!node.conditionContextKey || !node.conditionOperator || !node.conditionValue) return false;
@@ -1804,6 +2066,7 @@ var FlowInterpreter = class {
1804
2066
  return this.moveTo(input, resolveNext(node, branch));
1805
2067
  }
1806
2068
  if (node.type === "action") {
2069
+ if (!node.actionKind) return this.moveTo(input, resolveNext(node, void 0));
1807
2070
  const handler = node.actionKind ? this.actionHandlers.get(node.actionKind) : void 0;
1808
2071
  if (!handler) return {
1809
2072
  kind: "terminal",
@@ -1825,7 +2088,7 @@ var FlowInterpreter = class {
1825
2088
  context: contextAfterAction
1826
2089
  }, nextNodeId2);
1827
2090
  }
1828
- const isChoice = node.type === "menu" || node.questionType === "choice";
2091
+ const isChoice = node.type === "menu" || node.type === "dynamic_choice" || node.questionType === "choice";
1829
2092
  if (input.userAnswer === void 0) {
1830
2093
  return {
1831
2094
  kind: "awaiting-answer",
@@ -1833,9 +2096,10 @@ var FlowInterpreter = class {
1833
2096
  context: input.context
1834
2097
  };
1835
2098
  }
2099
+ const storedValue = input.answerValue !== void 0 ? input.answerValue : input.userAnswer;
1836
2100
  const updatedContext = node.contextKey ? {
1837
2101
  ...input.context,
1838
- [node.contextKey]: input.userAnswer
2102
+ [node.contextKey]: storedValue
1839
2103
  } : input.context;
1840
2104
  const answerId = isChoice ? input.userAnswer : void 0;
1841
2105
  const nextNodeId = resolveNext(node, answerId);
@@ -1849,9 +2113,9 @@ var FlowInterpreter = class {
1849
2113
  kind: "terminal",
1850
2114
  context: input.context
1851
2115
  };
1852
- if ((0, import_meta_whatsapp_contracts7.isCrossFlowTarget)(nextNodeId)) return {
2116
+ if ((0, import_meta_whatsapp_contracts8.isCrossFlowTarget)(nextNodeId)) return {
1853
2117
  kind: "cross-flow",
1854
- flowKey: (0, import_meta_whatsapp_contracts7.crossFlowKey)(nextNodeId),
2118
+ flowKey: (0, import_meta_whatsapp_contracts8.crossFlowKey)(nextNodeId),
1855
2119
  context: input.context
1856
2120
  };
1857
2121
  if (!input.graph.nodes[nextNodeId]) return {
@@ -1878,6 +2142,8 @@ var FlowInterpreter = class {
1878
2142
  const visited = [
1879
2143
  input.currentNodeId
1880
2144
  ];
2145
+ const initialNode = input.graph.nodes[input.currentNodeId];
2146
+ if (options?.enterInitialNode && initialNode) await options.onNodeEntered?.(initialNode, input.context);
1881
2147
  let current = input;
1882
2148
  let steps = 0;
1883
2149
  while (steps < maxSteps) {
@@ -1889,11 +2155,14 @@ var FlowInterpreter = class {
1889
2155
  steps
1890
2156
  };
1891
2157
  visited.push(result.nodeId);
2158
+ const enteredNode = current.graph.nodes[result.nodeId];
2159
+ if (enteredNode) await options?.onNodeEntered?.(enteredNode, result.context);
1892
2160
  current = {
1893
2161
  ...current,
1894
2162
  currentNodeId: result.nodeId,
1895
2163
  context: result.context,
1896
- userAnswer: void 0
2164
+ userAnswer: void 0,
2165
+ answerValue: void 0
1897
2166
  };
1898
2167
  }
1899
2168
  return {
@@ -1905,70 +2174,1026 @@ var FlowInterpreter = class {
1905
2174
  }
1906
2175
  };
1907
2176
 
1908
- // src/flows/createSendMediaAction.ts
1909
- function mediaTypeFor2(mimeType) {
1910
- if (mimeType.startsWith("image/")) return "image";
1911
- if (mimeType.startsWith("audio/")) return "audio";
1912
- if (mimeType.startsWith("video/")) return "video";
1913
- return "document";
2177
+ // src/flows/FlowRunner.ts
2178
+ var import_meta_whatsapp_contracts12 = require("@adatechnology/meta-whatsapp-contracts");
2179
+
2180
+ // src/flows/resolveFlowAnswer.ts
2181
+ var import_meta_whatsapp_contracts9 = require("@adatechnology/meta-whatsapp-contracts");
2182
+
2183
+ // src/flows/flowRunner.constant.ts
2184
+ var DEFAULT_START_FLOW_KEY = "main";
2185
+ var DEFAULT_MAX_INVALID_ANSWERS = 2;
2186
+ var DEFAULT_MAX_CROSS_FLOW_JUMPS = 5;
2187
+ var DEFAULT_FLOW_TEXT = {
2188
+ FALLBACK: "N\xE3o entendi. Pode responder de novo?",
2189
+ CHOICE_PROMPT: "Escolha uma op\xE7\xE3o:",
2190
+ LIST_BUTTON_LABEL: "Ver op\xE7\xF5es",
2191
+ SEE_MORE: "Ver mais",
2192
+ NON_TEXT_ANSWER: "Por aqui eu entendo s\xF3 texto. Pode escrever a resposta?",
2193
+ MORE_OPTIONS_TRUNCATED: "\u2026",
2194
+ HANDOFF: "Vou chamar uma pessoa da equipe para continuar por aqui.",
2195
+ HANDOFF_OUT_OF_HOURS: "Nossa equipe est\xE1 fora do hor\xE1rio agora. Sua mensagem ficou registrada e respondemos assim que voltarmos."
2196
+ };
2197
+ var DYNAMIC_CHOICE_MORE_ID = "__more__";
2198
+ var FLOW_RUNTIME_CONTEXT_KEY = "__flow";
2199
+
2200
+ // src/flows/resolveFlowAnswer.ts
2201
+ function isChoiceNode(node) {
2202
+ return node.type === "menu" || node.questionType === "choice";
1914
2203
  }
1915
- __name(mediaTypeFor2, "mediaTypeFor");
1916
- async function sendAttachment(params) {
1917
- const { attachment, channel, to, cache } = params;
1918
- const common = {
1919
- to,
1920
- mimeType: attachment.mimeType,
1921
- filename: attachment.filename,
1922
- caption: attachment.caption ?? void 0
2204
+ __name(isChoiceNode, "isChoiceNode");
2205
+ function keywordRoute(node, answer, isInteractiveReply) {
2206
+ if (isInteractiveReply || typeof node.next !== "object" || !node.next.byKeyword) return void 0;
2207
+ return (0, import_meta_whatsapp_contracts9.matchFlowKeywordRoute)(answer, node.next.byKeyword);
2208
+ }
2209
+ __name(keywordRoute, "keywordRoute");
2210
+ function matchOption(answer, options, isInteractiveReply) {
2211
+ if (isInteractiveReply) return options.some(([id]) => id === answer) ? answer : void 0;
2212
+ return (0, import_meta_whatsapp_contracts9.matchFlowChoice)(answer, options);
2213
+ }
2214
+ __name(matchOption, "matchOption");
2215
+ function resolveChoice(params, answer) {
2216
+ const optionId = matchOption(answer, params.node.options ?? [], params.isInteractiveReply);
2217
+ if (optionId) return {
2218
+ kind: "answer",
2219
+ userAnswer: optionId
1923
2220
  };
1924
- const cacheKey = cache ? {
1925
- flowMediaId: attachment.id,
1926
- senderKey: cache.senderKey
1927
- } : void 0;
1928
- if (cache && cacheKey) {
1929
- const knownMediaId = await cache.store.get(cacheKey);
1930
- if (knownMediaId) {
1931
- try {
1932
- return await channel.sendMedia({
1933
- ...common,
1934
- mediaId: knownMediaId
1935
- });
1936
- } catch {
1937
- await cache.store.clear(cacheKey);
1938
- }
1939
- }
1940
- }
1941
- const buffer = await params.objectStorage.getObject(attachment.uploadId);
1942
- const result = await channel.sendMedia({
1943
- ...common,
1944
- buffer
2221
+ const target = keywordRoute(params.node, answer, params.isInteractiveReply);
2222
+ return target ? {
2223
+ kind: "jump",
2224
+ target
2225
+ } : {
2226
+ kind: "invalid"
2227
+ };
2228
+ }
2229
+ __name(resolveChoice, "resolveChoice");
2230
+ function resolveDynamicChoice(params, answer) {
2231
+ const optionId = matchOption(answer, params.dynamicOptions ?? [], params.isInteractiveReply);
2232
+ if (optionId === DYNAMIC_CHOICE_MORE_ID) return {
2233
+ kind: "see-more"
2234
+ };
2235
+ if (optionId) return {
2236
+ kind: "answer",
2237
+ userAnswer: optionId
2238
+ };
2239
+ const target = keywordRoute(params.node, answer, params.isInteractiveReply);
2240
+ return target ? {
2241
+ kind: "jump",
2242
+ target
2243
+ } : {
2244
+ kind: "invalid"
2245
+ };
2246
+ }
2247
+ __name(resolveDynamicChoice, "resolveDynamicChoice");
2248
+ function resolveQuestion(params, answer) {
2249
+ const target = keywordRoute(params.node, answer, params.isInteractiveReply);
2250
+ if (target) return {
2251
+ kind: "jump",
2252
+ target
2253
+ };
2254
+ const result = (0, import_meta_whatsapp_contracts9.validateFlowAnswer)({
2255
+ node: params.node,
2256
+ answer,
2257
+ context: params.context,
2258
+ clock: params.clock
1945
2259
  });
1946
- if (cache && cacheKey && result.mediaId) await cache.store.set({
1947
- ...cacheKey,
1948
- mediaId: result.mediaId
2260
+ if (!result.isValid) return {
2261
+ kind: "invalid",
2262
+ rejection: result.rejection
2263
+ };
2264
+ return {
2265
+ kind: "answer",
2266
+ userAnswer: answer,
2267
+ value: result.value
2268
+ };
2269
+ }
2270
+ __name(resolveQuestion, "resolveQuestion");
2271
+ function resolveFlowAnswer(params) {
2272
+ if (params.answer === void 0) return {
2273
+ kind: "invalid"
2274
+ };
2275
+ if (params.node.type === "dynamic_choice") return resolveDynamicChoice(params, params.answer);
2276
+ if (isChoiceNode(params.node)) return resolveChoice(params, params.answer);
2277
+ return resolveQuestion(params, params.answer);
2278
+ }
2279
+ __name(resolveFlowAnswer, "resolveFlowAnswer");
2280
+
2281
+ // src/flows/FlowQuestionRenderer.ts
2282
+ var import_meta_whatsapp_contracts11 = require("@adatechnology/meta-whatsapp-contracts");
2283
+
2284
+ // src/flows/buildFlowChoiceMessage.ts
2285
+ var import_meta_whatsapp_contracts10 = require("@adatechnology/meta-whatsapp-contracts");
2286
+ function groupSections(options) {
2287
+ const sections = [];
2288
+ for (const option of options) {
2289
+ const title = option.section?.trim() || void 0;
2290
+ const existing = sections.find((section) => section.title === title);
2291
+ if (existing) existing.rows.push(option);
2292
+ else sections.push({
2293
+ title,
2294
+ rows: [
2295
+ option
2296
+ ]
2297
+ });
2298
+ }
2299
+ return sections.map((section) => ({
2300
+ ...section.title ? {
2301
+ title: section.title
2302
+ } : {},
2303
+ rows: section.rows.map((row) => ({
2304
+ id: row.id,
2305
+ title: row.title,
2306
+ ...row.description ? {
2307
+ description: row.description
2308
+ } : {}
2309
+ }))
2310
+ }));
2311
+ }
2312
+ __name(groupSections, "groupSections");
2313
+ function asNumberedText(params) {
2314
+ const lines = params.options.map((option, index2) => {
2315
+ const description = option.description ? ` \u2014 ${option.description}` : "";
2316
+ return `${index2 + 1}. ${option.title}${description}`;
1949
2317
  });
1950
- return result;
2318
+ const limit = import_meta_whatsapp_contracts10.WHATSAPP_CHOICE_LIMIT.TEXT_BODY_LENGTH;
2319
+ const full = `${params.body}
2320
+
2321
+ ${lines.join("\n")}`;
2322
+ if (Array.from(full).length <= limit) return {
2323
+ kind: "text",
2324
+ body: full
2325
+ };
2326
+ const truncated = `
2327
+ ${DEFAULT_FLOW_TEXT.MORE_OPTIONS_TRUNCATED}`;
2328
+ let body = `${params.body}
2329
+ `;
2330
+ for (const line of lines) {
2331
+ const candidate = `${body}
2332
+ ${line}`;
2333
+ if (Array.from(candidate).length + truncated.length > limit) break;
2334
+ body = candidate;
2335
+ }
2336
+ const withMarker = `${body}${truncated}`;
2337
+ return {
2338
+ kind: "text",
2339
+ body: Array.from(withMarker).slice(0, limit).join("")
2340
+ };
1951
2341
  }
1952
- __name(sendAttachment, "sendAttachment");
1953
- function createSendMediaAction(params) {
1954
- return async ({ node, session, channel }) => {
1955
- if (!session.flowKey) return;
1956
- const location = {
1957
- companyId: session.companyId,
1958
- flowKey: session.flowKey,
1959
- nodeId: node.id
2342
+ __name(asNumberedText, "asNumberedText");
2343
+ function buildFlowChoiceMessage(params) {
2344
+ const isPlain = params.options.every((option) => !option.description && !option.section);
2345
+ if (isPlain && params.options.length <= import_meta_whatsapp_contracts10.WHATSAPP_CHOICE_LIMIT.BUTTONS) {
2346
+ const buttons = {
2347
+ kind: "buttons",
2348
+ body: params.body,
2349
+ buttons: params.options.map((option) => ({
2350
+ id: option.id,
2351
+ title: option.title
2352
+ }))
1960
2353
  };
1961
- const attachments = await params.flowMediaRepository.listActive(location);
1962
- for (const attachment of attachments) {
1963
- try {
1964
- const { externalMessageId } = await sendAttachment({
1965
- attachment,
1966
- channel,
1967
- to: session.whatsappNumber,
1968
- objectStorage: params.objectStorage,
1969
- ...params.mediaIdCache ? {
1970
- cache: params.mediaIdCache
1971
- } : {}
2354
+ if ((0, import_meta_whatsapp_contracts10.listInteractiveLimitViolations)(buttons).length === 0) return {
2355
+ kind: "interactive",
2356
+ interactive: buttons
2357
+ };
2358
+ }
2359
+ const list = {
2360
+ kind: "list",
2361
+ body: params.body,
2362
+ buttonLabel: params.listButtonLabel,
2363
+ sections: groupSections(params.options)
2364
+ };
2365
+ if ((0, import_meta_whatsapp_contracts10.listInteractiveLimitViolations)(list).length === 0) return {
2366
+ kind: "interactive",
2367
+ interactive: list
2368
+ };
2369
+ return asNumberedText(params);
2370
+ }
2371
+ __name(buildFlowChoiceMessage, "buildFlowChoiceMessage");
2372
+
2373
+ // src/flows/flowRuntimeState.ts
2374
+ function runtimeOf(context) {
2375
+ const state = context[FLOW_RUNTIME_CONTEXT_KEY];
2376
+ return state !== null && typeof state === "object" ? state : {};
2377
+ }
2378
+ __name(runtimeOf, "runtimeOf");
2379
+ function withRuntime(context, state) {
2380
+ return {
2381
+ ...context,
2382
+ [FLOW_RUNTIME_CONTEXT_KEY]: state
2383
+ };
2384
+ }
2385
+ __name(withRuntime, "withRuntime");
2386
+
2387
+ // src/flows/FlowQuestionRenderer.ts
2388
+ var FlowQuestionRenderer = class {
2389
+ static {
2390
+ __name(this, "FlowQuestionRenderer");
2391
+ }
2392
+ config;
2393
+ providers = /* @__PURE__ */ new Map();
2394
+ constructor(config) {
2395
+ this.config = config;
2396
+ for (const [key, provider] of Object.entries(config.dynamicChoiceProviders ?? {})) this.providers.set(key, provider);
2397
+ }
2398
+ registerDynamicChoiceProvider(key, provider) {
2399
+ this.providers.set(key, provider);
2400
+ }
2401
+ interpolate(text2, variables) {
2402
+ return (0, import_meta_whatsapp_contracts11.interpolateFlowText)(text2, variables, this.config.formatValue ? {
2403
+ formatValue: this.config.formatValue
2404
+ } : {});
2405
+ }
2406
+ async prepare(params) {
2407
+ const { node, context } = params;
2408
+ const variables = {
2409
+ ...context,
2410
+ ...params.variables
2411
+ };
2412
+ const body = this.interpolate(node.question ?? this.config.choicePrompt ?? DEFAULT_FLOW_TEXT.CHOICE_PROMPT, variables);
2413
+ const listButtonLabel = node.listButtonLabel ?? this.config.listButtonLabel ?? DEFAULT_FLOW_TEXT.LIST_BUTTON_LABEL;
2414
+ if (node.type === "dynamic_choice") {
2415
+ const options = await this.loadDynamicOptions(params);
2416
+ const shown = options.map((option) => [
2417
+ option.id,
2418
+ option.title
2419
+ ]);
2420
+ const state = {
2421
+ ...runtimeOf(context),
2422
+ dynamic: {
2423
+ nodeId: node.id,
2424
+ page: params.page,
2425
+ options: shown
2426
+ }
2427
+ };
2428
+ return {
2429
+ message: buildFlowChoiceMessage({
2430
+ body,
2431
+ options,
2432
+ listButtonLabel
2433
+ }),
2434
+ context: withRuntime(context, state)
2435
+ };
2436
+ }
2437
+ if (isChoiceNode(node) && (node.options?.length ?? 0) > 0) {
2438
+ const options = (node.options ?? []).map(([id, title]) => {
2439
+ const detail = node.optionDetails?.[id];
2440
+ return {
2441
+ id,
2442
+ title: this.interpolate(title, variables),
2443
+ ...detail?.description ? {
2444
+ description: this.interpolate(detail.description, variables)
2445
+ } : {},
2446
+ ...detail?.section ? {
2447
+ section: detail.section
2448
+ } : {}
2449
+ };
2450
+ });
2451
+ return {
2452
+ message: buildFlowChoiceMessage({
2453
+ body,
2454
+ options,
2455
+ listButtonLabel
2456
+ }),
2457
+ context
2458
+ };
2459
+ }
2460
+ if (!node.question) return {
2461
+ context
2462
+ };
2463
+ return {
2464
+ message: {
2465
+ kind: "text",
2466
+ body
2467
+ },
2468
+ context
2469
+ };
2470
+ }
2471
+ async loadDynamicOptions(params) {
2472
+ const { node } = params;
2473
+ const provider = node.choiceProvider ? this.providers.get(node.choiceProvider) : void 0;
2474
+ if (!provider) throw new import_meta_whatsapp_contracts11.FlowRunnerError("provider-missing", node.choiceProvider ?? node.id);
2475
+ const pageSize = import_meta_whatsapp_contracts11.WHATSAPP_CHOICE_LIMIT.LIST_ROWS - 1;
2476
+ const result = await provider({
2477
+ node,
2478
+ session: params.session,
2479
+ context: params.context,
2480
+ page: params.page,
2481
+ pageSize
2482
+ });
2483
+ const options = result.options.slice(0, pageSize).map((option) => ({
2484
+ id: option.id,
2485
+ title: option.title,
2486
+ ...option.description ? {
2487
+ description: option.description
2488
+ } : {}
2489
+ }));
2490
+ const seeMore = this.config.seeMoreLabel ?? DEFAULT_FLOW_TEXT.SEE_MORE;
2491
+ return result.hasMore ? [
2492
+ ...options,
2493
+ {
2494
+ id: DYNAMIC_CHOICE_MORE_ID,
2495
+ title: seeMore
2496
+ }
2497
+ ] : options;
2498
+ }
2499
+ };
2500
+
2501
+ // src/flows/readFlowInbound.ts
2502
+ function readFlowInbound(message) {
2503
+ const reply = message.interactive?.button_reply?.id ?? message.interactive?.list_reply?.id;
2504
+ if (reply !== void 0) return {
2505
+ kind: "reply",
2506
+ answer: reply
2507
+ };
2508
+ if (message.text?.body !== void 0) return {
2509
+ kind: "text",
2510
+ answer: message.text.body
2511
+ };
2512
+ if (message.button?.text !== void 0) return {
2513
+ kind: "text",
2514
+ answer: message.button.text
2515
+ };
2516
+ return {
2517
+ kind: "unsupported"
2518
+ };
2519
+ }
2520
+ __name(readFlowInbound, "readFlowInbound");
2521
+
2522
+ // src/flows/FlowRunner.ts
2523
+ function contactVariables(profileName) {
2524
+ if (!profileName) return {};
2525
+ return {
2526
+ contactName: profileName,
2527
+ contactFirstName: profileName.trim().split(/\s+/)[0] ?? profileName
2528
+ };
2529
+ }
2530
+ __name(contactVariables, "contactVariables");
2531
+ function resolveFlowTimeZone(config) {
2532
+ const businessHours = config.handoff?.businessHours;
2533
+ const timeZone = config.timeZone ?? (typeof businessHours === "object" ? businessHours.timeZone : void 0);
2534
+ if (!timeZone) throw new import_meta_whatsapp_contracts12.ConfigMissingError("features.flowRunner.timeZone");
2535
+ new Intl.DateTimeFormat("en-US", {
2536
+ timeZone
2537
+ });
2538
+ return timeZone;
2539
+ }
2540
+ __name(resolveFlowTimeZone, "resolveFlowTimeZone");
2541
+ var FlowRunner = class {
2542
+ static {
2543
+ __name(this, "FlowRunner");
2544
+ }
2545
+ dependencies;
2546
+ renderer;
2547
+ timeZone;
2548
+ // Variáveis da mensagem em curso, por sessão: é como a action `handoff` (que só recebe a sessão)
2549
+ // enxerga o nome do contato sem que ele precise ir para o contexto gravado.
2550
+ turnVariables = /* @__PURE__ */ new WeakMap();
2551
+ constructor(dependencies) {
2552
+ this.dependencies = dependencies;
2553
+ this.renderer = new FlowQuestionRenderer(dependencies.config);
2554
+ this.timeZone = resolveFlowTimeZone(dependencies.config);
2555
+ }
2556
+ registerDynamicChoiceProvider(key, provider) {
2557
+ this.renderer.registerDynamicChoiceProvider(key, provider);
2558
+ }
2559
+ /**
2560
+ * Variáveis para `{{chave}}`. As do host (`resolveVariables`, `contactName`, `contactFirstName`)
2561
+ * vencem as respostas do cliente: um `contextKey` chamado `contactName` não pode trocar o nome que
2562
+ * o sistema conhece pelo que o cliente digitou.
2563
+ */
2564
+ variablesFor(params) {
2565
+ return {
2566
+ ...params.context,
2567
+ ...this.turnVariables.get(params.session) ?? {}
2568
+ };
2569
+ }
2570
+ /** Atende uma mensagem. Um turno por conversa de cada vez (`lock`); reentrega da mesma mensagem é ignorada. */
2571
+ handle(params) {
2572
+ const key = {
2573
+ companyId: params.companyId,
2574
+ whatsappNumber: params.message.from
2575
+ };
2576
+ return this.dependencies.lock.withLock(key, () => this.handleLocked(params));
2577
+ }
2578
+ /** Abre um fluxo para a conversa sem esperar mensagem — ex.: ao devolver a conversa ao bot. */
2579
+ start(params) {
2580
+ const key = {
2581
+ companyId: params.companyId,
2582
+ whatsappNumber: params.whatsappNumber
2583
+ };
2584
+ return this.dependencies.lock.withLock(key, async () => {
2585
+ const row = await this.dependencies.sessionRepository.getContext(params.companyId, params.whatsappNumber);
2586
+ if (!row) return "no-session";
2587
+ const turn = await this.openTurn({
2588
+ companyId: params.companyId,
2589
+ session: toSessionContract(row),
2590
+ ...params.profileName ? {
2591
+ profileName: params.profileName
2592
+ } : {}
2593
+ });
2594
+ const graph = await this.loadGraph(params.companyId, params.flowKey ?? this.startFlowKey());
2595
+ if (!graph) return "no-flow";
2596
+ turn.isClaimed = true;
2597
+ return this.guard(turn, async () => {
2598
+ await this.runFrom(turn, {
2599
+ graph,
2600
+ nodeId: graph.startNodeId,
2601
+ context: {
2602
+ ...turn.session.context
2603
+ },
2604
+ enterInitialNode: true
2605
+ });
2606
+ return "handled";
2607
+ });
2608
+ });
2609
+ }
2610
+ async handleLocked(params) {
2611
+ const row = await this.dependencies.sessionRepository.getContext(params.companyId, params.message.from);
2612
+ if (!row) return "no-session";
2613
+ if (row.mode === "human") return "human-mode";
2614
+ const session = toSessionContract(row);
2615
+ if (runtimeOf(session.context).lastInboundId === params.message.id) return "duplicate";
2616
+ const turn = await this.openTurn({
2617
+ companyId: params.companyId,
2618
+ session,
2619
+ inboundId: params.message.id,
2620
+ ...params.profileName ? {
2621
+ profileName: params.profileName
2622
+ } : {}
2623
+ });
2624
+ return this.guard(turn, () => this.route(turn, readFlowInbound(params.message)));
2625
+ }
2626
+ async route(turn, inbound) {
2627
+ const globalTarget = inbound.kind === "text" ? this.globalKeywordTarget(inbound.answer) : void 0;
2628
+ if (globalTarget) return this.applyGlobalTarget(turn, globalTarget);
2629
+ const whileAwaitingHuman = this.dependencies.config.whileAwaitingHuman ?? "silent";
2630
+ if (turn.session.humanRequestedAt && !turn.session.currentNodeId && whileAwaitingHuman === "silent") {
2631
+ return "awaiting-human";
2632
+ }
2633
+ const savedFlowKey = turn.session.flowKey;
2634
+ const savedGraph = await this.loadGraph(turn.companyId, savedFlowKey ?? this.startFlowKey());
2635
+ const isStale = !savedGraph && savedFlowKey !== null && savedFlowKey !== this.startFlowKey();
2636
+ const graph = savedGraph ?? (isStale ? await this.loadGraph(turn.companyId, this.startFlowKey()) : void 0);
2637
+ if (!graph) return "no-flow";
2638
+ await this.claim(turn);
2639
+ if (isStale) await this.report(turn, savedFlowKey, turn.session.currentNodeId, "cross-flow", new import_meta_whatsapp_contracts12.FlowRunnerError("flow-not-found", savedFlowKey));
2640
+ const node = !isStale && turn.session.currentNodeId ? graph.nodes[turn.session.currentNodeId] : void 0;
2641
+ const context = {
2642
+ ...turn.session.context
2643
+ };
2644
+ if (node) {
2645
+ await this.answerNode({
2646
+ turn,
2647
+ graph,
2648
+ node,
2649
+ context,
2650
+ inbound
2651
+ });
2652
+ return "handled";
2653
+ }
2654
+ const start = graph.nodes[graph.startNodeId];
2655
+ const target = start && inbound.kind !== "unsupported" ? this.keywordJumpAtStart(start, inbound) : void 0;
2656
+ if (target) await this.jumpTo(turn, graph, target, context);
2657
+ else await this.runFrom(turn, {
2658
+ graph,
2659
+ nodeId: graph.startNodeId,
2660
+ context,
2661
+ enterInitialNode: true
2662
+ });
2663
+ return "handled";
2664
+ }
2665
+ async guard(turn, work) {
2666
+ try {
2667
+ return await work();
2668
+ } catch (error) {
2669
+ if (!turn.isClaimed) throw error;
2670
+ await this.report(turn, turn.session.flowKey, turn.session.currentNodeId, "turn", error);
2671
+ return "handled";
2672
+ }
2673
+ }
2674
+ /** Primeira escrita do turno: grava o id da mensagem antes de qualquer efeito externo. */
2675
+ async claim(turn) {
2676
+ if (turn.isClaimed) return;
2677
+ await this.save(turn, {
2678
+ flowKey: turn.session.flowKey,
2679
+ nodeId: turn.session.currentNodeId,
2680
+ context: {
2681
+ ...turn.session.context
2682
+ }
2683
+ });
2684
+ turn.isClaimed = true;
2685
+ }
2686
+ async openTurn(params) {
2687
+ const { session, profileName } = params;
2688
+ const resolver = this.dependencies.config.resolveVariables;
2689
+ const hostVariables = resolver ? await resolver({
2690
+ session,
2691
+ ...profileName ? {
2692
+ profileName
2693
+ } : {}
2694
+ }) : {};
2695
+ const baseVariables = {
2696
+ ...contactVariables(profileName),
2697
+ ...hostVariables
2698
+ };
2699
+ this.turnVariables.set(session, baseVariables);
2700
+ return {
2701
+ companyId: params.companyId,
2702
+ session,
2703
+ baseVariables,
2704
+ ...params.inboundId ? {
2705
+ inboundId: params.inboundId
2706
+ } : {},
2707
+ isClaimed: false
2708
+ };
2709
+ }
2710
+ startFlowKey() {
2711
+ return this.dependencies.config.startFlowKey ?? DEFAULT_START_FLOW_KEY;
2712
+ }
2713
+ clock() {
2714
+ const { config } = this.dependencies;
2715
+ return {
2716
+ now: config.now?.() ?? /* @__PURE__ */ new Date(),
2717
+ locale: config.dateLocale ?? import_meta_whatsapp_contracts12.FLOW_DATE_LOCALE_PT_BR,
2718
+ timeZone: this.timeZone
2719
+ };
2720
+ }
2721
+ loadGraph(companyId, flowKey) {
2722
+ return this.dependencies.flowGraphRepository.get(companyId, flowKey);
2723
+ }
2724
+ globalKeywordTarget(answer) {
2725
+ const keywords = this.dependencies.config.globalKeywords ?? [];
2726
+ return keywords.find((entry) => (0, import_meta_whatsapp_contracts12.matchesFlowKeyword)(answer, entry.keywords))?.target;
2727
+ }
2728
+ keywordJumpAtStart(start, inbound) {
2729
+ if (inbound.kind === "unsupported") return void 0;
2730
+ const decision = resolveFlowAnswer({
2731
+ node: start,
2732
+ answer: inbound.answer,
2733
+ isInteractiveReply: inbound.kind === "reply",
2734
+ context: {},
2735
+ clock: this.clock()
2736
+ });
2737
+ return decision.kind === "jump" ? decision.target : void 0;
2738
+ }
2739
+ /**
2740
+ * Palavra global vale mesmo com a conversa aguardando atendimento. Reiniciar NÃO tira o pedido da
2741
+ * fila (`humanRequestedAt` continua): a equipe ainda responde, e o cliente pode usar o bot enquanto
2742
+ * espera; quando o fluxo terminar, o runner volta ao silêncio.
2743
+ */
2744
+ async applyGlobalTarget(turn, target) {
2745
+ const context = withRuntime({
2746
+ ...turn.session.context
2747
+ }, {});
2748
+ if (target === "handoff") {
2749
+ await this.claim(turn);
2750
+ await this.handOff(turn, context);
2751
+ return "handled";
2752
+ }
2753
+ const flowKey = target === "restart" ? this.startFlowKey() : (0, import_meta_whatsapp_contracts12.crossFlowKey)(target);
2754
+ const graph = await this.loadGraph(turn.companyId, flowKey);
2755
+ if (!graph) return "no-flow";
2756
+ await this.claim(turn);
2757
+ await this.runFrom(turn, {
2758
+ graph,
2759
+ nodeId: graph.startNodeId,
2760
+ context,
2761
+ enterInitialNode: true
2762
+ });
2763
+ return "handled";
2764
+ }
2765
+ async answerNode(params) {
2766
+ const { turn, graph, node, context, inbound } = params;
2767
+ const runtime = runtimeOf(context);
2768
+ const dynamic = runtime.dynamic?.nodeId === node.id ? runtime.dynamic : void 0;
2769
+ const page = dynamic?.page ?? 0;
2770
+ if (inbound.kind === "unsupported") {
2771
+ const text2 = this.dependencies.config.nonTextAnswerMessage ?? DEFAULT_FLOW_TEXT.NON_TEXT_ANSWER;
2772
+ await this.say(turn, text2, context);
2773
+ return this.awaitAnswer(turn, graph, node, context, page);
2774
+ }
2775
+ const decision = resolveFlowAnswer({
2776
+ node,
2777
+ answer: inbound.answer,
2778
+ isInteractiveReply: inbound.kind === "reply",
2779
+ context,
2780
+ clock: this.clock(),
2781
+ ...dynamic ? {
2782
+ dynamicOptions: dynamic.options
2783
+ } : {}
2784
+ });
2785
+ if (decision.kind === "jump") return this.jumpTo(turn, graph, decision.target, withRuntime(context, {}));
2786
+ if (decision.kind === "see-more") return this.awaitAnswer(turn, graph, node, context, page + 1);
2787
+ if (decision.kind === "invalid" && this.followsDefaultWhenUnmatched(node)) {
2788
+ return this.runFrom(turn, {
2789
+ graph,
2790
+ nodeId: node.id,
2791
+ context: withRuntime(context, {}),
2792
+ userAnswer: inbound.answer,
2793
+ enterInitialNode: false
2794
+ });
2795
+ }
2796
+ if (decision.kind === "invalid") return this.handleInvalid(turn, graph, node, context, decision.rejection);
2797
+ await this.runFrom(turn, {
2798
+ graph,
2799
+ nodeId: node.id,
2800
+ context: withRuntime(context, {}),
2801
+ userAnswer: decision.userAnswer,
2802
+ ...decision.value !== void 0 ? {
2803
+ answerValue: decision.value
2804
+ } : {},
2805
+ enterInitialNode: false
2806
+ });
2807
+ }
2808
+ followsDefaultWhenUnmatched(node) {
2809
+ if (!isChoiceNode(node)) return false;
2810
+ return (node.unmatchedChoice ?? this.dependencies.config.unmatchedChoice ?? "reask") === "default";
2811
+ }
2812
+ async handleInvalid(turn, graph, node, context, rejection) {
2813
+ const runtime = runtimeOf(context);
2814
+ const attempts = (runtime.invalidAnswers ?? 0) + 1;
2815
+ const limit = node.maxInvalidAnswers ?? this.dependencies.config.maxInvalidAnswers ?? DEFAULT_MAX_INVALID_ANSWERS;
2816
+ if (attempts >= limit) return this.handOff(turn, withRuntime(context, {}));
2817
+ const updated = withRuntime(context, {
2818
+ ...runtime,
2819
+ invalidAnswers: attempts
2820
+ });
2821
+ await this.say(turn, this.fallbackText(node, rejection), updated);
2822
+ await this.awaitAnswer(turn, graph, node, updated, runtime.dynamic?.nodeId === node.id ? runtime.dynamic.page : 0);
2823
+ }
2824
+ fallbackText(node, rejection) {
2825
+ const { config } = this.dependencies;
2826
+ return node.fallbackMessage ?? (rejection ? config.rejectionMessages?.[rejection] : void 0) ?? config.defaultFallbackMessage ?? DEFAULT_FLOW_TEXT.FALLBACK;
2827
+ }
2828
+ async handOff(turn, context) {
2829
+ const isWithinHours = await this.dependencies.handoff.request({
2830
+ companyId: turn.companyId,
2831
+ whatsappNumber: turn.session.whatsappNumber,
2832
+ variables: {
2833
+ ...context,
2834
+ ...turn.baseVariables
2835
+ }
2836
+ });
2837
+ await this.save(turn, {
2838
+ flowKey: null,
2839
+ nodeId: null,
2840
+ context: {
2841
+ ...context,
2842
+ handoffWithinBusinessHours: isWithinHours
2843
+ }
2844
+ });
2845
+ }
2846
+ async jumpTo(turn, graph, target, context) {
2847
+ if ((0, import_meta_whatsapp_contracts12.isCrossFlowTarget)(target)) {
2848
+ const targetGraph = await this.loadGraph(turn.companyId, (0, import_meta_whatsapp_contracts12.crossFlowKey)(target));
2849
+ if (!targetGraph) return this.reportMissingFlow(turn, graph.key, target, context);
2850
+ return this.runFrom(turn, {
2851
+ graph: targetGraph,
2852
+ nodeId: targetGraph.startNodeId,
2853
+ context,
2854
+ enterInitialNode: true
2855
+ });
2856
+ }
2857
+ return this.runFrom(turn, {
2858
+ graph,
2859
+ nodeId: target,
2860
+ context,
2861
+ enterInitialNode: true
2862
+ });
2863
+ }
2864
+ async runFrom(turn, initial) {
2865
+ const maxJumps = this.dependencies.config.maxCrossFlowJumps ?? DEFAULT_MAX_CROSS_FLOW_JUMPS;
2866
+ let params = initial;
2867
+ for (let jump = 0; jump <= maxJumps; jump++) {
2868
+ const result = await this.dependencies.interpreter.run({
2869
+ graph: params.graph,
2870
+ currentNodeId: params.nodeId,
2871
+ ...params.userAnswer !== void 0 ? {
2872
+ userAnswer: params.userAnswer
2873
+ } : {},
2874
+ ...params.answerValue !== void 0 ? {
2875
+ answerValue: params.answerValue
2876
+ } : {},
2877
+ context: params.context,
2878
+ session: turn.session,
2879
+ channel: this.dependencies.channel
2880
+ }, {
2881
+ enterInitialNode: params.enterInitialNode,
2882
+ onNodeEntered: /* @__PURE__ */ __name(async (node, context) => {
2883
+ if (node.directMessage) await this.say(turn, node.directMessage, context);
2884
+ }, "onNodeEntered")
2885
+ });
2886
+ if (result.kind === "awaiting-answer") {
2887
+ const node = params.graph.nodes[result.nodeId];
2888
+ if (node) return this.awaitAnswer(turn, params.graph, node, result.context, 0);
2889
+ return this.save(turn, {
2890
+ flowKey: null,
2891
+ nodeId: null,
2892
+ context: result.context
2893
+ });
2894
+ }
2895
+ if (result.kind === "terminal") return this.save(turn, {
2896
+ flowKey: null,
2897
+ nodeId: null,
2898
+ context: result.context
2899
+ });
2900
+ if (result.kind === "max-steps-exceeded") {
2901
+ await this.save(turn, {
2902
+ flowKey: null,
2903
+ nodeId: null,
2904
+ context: result.context
2905
+ });
2906
+ return this.report(turn, params.graph.key, null, "max-steps", new import_meta_whatsapp_contracts12.FlowRunnerError("cycle", result.visited.join(" -> ")));
2907
+ }
2908
+ const target = await this.loadGraph(turn.companyId, result.flowKey);
2909
+ if (!target) return this.reportMissingFlow(turn, params.graph.key, result.flowKey, result.context);
2910
+ params = {
2911
+ graph: target,
2912
+ nodeId: target.startNodeId,
2913
+ context: result.context,
2914
+ enterInitialNode: true
2915
+ };
2916
+ }
2917
+ await this.save(turn, {
2918
+ flowKey: null,
2919
+ nodeId: null,
2920
+ context: params.context
2921
+ });
2922
+ return this.report(turn, params.graph.key, null, "cross-flow", new import_meta_whatsapp_contracts12.FlowRunnerError("too-many-jumps", params.graph.key));
2923
+ }
2924
+ /** Grava a posição no nó e pergunta. Para `dynamic_choice`, busca a página antes de gravar. */
2925
+ async awaitAnswer(turn, graph, node, context, page) {
2926
+ try {
2927
+ const { message, context: renderedContext } = await this.renderer.prepare({
2928
+ session: turn.session,
2929
+ variables: turn.baseVariables,
2930
+ node,
2931
+ context,
2932
+ page
2933
+ });
2934
+ await this.save(turn, {
2935
+ flowKey: graph.key,
2936
+ nodeId: node.id,
2937
+ context: renderedContext
2938
+ });
2939
+ if (message) await this.send(turn, message);
2940
+ } catch (error) {
2941
+ await this.report(turn, graph.key, node.id, "render", error);
2942
+ }
2943
+ }
2944
+ async say(turn, template, context) {
2945
+ const body = this.renderer.interpolate(template, {
2946
+ ...context,
2947
+ ...turn.baseVariables
2948
+ });
2949
+ if (body.trim().length > 0) await this.send(turn, {
2950
+ kind: "text",
2951
+ body
2952
+ });
2953
+ }
2954
+ async send(turn, message) {
2955
+ const common = {
2956
+ companyId: turn.companyId,
2957
+ whatsappNumber: turn.session.whatsappNumber,
2958
+ sender: "bot",
2959
+ startState: this.dependencies.startState
2960
+ };
2961
+ if (message.kind === "text") await this.dependencies.sendMessage.sendText({
2962
+ ...common,
2963
+ body: message.body
2964
+ });
2965
+ else await this.dependencies.sendMessage.sendInteractive({
2966
+ ...common,
2967
+ interactive: message.interactive
2968
+ });
2969
+ }
2970
+ save(turn, progress) {
2971
+ const runtime = runtimeOf(progress.context);
2972
+ const context = turn.inboundId ? withRuntime(progress.context, {
2973
+ ...runtime,
2974
+ lastInboundId: turn.inboundId
2975
+ }) : progress.context;
2976
+ return this.dependencies.sessionRepository.saveFlowProgress(turn.companyId, turn.session.whatsappNumber, {
2977
+ flowKey: progress.flowKey,
2978
+ currentNodeId: progress.nodeId,
2979
+ context
2980
+ });
2981
+ }
2982
+ async reportMissingFlow(turn, fromFlowKey, target, context) {
2983
+ await this.save(turn, {
2984
+ flowKey: null,
2985
+ nodeId: null,
2986
+ context
2987
+ });
2988
+ await this.report(turn, fromFlowKey, null, "cross-flow", new import_meta_whatsapp_contracts12.FlowRunnerError("flow-not-found", target));
2989
+ }
2990
+ /**
2991
+ * Nunca relança: só é chamado depois de o turno ter sido gravado, e relançar faria a fila repetir
2992
+ * uma mensagem já marcada como tratada. Sem gancho, o erro é descartado (a conversa fica no último
2993
+ * ponto gravado e a próxima mensagem do cliente segue dali); gancho que falha também não derruba.
2994
+ */
2995
+ async report(turn, flowKey, nodeId, stage, error) {
2996
+ const details = {
2997
+ companyId: turn.companyId,
2998
+ whatsappNumber: turn.session.whatsappNumber,
2999
+ flowKey,
3000
+ nodeId,
3001
+ stage
3002
+ };
3003
+ try {
3004
+ await this.dependencies.hooks?.onFlowRunnerError?.(error, details);
3005
+ } catch {
3006
+ }
3007
+ }
3008
+ };
3009
+
3010
+ // src/flows/FlowHandoff.ts
3011
+ var import_meta_whatsapp_contracts13 = require("@adatechnology/meta-whatsapp-contracts");
3012
+ function readParam(node, key) {
3013
+ const value = node?.actionParams?.[key];
3014
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
3015
+ }
3016
+ __name(readParam, "readParam");
3017
+ var FlowHandoff = class {
3018
+ static {
3019
+ __name(this, "FlowHandoff");
3020
+ }
3021
+ dependencies;
3022
+ constructor(dependencies) {
3023
+ this.dependencies = dependencies;
3024
+ }
3025
+ /** Devolve se caiu dentro do horário — vai para o contexto como `handoffWithinBusinessHours`. */
3026
+ async request(params) {
3027
+ const { requestHuman, sendMessage, startState, interpolation } = this.dependencies;
3028
+ try {
3029
+ await requestHuman.execute({
3030
+ companyId: params.companyId,
3031
+ whatsappNumber: params.whatsappNumber
3032
+ });
3033
+ } catch (error) {
3034
+ await this.reportFailure(error, params);
3035
+ }
3036
+ const isWithinHours = await this.isWithinHours(params.companyId);
3037
+ const template = this.messageFor(isWithinHours, params.node);
3038
+ await sendMessage.sendText({
3039
+ companyId: params.companyId,
3040
+ whatsappNumber: params.whatsappNumber,
3041
+ body: (0, import_meta_whatsapp_contracts13.interpolateFlowText)(template, params.variables, interpolation),
3042
+ sender: "bot",
3043
+ startState
3044
+ });
3045
+ return isWithinHours;
3046
+ }
3047
+ /**
3048
+ * Handler do `actionKind: 'handoff'`. `actionParams.message` e `actionParams.outOfHoursMessage`
3049
+ * sobrescrevem os textos do runner para aquele nó.
3050
+ */
3051
+ createActionHandler(resolveVariables) {
3052
+ return async ({ node, session, context }) => {
3053
+ const isWithinHours = await this.request({
3054
+ companyId: session.companyId,
3055
+ whatsappNumber: session.whatsappNumber,
3056
+ variables: resolveVariables({
3057
+ session,
3058
+ context
3059
+ }),
3060
+ node
3061
+ });
3062
+ return {
3063
+ context: {
3064
+ handoffWithinBusinessHours: isWithinHours
3065
+ }
3066
+ };
3067
+ };
3068
+ }
3069
+ async reportFailure(error, params) {
3070
+ try {
3071
+ await this.dependencies.hooks?.onFlowRunnerError?.(error, {
3072
+ companyId: params.companyId,
3073
+ whatsappNumber: params.whatsappNumber,
3074
+ flowKey: null,
3075
+ nodeId: params.node?.id ?? null,
3076
+ stage: "handoff"
3077
+ });
3078
+ } catch {
3079
+ }
3080
+ }
3081
+ async isWithinHours(companyId) {
3082
+ const source = this.dependencies.config.businessHours;
3083
+ const hours = typeof source === "function" ? await source(companyId) : source;
3084
+ return hours ? (0, import_meta_whatsapp_contracts13.isWithinBusinessHours)(hours, this.dependencies.now()) : true;
3085
+ }
3086
+ messageFor(isWithinHours, node) {
3087
+ const { config } = this.dependencies;
3088
+ const inHours = readParam(node, "message") ?? config.message ?? DEFAULT_FLOW_TEXT.HANDOFF;
3089
+ if (isWithinHours) return inHours;
3090
+ return readParam(node, "outOfHoursMessage") ?? config.outOfHoursMessage ?? readParam(node, "message") ?? config.message ?? DEFAULT_FLOW_TEXT.HANDOFF_OUT_OF_HOURS;
3091
+ }
3092
+ };
3093
+
3094
+ // src/flows/flowTurnLock.ts
3095
+ var import_drizzle_orm7 = require("drizzle-orm");
3096
+ function lockName(key) {
3097
+ return `meta_whatsapp_flow:${key.companyId}:${key.whatsappNumber}`;
3098
+ }
3099
+ __name(lockName, "lockName");
3100
+ var PostgresAdvisoryFlowTurnLock = class {
3101
+ static {
3102
+ __name(this, "PostgresAdvisoryFlowTurnLock");
3103
+ }
3104
+ db;
3105
+ constructor(db) {
3106
+ this.db = db;
3107
+ }
3108
+ withLock(key, work) {
3109
+ return this.db.transaction(async (transaction) => {
3110
+ await transaction.execute(import_drizzle_orm7.sql`select pg_advisory_xact_lock(hashtext(${lockName(key)}))`);
3111
+ return work();
3112
+ });
3113
+ }
3114
+ };
3115
+ var InProcessFlowTurnLock = class {
3116
+ static {
3117
+ __name(this, "InProcessFlowTurnLock");
3118
+ }
3119
+ tails = /* @__PURE__ */ new Map();
3120
+ async withLock(key, work) {
3121
+ const name = lockName(key);
3122
+ const previous = this.tails.get(name) ?? Promise.resolve();
3123
+ const current = previous.catch(() => void 0).then(work);
3124
+ this.tails.set(name, current);
3125
+ try {
3126
+ return await current;
3127
+ } finally {
3128
+ if (this.tails.get(name) === current) this.tails.delete(name);
3129
+ }
3130
+ }
3131
+ };
3132
+
3133
+ // src/flows/createSendMediaAction.ts
3134
+ function mediaTypeFor2(mimeType) {
3135
+ if (mimeType.startsWith("image/")) return "image";
3136
+ if (mimeType.startsWith("audio/")) return "audio";
3137
+ if (mimeType.startsWith("video/")) return "video";
3138
+ return "document";
3139
+ }
3140
+ __name(mediaTypeFor2, "mediaTypeFor");
3141
+ async function sendAttachment(params) {
3142
+ const { attachment, channel, to, cache } = params;
3143
+ const common = {
3144
+ to,
3145
+ mimeType: attachment.mimeType,
3146
+ filename: attachment.filename,
3147
+ caption: attachment.caption ?? void 0
3148
+ };
3149
+ const cacheKey = cache ? {
3150
+ flowMediaId: attachment.id,
3151
+ senderKey: cache.senderKey
3152
+ } : void 0;
3153
+ if (cache && cacheKey) {
3154
+ const knownMediaId = await cache.store.get(cacheKey);
3155
+ if (knownMediaId) {
3156
+ try {
3157
+ return await channel.sendMedia({
3158
+ ...common,
3159
+ mediaId: knownMediaId
3160
+ });
3161
+ } catch {
3162
+ await cache.store.clear(cacheKey);
3163
+ }
3164
+ }
3165
+ }
3166
+ const buffer = await params.objectStorage.getObject(attachment.uploadId);
3167
+ const result = await channel.sendMedia({
3168
+ ...common,
3169
+ buffer
3170
+ });
3171
+ if (cache && cacheKey && result.mediaId) await cache.store.set({
3172
+ ...cacheKey,
3173
+ mediaId: result.mediaId
3174
+ });
3175
+ return result;
3176
+ }
3177
+ __name(sendAttachment, "sendAttachment");
3178
+ function createSendMediaAction(params) {
3179
+ return async ({ node, session, channel }) => {
3180
+ if (!session.flowKey) return;
3181
+ const location = {
3182
+ companyId: session.companyId,
3183
+ flowKey: session.flowKey,
3184
+ nodeId: node.id
3185
+ };
3186
+ const attachments = await params.flowMediaRepository.listActive(location);
3187
+ for (const attachment of attachments) {
3188
+ try {
3189
+ const { externalMessageId } = await sendAttachment({
3190
+ attachment,
3191
+ channel,
3192
+ to: session.whatsappNumber,
3193
+ objectStorage: params.objectStorage,
3194
+ ...params.mediaIdCache ? {
3195
+ cache: params.mediaIdCache
3196
+ } : {}
1972
3197
  });
1973
3198
  await params.logMessage.execute({
1974
3199
  companyId: session.companyId,
@@ -2070,7 +3295,7 @@ async function listAvailableProducts(params) {
2070
3295
  __name(listAvailableProducts, "listAvailableProducts");
2071
3296
 
2072
3297
  // src/repositories/FlowMediaRepository.ts
2073
- var import_drizzle_orm7 = require("drizzle-orm");
3298
+ var import_drizzle_orm8 = require("drizzle-orm");
2074
3299
  var FlowMediaRepository = class {
2075
3300
  static {
2076
3301
  __name(this, "FlowMediaRepository");
@@ -2080,18 +3305,18 @@ var FlowMediaRepository = class {
2080
3305
  this.db = db;
2081
3306
  }
2082
3307
  locationFilter(location) {
2083
- return (0, import_drizzle_orm7.and)((0, import_drizzle_orm7.eq)(flowMedia.companyId, location.companyId), (0, import_drizzle_orm7.eq)(flowMedia.flowKey, location.flowKey), (0, import_drizzle_orm7.eq)(flowMedia.nodeId, location.nodeId));
3308
+ return (0, import_drizzle_orm8.and)((0, import_drizzle_orm8.eq)(flowMedia.companyId, location.companyId), (0, import_drizzle_orm8.eq)(flowMedia.flowKey, location.flowKey), (0, import_drizzle_orm8.eq)(flowMedia.nodeId, location.nodeId));
2084
3309
  }
2085
3310
  // O que o nó realmente envia, na ordem de envio. `active` filtrado aqui e não no chamador:
2086
3311
  // é a razão de a coluna existir, e um chamador que esquecesse do filtro mandaria ao cliente
2087
3312
  // justamente o material que alguém desligou.
2088
3313
  async listActive(location) {
2089
- return this.db.select().from(flowMedia).where((0, import_drizzle_orm7.and)(this.locationFilter(location), (0, import_drizzle_orm7.eq)(flowMedia.active, true))).orderBy((0, import_drizzle_orm7.asc)(flowMedia.sortOrder), (0, import_drizzle_orm7.asc)(flowMedia.createdAt));
3314
+ return this.db.select().from(flowMedia).where((0, import_drizzle_orm8.and)(this.locationFilter(location), (0, import_drizzle_orm8.eq)(flowMedia.active, true))).orderBy((0, import_drizzle_orm8.asc)(flowMedia.sortOrder), (0, import_drizzle_orm8.asc)(flowMedia.createdAt));
2090
3315
  }
2091
3316
  // Inclui os desligados — é a visão do editor, onde desligar precisa continuar visível para
2092
3317
  // poder ser religado.
2093
3318
  async listAll(location) {
2094
- return this.db.select().from(flowMedia).where(this.locationFilter(location)).orderBy((0, import_drizzle_orm7.asc)(flowMedia.sortOrder), (0, import_drizzle_orm7.asc)(flowMedia.createdAt));
3319
+ return this.db.select().from(flowMedia).where(this.locationFilter(location)).orderBy((0, import_drizzle_orm8.asc)(flowMedia.sortOrder), (0, import_drizzle_orm8.asc)(flowMedia.createdAt));
2095
3320
  }
2096
3321
  /**
2097
3322
  * Anexa um arquivo já existente no storage ao nó.
@@ -2122,7 +3347,7 @@ var FlowMediaRepository = class {
2122
3347
  caption: params.caption ?? null,
2123
3348
  sortOrder: params.sortOrder ?? 0,
2124
3349
  active: true,
2125
- updatedAt: import_drizzle_orm7.sql`now()`
3350
+ updatedAt: import_drizzle_orm8.sql`now()`
2126
3351
  }
2127
3352
  }).returning();
2128
3353
  return row;
@@ -2138,8 +3363,8 @@ var FlowMediaRepository = class {
2138
3363
  ...params.active !== void 0 ? {
2139
3364
  active: params.active
2140
3365
  } : {},
2141
- updatedAt: import_drizzle_orm7.sql`now()`
2142
- }).where((0, import_drizzle_orm7.and)((0, import_drizzle_orm7.eq)(flowMedia.companyId, params.companyId), (0, import_drizzle_orm7.eq)(flowMedia.id, params.id))).returning();
3366
+ updatedAt: import_drizzle_orm8.sql`now()`
3367
+ }).where((0, import_drizzle_orm8.and)((0, import_drizzle_orm8.eq)(flowMedia.companyId, params.companyId), (0, import_drizzle_orm8.eq)(flowMedia.id, params.id))).returning();
2143
3368
  return row;
2144
3369
  }
2145
3370
  /**
@@ -2148,17 +3373,17 @@ var FlowMediaRepository = class {
2148
3373
  * host, que é dono da biblioteca de arquivos.
2149
3374
  */
2150
3375
  async detach(params) {
2151
- await this.db.delete(flowMedia).where((0, import_drizzle_orm7.and)((0, import_drizzle_orm7.eq)(flowMedia.companyId, params.companyId), (0, import_drizzle_orm7.eq)(flowMedia.id, params.id)));
3376
+ await this.db.delete(flowMedia).where((0, import_drizzle_orm8.and)((0, import_drizzle_orm8.eq)(flowMedia.companyId, params.companyId), (0, import_drizzle_orm8.eq)(flowMedia.id, params.id)));
2152
3377
  }
2153
3378
  // Chamado ao salvar o grafo: nós apagados no editor deixam linhas que nada mais alcança.
2154
3379
  async detachRemovedNodes(params) {
2155
- const condition = params.existingNodeIds.length === 0 ? void 0 : import_drizzle_orm7.sql`${flowMedia.nodeId} NOT IN ${params.existingNodeIds}`;
2156
- await this.db.delete(flowMedia).where((0, import_drizzle_orm7.and)((0, import_drizzle_orm7.eq)(flowMedia.companyId, params.companyId), (0, import_drizzle_orm7.eq)(flowMedia.flowKey, params.flowKey), condition));
3380
+ const condition = params.existingNodeIds.length === 0 ? void 0 : import_drizzle_orm8.sql`${flowMedia.nodeId} NOT IN ${params.existingNodeIds}`;
3381
+ await this.db.delete(flowMedia).where((0, import_drizzle_orm8.and)((0, import_drizzle_orm8.eq)(flowMedia.companyId, params.companyId), (0, import_drizzle_orm8.eq)(flowMedia.flowKey, params.flowKey), condition));
2157
3382
  }
2158
3383
  };
2159
3384
 
2160
3385
  // src/repositories/FlowMediaIdRepository.ts
2161
- var import_drizzle_orm8 = require("drizzle-orm");
3386
+ var import_drizzle_orm9 = require("drizzle-orm");
2162
3387
  var FlowMediaIdRepository = class {
2163
3388
  static {
2164
3389
  __name(this, "FlowMediaIdRepository");
@@ -2170,7 +3395,7 @@ var FlowMediaIdRepository = class {
2170
3395
  async get(params) {
2171
3396
  const rows = await this.db.select({
2172
3397
  ids: flowMedia.metaMediaIds
2173
- }).from(flowMedia).where((0, import_drizzle_orm8.eq)(flowMedia.id, params.flowMediaId)).limit(1);
3398
+ }).from(flowMedia).where((0, import_drizzle_orm9.eq)(flowMedia.id, params.flowMediaId)).limit(1);
2174
3399
  return rows[0]?.ids?.[params.senderKey];
2175
3400
  }
2176
3401
  /**
@@ -2182,23 +3407,23 @@ var FlowMediaIdRepository = class {
2182
3407
  */
2183
3408
  async set(params) {
2184
3409
  await this.db.update(flowMedia).set({
2185
- metaMediaIds: import_drizzle_orm8.sql`jsonb_set(${flowMedia.metaMediaIds}, ARRAY[${params.senderKey}::text], to_jsonb(${params.mediaId}::text), true)`
2186
- }).where((0, import_drizzle_orm8.eq)(flowMedia.id, params.flowMediaId));
3410
+ metaMediaIds: import_drizzle_orm9.sql`jsonb_set(${flowMedia.metaMediaIds}, ARRAY[${params.senderKey}::text], to_jsonb(${params.mediaId}::text), true)`
3411
+ }).where((0, import_drizzle_orm9.eq)(flowMedia.id, params.flowMediaId));
2187
3412
  }
2188
3413
  /** Remove só a chave deste número — o id do outro número continua válido. */
2189
3414
  async clear(params) {
2190
3415
  await this.db.update(flowMedia).set({
2191
- metaMediaIds: import_drizzle_orm8.sql`${flowMedia.metaMediaIds} - ${params.senderKey}::text`
2192
- }).where((0, import_drizzle_orm8.eq)(flowMedia.id, params.flowMediaId));
3416
+ metaMediaIds: import_drizzle_orm9.sql`${flowMedia.metaMediaIds} - ${params.senderKey}::text`
3417
+ }).where((0, import_drizzle_orm9.eq)(flowMedia.id, params.flowMediaId));
2193
3418
  }
2194
3419
  };
2195
3420
 
2196
3421
  // src/channel/WhatsAppChannelAdapter.ts
2197
- var import_meta_graph_core = require("@adatechnology/meta-graph-core");
2198
- var import_meta_whatsapp_contracts9 = require("@adatechnology/meta-whatsapp-contracts");
3422
+ var import_meta_graph_core2 = require("@adatechnology/meta-graph-core");
3423
+ var import_meta_whatsapp_contracts15 = require("@adatechnology/meta-whatsapp-contracts");
2199
3424
 
2200
3425
  // src/channel/previewMedia.ts
2201
- var import_meta_whatsapp_contracts8 = require("@adatechnology/meta-whatsapp-contracts");
3426
+ var import_meta_whatsapp_contracts14 = require("@adatechnology/meta-whatsapp-contracts");
2202
3427
 
2203
3428
  // src/channel/WhatsAppChannelAdapter.ts
2204
3429
  var WhatsAppChannelAdapter = class {
@@ -2207,25 +3432,40 @@ var WhatsAppChannelAdapter = class {
2207
3432
  }
2208
3433
  messages;
2209
3434
  previewMedia;
2210
- constructor(messages2, previewMedia) {
3435
+ previewContacts;
3436
+ constructor(messages2, previewMedia, previewContacts) {
2211
3437
  this.messages = messages2;
2212
3438
  this.previewMedia = previewMedia;
3439
+ this.previewContacts = previewContacts;
3440
+ }
3441
+ /** `preview.<uuid>` quando o destino é contato do simulador e o recurso está ligado. */
3442
+ previewMessageId(to) {
3443
+ if (!this.previewContacts?.isEnabled || !(0, import_meta_whatsapp_contracts15.isPreviewContact)(to)) return void 0;
3444
+ return `preview.${this.previewContacts.generateId?.() ?? globalThis.crypto.randomUUID()}`;
2213
3445
  }
2214
3446
  async translateErrors(operation) {
2215
3447
  try {
2216
3448
  return await operation();
2217
3449
  } catch (error) {
2218
- if (error instanceof import_meta_graph_core.WhatsAppWindowExpiredError) throw new import_meta_whatsapp_contracts9.WindowExpiredError();
3450
+ if (error instanceof import_meta_graph_core2.WhatsAppWindowExpiredError) throw new import_meta_whatsapp_contracts15.WindowExpiredError();
2219
3451
  throw error;
2220
3452
  }
2221
3453
  }
2222
3454
  async sendText(to, body) {
3455
+ const previewId = this.previewMessageId(to);
3456
+ if (previewId) return {
3457
+ externalMessageId: previewId
3458
+ };
2223
3459
  const result = await this.translateErrors(() => this.messages.sendText(to, body));
2224
3460
  return {
2225
3461
  externalMessageId: result.waMessageId
2226
3462
  };
2227
3463
  }
2228
3464
  async sendMedia(params) {
3465
+ const previewId = this.previewMessageId(params.to);
3466
+ if (previewId) return {
3467
+ externalMessageId: previewId
3468
+ };
2229
3469
  const result = await this.translateErrors(() => this.messages.sendMedia(params));
2230
3470
  return {
2231
3471
  externalMessageId: result.waMessageId,
@@ -2233,28 +3473,49 @@ var WhatsAppChannelAdapter = class {
2233
3473
  };
2234
3474
  }
2235
3475
  async sendTemplate(params) {
3476
+ const previewId = this.previewMessageId(params.to);
3477
+ if (previewId) return {
3478
+ externalMessageId: previewId
3479
+ };
2236
3480
  const result = await this.translateErrors(() => this.messages.sendTemplate(params));
2237
3481
  return {
2238
3482
  externalMessageId: result.waMessageId
2239
3483
  };
2240
3484
  }
2241
3485
  async sendInteractiveList(params) {
3486
+ const previewId = this.previewMessageId(params.to);
3487
+ if (previewId) return {
3488
+ externalMessageId: previewId
3489
+ };
3490
+ const sections = (params.sections ?? [
3491
+ {
3492
+ rows: params.rows ?? []
3493
+ }
3494
+ ]).map((section) => ({
3495
+ title: section.title ?? params.buttonLabel,
3496
+ rows: section.rows.map((row) => ({
3497
+ id: row.id,
3498
+ title: row.title,
3499
+ ...row.description ? {
3500
+ description: row.description
3501
+ } : {}
3502
+ }))
3503
+ }));
2242
3504
  const result = await this.translateErrors(() => this.messages.sendInteractiveList({
2243
3505
  to: params.to,
2244
3506
  bodyText: params.body,
2245
3507
  buttonText: params.buttonLabel,
2246
- sections: [
2247
- {
2248
- title: params.buttonLabel,
2249
- rows: params.rows
2250
- }
2251
- ]
3508
+ sections
2252
3509
  }));
2253
3510
  return {
2254
3511
  externalMessageId: result.waMessageId
2255
3512
  };
2256
3513
  }
2257
3514
  async sendInteractiveButtons(params) {
3515
+ const previewId = this.previewMessageId(params.to);
3516
+ if (previewId) return {
3517
+ externalMessageId: previewId
3518
+ };
2258
3519
  const result = await this.translateErrors(() => this.messages.sendInteractiveButtons({
2259
3520
  to: params.to,
2260
3521
  bodyText: params.body,
@@ -2265,6 +3526,10 @@ var WhatsAppChannelAdapter = class {
2265
3526
  };
2266
3527
  }
2267
3528
  async sendProductList(params) {
3529
+ const previewId = this.previewMessageId(params.to);
3530
+ if (previewId) return {
3531
+ externalMessageId: previewId
3532
+ };
2268
3533
  const result = await this.translateErrors(() => this.messages.sendProductListMessage({
2269
3534
  to: params.to,
2270
3535
  headerText: params.headerText,
@@ -2285,7 +3550,7 @@ var WhatsAppChannelAdapter = class {
2285
3550
  * tentar buscá-lo lá renderia um 404 confuso em vez do áudio que o operador acabou de gravar.
2286
3551
  */
2287
3552
  async fetchMediaAsBase64(mediaId) {
2288
- const uploadId = this.previewMedia?.isEnabled ? (0, import_meta_whatsapp_contracts8.resolvePreviewUploadId)(mediaId) : void 0;
3553
+ const uploadId = this.previewMedia?.isEnabled ? (0, import_meta_whatsapp_contracts14.resolvePreviewUploadId)(mediaId) : void 0;
2289
3554
  if (uploadId) {
2290
3555
  const buffer = await this.previewMedia.objectStorage.getObject(uploadId);
2291
3556
  return {
@@ -2298,43 +3563,42 @@ var WhatsAppChannelAdapter = class {
2298
3563
  };
2299
3564
 
2300
3565
  // src/channel/ReceiveWebhook.use-case.ts
2301
- var import_meta_whatsapp_contracts12 = require("@adatechnology/meta-whatsapp-contracts");
2302
- var import_meta_graph_core3 = require("@adatechnology/meta-graph-core");
3566
+ var import_meta_whatsapp_contracts18 = require("@adatechnology/meta-whatsapp-contracts");
2303
3567
 
2304
3568
  // src/channel/webhookSecurity.ts
2305
- var import_meta_graph_core2 = require("@adatechnology/meta-graph-core");
2306
- var import_meta_whatsapp_contracts10 = require("@adatechnology/meta-whatsapp-contracts");
3569
+ var import_meta_graph_core3 = require("@adatechnology/meta-graph-core");
3570
+ var import_meta_whatsapp_contracts16 = require("@adatechnology/meta-whatsapp-contracts");
2307
3571
  var WEBHOOK_NONCE_NAMESPACE = "meta-whatsapp";
2308
3572
  function verifyWebhookChallenge(params) {
2309
- if (!(0, import_meta_graph_core2.isValidWebhookChallenge)(params)) throw new import_meta_whatsapp_contracts10.InvalidWebhookSignatureError();
3573
+ if (!(0, import_meta_graph_core3.isValidWebhookChallenge)(params)) throw new import_meta_whatsapp_contracts16.InvalidWebhookSignatureError();
2310
3574
  return params.challenge;
2311
3575
  }
2312
3576
  __name(verifyWebhookChallenge, "verifyWebhookChallenge");
2313
3577
  function verifyWebhookSignature(params) {
2314
- if (!(0, import_meta_graph_core2.isValidWebhookSignature)(params)) throw new import_meta_whatsapp_contracts10.InvalidWebhookSignatureError();
3578
+ if (!(0, import_meta_graph_core3.isValidWebhookSignature)(params)) throw new import_meta_whatsapp_contracts16.InvalidWebhookSignatureError();
2315
3579
  }
2316
3580
  __name(verifyWebhookSignature, "verifyWebhookSignature");
2317
3581
  function deliveryKey(signatureHeader) {
2318
- return (0, import_meta_graph_core2.buildWebhookDeliveryKey)({
3582
+ return (0, import_meta_graph_core3.buildWebhookDeliveryKey)({
2319
3583
  namespace: WEBHOOK_NONCE_NAMESPACE,
2320
3584
  signatureHeader
2321
3585
  });
2322
3586
  }
2323
3587
  __name(deliveryKey, "deliveryKey");
2324
3588
  async function claimWebhookDelivery(params) {
2325
- return params.nonceStore.setIfAbsent(deliveryKey(params.signatureHeader), params.ttlSeconds ?? import_meta_graph_core2.WEBHOOK_CLAIM_TTL_SECONDS);
3589
+ return params.nonceStore.setIfAbsent(deliveryKey(params.signatureHeader), params.ttlSeconds ?? import_meta_graph_core3.WEBHOOK_CLAIM_TTL_SECONDS);
2326
3590
  }
2327
3591
  __name(claimWebhookDelivery, "claimWebhookDelivery");
2328
3592
  async function confirmWebhookDelivery(params) {
2329
- await params.nonceStore.confirm?.(deliveryKey(params.signatureHeader), params.ttlSeconds ?? import_meta_graph_core2.WEBHOOK_NONCE_TTL_SECONDS);
3593
+ await params.nonceStore.confirm?.(deliveryKey(params.signatureHeader), params.ttlSeconds ?? import_meta_graph_core3.WEBHOOK_NONCE_TTL_SECONDS);
2330
3594
  }
2331
3595
  __name(confirmWebhookDelivery, "confirmWebhookDelivery");
2332
3596
 
2333
3597
  // src/channel/IngestInboundMedia.use-case.ts
2334
- var import_drizzle_orm9 = require("drizzle-orm");
3598
+ var import_drizzle_orm10 = require("drizzle-orm");
2335
3599
 
2336
3600
  // src/use-cases/TranscribeAudio.use-case.ts
2337
- var import_meta_whatsapp_contracts11 = require("@adatechnology/meta-whatsapp-contracts");
3601
+ var import_meta_whatsapp_contracts17 = require("@adatechnology/meta-whatsapp-contracts");
2338
3602
 
2339
3603
  // src/transcription.types.ts
2340
3604
  var TRANSCRIPTION_STATUS = {
@@ -2395,7 +3659,7 @@ var TranscribeAudioUseCase = class {
2395
3659
  }
2396
3660
  if (this.dependencies.resolvePolicy) {
2397
3661
  const policy = await this.dependencies.resolvePolicy(params.companyId);
2398
- if (!policy.isEnabled) throw new import_meta_whatsapp_contracts11.TranscriptionDisabledError();
3662
+ if (!policy.isEnabled) throw new import_meta_whatsapp_contracts17.TranscriptionDisabledError();
2399
3663
  }
2400
3664
  const audio = extractAudioReference(message);
2401
3665
  const buffer = await this.dependencies.objectStorage.getObject(audio.uploadId);
@@ -2472,11 +3736,11 @@ function extractAudioReference(message) {
2472
3736
  const audio = payload["audio"];
2473
3737
  const mimeType = typeof payload["mimeType"] === "string" ? payload["mimeType"] : audio?.mime_type;
2474
3738
  if (!isAudioMimeType(mimeType) && !audio) {
2475
- throw new import_meta_whatsapp_contracts11.MessageNotAudioError(message.id, message.type);
3739
+ throw new import_meta_whatsapp_contracts17.MessageNotAudioError(message.id, message.type);
2476
3740
  }
2477
3741
  const uploadId = payload["uploadId"];
2478
3742
  if (typeof uploadId !== "string" || uploadId.length === 0) {
2479
- throw new import_meta_whatsapp_contracts11.AudioNotIngestedError(message.id);
3743
+ throw new import_meta_whatsapp_contracts17.AudioNotIngestedError(message.id);
2480
3744
  }
2481
3745
  return {
2482
3746
  uploadId,
@@ -2503,7 +3767,7 @@ var IngestInboundMediaUseCase = class {
2503
3767
  this.transcription = transcription;
2504
3768
  }
2505
3769
  async execute(params) {
2506
- const [message] = await this.db.select().from(messages).where((0, import_drizzle_orm9.and)((0, import_drizzle_orm9.eq)(messages.companyId, params.companyId), (0, import_drizzle_orm9.eq)(messages.id, params.messageId))).limit(1);
3770
+ const [message] = await this.db.select().from(messages).where((0, import_drizzle_orm10.and)((0, import_drizzle_orm10.eq)(messages.companyId, params.companyId), (0, import_drizzle_orm10.eq)(messages.id, params.messageId))).limit(1);
2507
3771
  if (!message) throw new Error(`Mensagem ${params.messageId} n\xE3o encontrada para ingest\xE3o de m\xEDdia`);
2508
3772
  const payload = message.payload ?? {};
2509
3773
  if (payload["uploadId"] && payload["sourceMediaId"] === params.sourceMediaId) {
@@ -2534,7 +3798,7 @@ var IngestInboundMediaUseCase = class {
2534
3798
  };
2535
3799
  await this.db.update(messages).set({
2536
3800
  payload: updatedPayload
2537
- }).where((0, import_drizzle_orm9.and)((0, import_drizzle_orm9.eq)(messages.companyId, params.companyId), (0, import_drizzle_orm9.eq)(messages.id, params.messageId)));
3801
+ }).where((0, import_drizzle_orm10.and)((0, import_drizzle_orm10.eq)(messages.companyId, params.companyId), (0, import_drizzle_orm10.eq)(messages.id, params.messageId)));
2538
3802
  await this.documentRepository?.link({
2539
3803
  companyId: params.companyId,
2540
3804
  sessionId: message.sessionId,
@@ -2649,91 +3913,6 @@ function extractMediaDescriptor(message) {
2649
3913
  }
2650
3914
  __name(extractMediaDescriptor, "extractMediaDescriptor");
2651
3915
 
2652
- // src/channel/inboundDispatch.ts
2653
- function buildInboundJobId(job) {
2654
- return job.kind === "message" ? `wa-inbound-message:${job.message.id}` : `wa-inbound-status:${job.status.id}:${job.status.status}`;
2655
- }
2656
- __name(buildInboundJobId, "buildInboundJobId");
2657
- function toSessionContract(row) {
2658
- return {
2659
- id: row.id,
2660
- companyId: row.companyId,
2661
- whatsappNumber: row.whatsappNumber,
2662
- currentState: row.currentState,
2663
- flowKey: row.flowKey,
2664
- currentNodeId: row.currentNodeId,
2665
- context: row.context,
2666
- mode: row.mode,
2667
- assignedUserId: row.assignedUserId,
2668
- humanRequestedAt: row.humanRequestedAt?.toISOString() ?? null,
2669
- lastInboundAt: row.lastInboundAt?.toISOString() ?? null,
2670
- lastAgentReadAt: row.lastAgentReadAt?.toISOString() ?? null,
2671
- lastActivity: row.lastActivity.toISOString(),
2672
- createdAt: row.createdAt.toISOString(),
2673
- updatedAt: row.updatedAt.toISOString()
2674
- };
2675
- }
2676
- __name(toSessionContract, "toSessionContract");
2677
- function extractAnswer(message) {
2678
- const interactive = message.interactive;
2679
- if (interactive?.button_reply) return interactive.button_reply.id;
2680
- if (interactive?.list_reply) return interactive.list_reply.id;
2681
- return message.text?.body;
2682
- }
2683
- __name(extractAnswer, "extractAnswer");
2684
- var InboundEffectsDispatcher = class {
2685
- static {
2686
- __name(this, "InboundEffectsDispatcher");
2687
- }
2688
- params;
2689
- constructor(params) {
2690
- this.params = params;
2691
- }
2692
- async run(job) {
2693
- if (job.kind === "message") return this.runMessageEffects(job);
2694
- return this.runStatusEffects(job);
2695
- }
2696
- async runMessageEffects(job) {
2697
- const { companyId, message, savedMessageId, media } = job;
2698
- if (media) {
2699
- await this.params.hooks?.onMediaReceived?.({
2700
- companyId,
2701
- messageId: savedMessageId,
2702
- whatsappNumber: message.from,
2703
- sourceMediaId: media.sourceMediaId,
2704
- mimeType: media.mimeType,
2705
- ...media.filename ? {
2706
- filename: media.filename
2707
- } : {}
2708
- });
2709
- }
2710
- const sessionRow = await this.params.sessionRepository.getContext(companyId, message.from);
2711
- if (!sessionRow) return;
2712
- if (sessionRow.mode === "human") return;
2713
- const outcome = await this.params.hooks?.onMessageReceived?.(message, toSessionContract(sessionRow), job.profileName === void 0 ? {} : {
2714
- profileName: job.profileName
2715
- });
2716
- if (outcome?.outcome === "handled") return;
2717
- void extractAnswer(message);
2718
- }
2719
- async runStatusEffects(job) {
2720
- const sessionRow = await this.params.sessionRepository.getContext(job.companyId, job.whatsappNumber);
2721
- await this.params.hooks?.onStatusUpdate?.(job.status, sessionRow ? toSessionContract(sessionRow) : null);
2722
- }
2723
- };
2724
- var ProcessInboundDispatchUseCase = class {
2725
- static {
2726
- __name(this, "ProcessInboundDispatchUseCase");
2727
- }
2728
- dispatcher;
2729
- constructor(dispatcher) {
2730
- this.dispatcher = dispatcher;
2731
- }
2732
- async execute(job) {
2733
- await this.dispatcher.run(job);
2734
- }
2735
- };
2736
-
2737
3916
  // src/channel/ReceiveWebhook.use-case.ts
2738
3917
  var EMPTY_RESULT = {
2739
3918
  messagesProcessed: 0,
@@ -2777,8 +3956,8 @@ function extractPayload(message, { isLocationRedacted } = DEFAULT_EXTRACTION_OPT
2777
3956
  }
2778
3957
  __name(extractPayload, "extractPayload");
2779
3958
  var ACCOUNT_EVENT_FIELDS = [
2780
- import_meta_whatsapp_contracts12.WHATSAPP_WEBHOOK_FIELDS.TEMPLATE_STATUS_UPDATE,
2781
- import_meta_whatsapp_contracts12.WHATSAPP_WEBHOOK_FIELDS.PHONE_NUMBER_QUALITY_UPDATE
3959
+ import_meta_whatsapp_contracts18.WHATSAPP_WEBHOOK_FIELDS.TEMPLATE_STATUS_UPDATE,
3960
+ import_meta_whatsapp_contracts18.WHATSAPP_WEBHOOK_FIELDS.PHONE_NUMBER_QUALITY_UPDATE
2782
3961
  ];
2783
3962
  function isAccountEventField(field) {
2784
3963
  return field !== void 0 && ACCOUNT_EVENT_FIELDS.includes(field);
@@ -2798,6 +3977,9 @@ var ReceiveWebhookUseCase = class {
2798
3977
  } : {},
2799
3978
  ...params.realtime ? {
2800
3979
  realtime: params.realtime
3980
+ } : {},
3981
+ ...params.flowRunner ? {
3982
+ flowRunner: params.flowRunner
2801
3983
  } : {}
2802
3984
  });
2803
3985
  }
@@ -2817,7 +3999,7 @@ var ReceiveWebhookUseCase = class {
2817
3999
  ...EMPTY_RESULT
2818
4000
  };
2819
4001
  const rawText = typeof input.rawBody === "string" ? input.rawBody : input.rawBody.toString("utf8");
2820
- const parsed = import_meta_whatsapp_contracts12.whatsAppWebhookPayloadSchema.safeParse(JSON.parse(rawText));
4002
+ const parsed = import_meta_whatsapp_contracts18.whatsAppWebhookPayloadSchema.safeParse(JSON.parse(rawText));
2821
4003
  if (!parsed.success) {
2822
4004
  await this.params.hooks?.onUnhandledWebhookEvent?.({
2823
4005
  field: void 0,
@@ -2850,7 +4032,7 @@ var ReceiveWebhookUseCase = class {
2850
4032
  continue;
2851
4033
  }
2852
4034
  for (const message of change.value.messages ?? []) {
2853
- const profileName = (0, import_meta_whatsapp_contracts12.resolveContactProfileName)({
4035
+ const profileName = (0, import_meta_whatsapp_contracts18.resolveContactProfileName)({
2854
4036
  contacts: change.value.contacts,
2855
4037
  from: message.from
2856
4038
  });
@@ -2888,8 +4070,8 @@ var ReceiveWebhookUseCase = class {
2888
4070
  // Devolve `false` quando o corpo não bate com o schema do field — o chamador conta como não
2889
4071
  // tratado. O host é avisado nos dois casos, mas com `reason` diferente.
2890
4072
  async handleAccountEvent(change) {
2891
- if (change.field === import_meta_whatsapp_contracts12.WHATSAPP_WEBHOOK_FIELDS.TEMPLATE_STATUS_UPDATE) {
2892
- const update = import_meta_whatsapp_contracts12.whatsAppTemplateStatusUpdateSchema.safeParse(change.value);
4073
+ if (change.field === import_meta_whatsapp_contracts18.WHATSAPP_WEBHOOK_FIELDS.TEMPLATE_STATUS_UPDATE) {
4074
+ const update = import_meta_whatsapp_contracts18.whatsAppTemplateStatusUpdateSchema.safeParse(change.value);
2893
4075
  if (!update.success) {
2894
4076
  await this.params.hooks?.onUnhandledWebhookEvent?.({
2895
4077
  field: change.field,
@@ -2901,7 +4083,7 @@ var ReceiveWebhookUseCase = class {
2901
4083
  await this.params.hooks?.onTemplateStatusUpdate?.(update.data);
2902
4084
  return true;
2903
4085
  }
2904
- const quality = import_meta_whatsapp_contracts12.whatsAppPhoneNumberQualityUpdateSchema.safeParse(change.value);
4086
+ const quality = import_meta_whatsapp_contracts18.whatsAppPhoneNumberQualityUpdateSchema.safeParse(change.value);
2905
4087
  if (!quality.success) {
2906
4088
  await this.params.hooks?.onUnhandledWebhookEvent?.({
2907
4089
  field: change.field,
@@ -2983,24 +4165,15 @@ var ReceiveWebhookUseCase = class {
2983
4165
  });
2984
4166
  return;
2985
4167
  }
2986
- try {
2987
- await this.dispatcher.run(job);
2988
- } catch (error) {
2989
- if (!(0, import_meta_graph_core3.isDeterministicMetaRejection)(error)) throw error;
2990
- await this.params.hooks?.onInboundEffectRejected?.({
2991
- companyId: job.companyId,
2992
- kind: job.kind,
2993
- whatsappNumber: resolveJobNumber(job),
2994
- code: error.code,
2995
- error
2996
- });
2997
- }
4168
+ await runInboundEffects({
4169
+ dispatcher: this.dispatcher,
4170
+ job,
4171
+ ...this.params.hooks ? {
4172
+ hooks: this.params.hooks
4173
+ } : {}
4174
+ });
2998
4175
  }
2999
4176
  };
3000
- function resolveJobNumber(job) {
3001
- return job.kind === "message" ? job.message.from : job.whatsappNumber;
3002
- }
3003
- __name(resolveJobNumber, "resolveJobNumber");
3004
4177
 
3005
4178
  // src/use-cases/resolveTranscriptionPolicy.ts
3006
4179
  function createTranscriptionPolicyResolver(dependencies) {
@@ -3041,7 +4214,7 @@ var StorePreviewMediaUseCase = class {
3041
4214
  key
3042
4215
  });
3043
4216
  return {
3044
- mediaId: (0, import_meta_whatsapp_contracts8.toPreviewMediaId)(uploadId),
4217
+ mediaId: (0, import_meta_whatsapp_contracts14.toPreviewMediaId)(uploadId),
3045
4218
  uploadId
3046
4219
  };
3047
4220
  }
@@ -3063,7 +4236,9 @@ function createMetaWhatsAppModule(params) {
3063
4236
  isEnabled: true,
3064
4237
  objectStorage: providers.objectStorage
3065
4238
  } : void 0;
3066
- const channel = new WhatsAppChannelAdapter(messageProvider, previewMediaSupport);
4239
+ const channel = new WhatsAppChannelAdapter(messageProvider, previewMediaSupport, params.features?.previewContacts ? {
4240
+ isEnabled: true
4241
+ } : void 0);
3067
4242
  const sessionRepository = new SessionRepository(db);
3068
4243
  const messageRepository = new MessageRepository(db);
3069
4244
  const settingsRepository = new SettingsRepository(db);
@@ -3074,6 +4249,40 @@ function createMetaWhatsAppModule(params) {
3074
4249
  const flowMediaRepository = new FlowMediaRepository(db);
3075
4250
  const logMessage = new LogMessageUseCase(sessionRepository, messageRepository, providers.realtime, providers.moderator);
3076
4251
  const sendMessage = new SendMessageUseCase(channel, sessionRepository, logMessage, providers.objectStorage, documentRepository);
4252
+ const requestHuman = new RequestHumanConversationUseCase(sessionRepository, providers.realtime, hooks);
4253
+ const flowInterpreter = flowEngineEnabled ? new FlowInterpreter() : void 0;
4254
+ const flowRunnerFeature = params.features?.flowRunner ?? false;
4255
+ const flowRunnerConfig = flowInterpreter && flowRunnerFeature ? flowRunnerFeature === true ? {} : flowRunnerFeature : void 0;
4256
+ const flowHandoff = flowRunnerConfig ? new FlowHandoff({
4257
+ requestHuman,
4258
+ sendMessage,
4259
+ startState,
4260
+ config: flowRunnerConfig.handoff ?? {},
4261
+ now: flowRunnerConfig.now ?? (() => /* @__PURE__ */ new Date()),
4262
+ interpolation: flowRunnerConfig.formatValue ? {
4263
+ formatValue: flowRunnerConfig.formatValue
4264
+ } : {},
4265
+ ...hooks ? {
4266
+ hooks
4267
+ } : {}
4268
+ }) : void 0;
4269
+ const flowRunner = flowInterpreter && flowRunnerConfig && flowHandoff ? new FlowRunner({
4270
+ interpreter: flowInterpreter,
4271
+ flowGraphRepository,
4272
+ sessionRepository,
4273
+ sendMessage,
4274
+ channel,
4275
+ handoff: flowHandoff,
4276
+ lock: providers.flowTurnLock ?? new PostgresAdvisoryFlowTurnLock(db),
4277
+ startState,
4278
+ config: flowRunnerConfig,
4279
+ ...hooks ? {
4280
+ hooks
4281
+ } : {}
4282
+ }) : void 0;
4283
+ if (flowInterpreter && flowRunner && flowHandoff) {
4284
+ flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts19.FLOW_ACTION_KIND.HANDOFF, flowHandoff.createActionHandler((turn) => flowRunner.variablesFor(turn)));
4285
+ }
3077
4286
  const receiveWebhook = new ReceiveWebhookUseCase({
3078
4287
  appSecret: config.appSecret,
3079
4288
  phoneNumberId: config.phoneNumberId,
@@ -3084,11 +4293,16 @@ function createMetaWhatsAppModule(params) {
3084
4293
  startState,
3085
4294
  hooks,
3086
4295
  realtime: providers.realtime,
3087
- redactInboundLocation: params.features?.redactInboundLocation ?? false
4296
+ ...providers.inboundQueue ? {
4297
+ inboundQueue: providers.inboundQueue
4298
+ } : {},
4299
+ redactInboundLocation: params.features?.redactInboundLocation ?? false,
4300
+ ...flowRunner ? {
4301
+ flowRunner
4302
+ } : {}
3088
4303
  });
3089
- const flowInterpreter = flowEngineEnabled ? new FlowInterpreter() : void 0;
3090
4304
  if (flowInterpreter && providers.objectStorage?.getObject) {
3091
- flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts13.FLOW_ACTION_KIND.SEND_MEDIA, createSendMediaAction({
4305
+ flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts19.FLOW_ACTION_KIND.SEND_MEDIA, createSendMediaAction({
3092
4306
  flowMediaRepository,
3093
4307
  objectStorage: providers.objectStorage,
3094
4308
  logMessage,
@@ -3105,7 +4319,7 @@ function createMetaWhatsAppModule(params) {
3105
4319
  }));
3106
4320
  }
3107
4321
  if (flowInterpreter && providers.catalog && config.catalogId) {
3108
- flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts13.FLOW_ACTION_KIND.SEND_PRODUCT_LIST, createSendProductListAction({
4322
+ flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts19.FLOW_ACTION_KIND.SEND_PRODUCT_LIST, createSendProductListAction({
3109
4323
  catalog: providers.catalog,
3110
4324
  catalogId: config.catalogId,
3111
4325
  logMessage,
@@ -3154,8 +4368,10 @@ function createMetaWhatsAppModule(params) {
3154
4368
  conversations: {
3155
4369
  log: logMessage,
3156
4370
  send: sendMessage,
3157
- takeover: new TakeoverConversationUseCase(sessionRepository, providers.realtime),
3158
- release: new ReleaseConversationUseCase(sessionRepository, providers.realtime),
4371
+ takeover: new TakeoverConversationUseCase(sessionRepository, providers.realtime, hooks),
4372
+ release: new ReleaseConversationUseCase(sessionRepository, providers.realtime, hooks),
4373
+ // Marca o pedido de atendimento (fila "aguardando atendimento") e dispara `onHumanRequested`.
4374
+ requestHuman,
3159
4375
  list: new ListConversationsUseCase(sessionRepository),
3160
4376
  listMessages: new ListMessagesUseCase(sessionRepository, messageRepository),
3161
4377
  listDocuments,
@@ -3194,15 +4410,47 @@ function createMetaWhatsAppModule(params) {
3194
4410
  webhook: {
3195
4411
  receive: receiveWebhook,
3196
4412
  // GET de verificação da Meta — o host liga na sua rota e devolve o retorno como texto puro.
4413
+ /**
4414
+ * Comando do simulador (ponte do `conversations-ui`) → payload da Meta com o `phone_number_id`
4415
+ * DESTE módulo. Montar com o padrão do builder fazia o filtro de número descartar a entrega.
4416
+ * Quem assina e entrega em `receive` é a rota do host.
4417
+ */
4418
+ buildPreviewPayload: /* @__PURE__ */ __name((command, envelope) => (0, import_testing.buildPreviewInboundPayload)(command, {
4419
+ ...config.wabaId ? {
4420
+ wabaId: config.wabaId
4421
+ } : {},
4422
+ ...envelope,
4423
+ phoneNumberId: config.phoneNumberId
4424
+ }), "buildPreviewPayload"),
3197
4425
  verifyChallenge: /* @__PURE__ */ __name((query) => verifyWebhookChallenge({
3198
4426
  ...query,
3199
4427
  expectedToken: config.webhookVerifyToken
3200
- }), "verifyChallenge")
4428
+ }), "verifyChallenge"),
4429
+ // Lado do worker de `providers.inboundQueue`: roda os efeitos de um job já enfileirado. Existe
4430
+ // mesmo sem fila configurada — um worker de outra instância pode consumir a fila desta.
4431
+ processInboundDispatch: new ProcessInboundDispatchUseCase(new InboundEffectsDispatcher({
4432
+ sessionRepository,
4433
+ ...hooks ? {
4434
+ hooks
4435
+ } : {},
4436
+ ...providers.realtime ? {
4437
+ realtime: providers.realtime
4438
+ } : {},
4439
+ ...flowRunner ? {
4440
+ flowRunner
4441
+ } : {}
4442
+ }), hooks)
3201
4443
  },
3202
4444
  // undefined quando features.flowEngine === false.
3203
4445
  flows: flowInterpreter ? {
3204
4446
  interpreter: flowInterpreter,
3205
4447
  registerFlowAction: /* @__PURE__ */ __name((kind, handler) => flowInterpreter.registerFlowAction(kind, handler), "registerFlowAction"),
4448
+ // undefined quando `features.flowRunner` está desligado — o host dirige a conversa.
4449
+ runner: flowRunner,
4450
+ registerDynamicChoiceProvider: /* @__PURE__ */ __name((key, provider) => {
4451
+ if (!flowRunner) throw new import_meta_whatsapp_contracts19.ConfigMissingError("features.flowRunner");
4452
+ flowRunner.registerDynamicChoiceProvider(key, provider);
4453
+ }, "registerDynamicChoiceProvider"),
3206
4454
  get: new GetFlowGraphUseCase(flowGraphRepository),
3207
4455
  list: new ListFlowGraphsUseCase(flowGraphRepository),
3208
4456
  create: new CreateFlowGraphUseCase(flowGraphRepository),
@@ -3223,15 +4471,29 @@ __name(createMetaWhatsAppModule, "createMetaWhatsAppModule");
3223
4471
  // src/runMigrations.ts
3224
4472
  var import_node_path = require("path");
3225
4473
  var META_WHATSAPP_MIGRATIONS_TABLE = "meta_whatsapp_migrations";
3226
- function metaWhatsAppMigrationsFolder() {
3227
- return (0, import_node_path.join)(__dirname, "migrations");
4474
+ var LAYOUT_DIRECTORY = {
4475
+ v1: "migrations",
4476
+ journal: "migrations-journal"
4477
+ };
4478
+ function metaWhatsAppMigrationsFolder(params = {}) {
4479
+ return (0, import_node_path.join)(__dirname, LAYOUT_DIRECTORY[params.layout ?? "v1"]);
3228
4480
  }
3229
4481
  __name(metaWhatsAppMigrationsFolder, "metaWhatsAppMigrationsFolder");
4482
+ var MISSING_JOURNAL_REFUSAL = "meta/_journal.json";
3230
4483
  async function runMetaWhatsAppMigrations(params) {
3231
- await params.migrate(params.db, {
3232
- migrationsFolder: metaWhatsAppMigrationsFolder(),
4484
+ const run = /* @__PURE__ */ __name((layout) => params.migrate(params.db, {
4485
+ migrationsFolder: metaWhatsAppMigrationsFolder({
4486
+ layout
4487
+ }),
3233
4488
  migrationsTable: META_WHATSAPP_MIGRATIONS_TABLE
3234
- });
4489
+ }), "run");
4490
+ if (params.layout) return run(params.layout);
4491
+ try {
4492
+ await run("v1");
4493
+ } catch (error) {
4494
+ if (!(error instanceof Error) || !error.message.includes(MISSING_JOURNAL_REFUSAL)) throw error;
4495
+ await run("journal");
4496
+ }
3235
4497
  }
3236
4498
  __name(runMetaWhatsAppMigrations, "runMetaWhatsAppMigrations");
3237
4499
 
@@ -3314,19 +4576,28 @@ __name(redeemSseTicket, "redeemSseTicket");
3314
4576
  0 && (module.exports = {
3315
4577
  CountInboundLocationsUseCase,
3316
4578
  CreateFlowGraphUseCase,
4579
+ DEFAULT_FALLBACK_LIST_LABEL,
3317
4580
  DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS,
4581
+ DEFAULT_FLOW_TEXT,
4582
+ DEFAULT_MAX_INVALID_ANSWERS,
4583
+ DEFAULT_START_FLOW_KEY,
4584
+ DYNAMIC_CHOICE_MORE_ID,
3318
4585
  DeleteConversationUseCase,
3319
4586
  DeleteFlowGraphUseCase,
3320
4587
  DocumentRepository,
3321
4588
  ExportConversationUseCase,
4589
+ FLOW_RUNTIME_CONTEXT_KEY,
3322
4590
  FlowGraphCache,
3323
4591
  FlowGraphRepository,
4592
+ FlowHandoff,
3324
4593
  FlowInterpreter,
3325
4594
  FlowMediaIdRepository,
3326
4595
  FlowMediaRepository,
4596
+ FlowRunner,
3327
4597
  GetFlowGraphUseCase,
3328
4598
  GetLiveFlowPositionsUseCase,
3329
4599
  INBOUND_LOCATION_CONTENT,
4600
+ InProcessFlowTurnLock,
3330
4601
  InboundEffectsDispatcher,
3331
4602
  IngestInboundMediaUseCase,
3332
4603
  InvalidFlowGraphError,
@@ -3341,11 +4612,13 @@ __name(redeemSseTicket, "redeemSseTicket");
3341
4612
  OptimisticLockError,
3342
4613
  PREVIEW_MEDIA_ID_PREFIX,
3343
4614
  PRODUCT_LIST_LIMIT,
4615
+ PostgresAdvisoryFlowTurnLock,
3344
4616
  ProcessInboundDispatchUseCase,
3345
4617
  PurgeExpiredDocumentsUseCase,
3346
4618
  ReceiveWebhookUseCase,
3347
4619
  RedactInboundLocationsUseCase,
3348
4620
  ReleaseConversationUseCase,
4621
+ RequestHumanConversationUseCase,
3349
4622
  SaveFlowGraphUseCase,
3350
4623
  SendMessageUseCase,
3351
4624
  SessionRepository,
@@ -3359,6 +4632,7 @@ __name(redeemSseTicket, "redeemSseTicket");
3359
4632
  WEBHOOK_CLAIM_TTL_SECONDS,
3360
4633
  WEBHOOK_NONCE_TTL_SECONDS,
3361
4634
  WhatsAppChannelAdapter,
4635
+ buildFlowChoiceMessage,
3362
4636
  buildInboundJobId,
3363
4637
  claimWebhookDelivery,
3364
4638
  confirmWebhookDelivery,
@@ -3371,14 +4645,18 @@ __name(redeemSseTicket, "redeemSseTicket");
3371
4645
  flowGraphs,
3372
4646
  flowMedia,
3373
4647
  isAudioMimeType,
4648
+ isChoiceNode,
3374
4649
  isRetriableTranscriptionError,
3375
4650
  isUnsupportedTranscriptionError,
3376
4651
  issueSseTicket,
3377
4652
  messages,
3378
4653
  metaWhatsAppMigrationsFolder,
3379
4654
  metaWhatsAppSchema,
4655
+ readFlowInbound,
3380
4656
  redeemSseTicket,
3381
4657
  resolveFailureStatus,
4658
+ resolveFlowAnswer,
4659
+ resolveFlowTimeZone,
3382
4660
  resolvePreviewUploadId,
3383
4661
  runMetaWhatsAppMigrations,
3384
4662
  sessions,