@adatechnology/meta-whatsapp-module 0.9.0 → 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
@@ -25,18 +25,26 @@ __export(index_exports, {
25
25
  CreateFlowGraphUseCase: () => CreateFlowGraphUseCase,
26
26
  DEFAULT_FALLBACK_LIST_LABEL: () => DEFAULT_FALLBACK_LIST_LABEL,
27
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,
28
32
  DeleteConversationUseCase: () => DeleteConversationUseCase,
29
33
  DeleteFlowGraphUseCase: () => DeleteFlowGraphUseCase,
30
34
  DocumentRepository: () => DocumentRepository,
31
35
  ExportConversationUseCase: () => ExportConversationUseCase,
36
+ FLOW_RUNTIME_CONTEXT_KEY: () => FLOW_RUNTIME_CONTEXT_KEY,
32
37
  FlowGraphCache: () => FlowGraphCache,
33
38
  FlowGraphRepository: () => FlowGraphRepository,
39
+ FlowHandoff: () => FlowHandoff,
34
40
  FlowInterpreter: () => FlowInterpreter,
35
41
  FlowMediaIdRepository: () => FlowMediaIdRepository,
36
42
  FlowMediaRepository: () => FlowMediaRepository,
43
+ FlowRunner: () => FlowRunner,
37
44
  GetFlowGraphUseCase: () => GetFlowGraphUseCase,
38
45
  GetLiveFlowPositionsUseCase: () => GetLiveFlowPositionsUseCase,
39
46
  INBOUND_LOCATION_CONTENT: () => INBOUND_LOCATION_CONTENT,
47
+ InProcessFlowTurnLock: () => InProcessFlowTurnLock,
40
48
  InboundEffectsDispatcher: () => InboundEffectsDispatcher,
41
49
  IngestInboundMediaUseCase: () => IngestInboundMediaUseCase,
42
50
  InvalidFlowGraphError: () => InvalidFlowGraphError,
@@ -49,8 +57,9 @@ __export(index_exports, {
49
57
  META_WHATSAPP_MIGRATIONS_TABLE: () => META_WHATSAPP_MIGRATIONS_TABLE,
50
58
  MessageRepository: () => MessageRepository,
51
59
  OptimisticLockError: () => OptimisticLockError,
52
- PREVIEW_MEDIA_ID_PREFIX: () => import_meta_whatsapp_contracts9.PREVIEW_MEDIA_ID_PREFIX,
60
+ PREVIEW_MEDIA_ID_PREFIX: () => import_meta_whatsapp_contracts14.PREVIEW_MEDIA_ID_PREFIX,
53
61
  PRODUCT_LIST_LIMIT: () => PRODUCT_LIST_LIMIT,
62
+ PostgresAdvisoryFlowTurnLock: () => PostgresAdvisoryFlowTurnLock,
54
63
  ProcessInboundDispatchUseCase: () => ProcessInboundDispatchUseCase,
55
64
  PurgeExpiredDocumentsUseCase: () => PurgeExpiredDocumentsUseCase,
56
65
  ReceiveWebhookUseCase: () => ReceiveWebhookUseCase,
@@ -70,6 +79,7 @@ __export(index_exports, {
70
79
  WEBHOOK_CLAIM_TTL_SECONDS: () => import_meta_graph_core3.WEBHOOK_CLAIM_TTL_SECONDS,
71
80
  WEBHOOK_NONCE_TTL_SECONDS: () => import_meta_graph_core3.WEBHOOK_NONCE_TTL_SECONDS,
72
81
  WhatsAppChannelAdapter: () => WhatsAppChannelAdapter,
82
+ buildFlowChoiceMessage: () => buildFlowChoiceMessage,
73
83
  buildInboundJobId: () => buildInboundJobId,
74
84
  claimWebhookDelivery: () => claimWebhookDelivery,
75
85
  confirmWebhookDelivery: () => confirmWebhookDelivery,
@@ -82,19 +92,23 @@ __export(index_exports, {
82
92
  flowGraphs: () => flowGraphs,
83
93
  flowMedia: () => flowMedia,
84
94
  isAudioMimeType: () => isAudioMimeType,
95
+ isChoiceNode: () => isChoiceNode,
85
96
  isRetriableTranscriptionError: () => isRetriableTranscriptionError,
86
97
  isUnsupportedTranscriptionError: () => isUnsupportedTranscriptionError,
87
98
  issueSseTicket: () => issueSseTicket,
88
99
  messages: () => messages,
89
100
  metaWhatsAppMigrationsFolder: () => metaWhatsAppMigrationsFolder,
90
101
  metaWhatsAppSchema: () => metaWhatsAppSchema,
102
+ readFlowInbound: () => readFlowInbound,
91
103
  redeemSseTicket: () => redeemSseTicket,
92
104
  resolveFailureStatus: () => resolveFailureStatus,
93
- resolvePreviewUploadId: () => import_meta_whatsapp_contracts9.resolvePreviewUploadId,
105
+ resolveFlowAnswer: () => resolveFlowAnswer,
106
+ resolveFlowTimeZone: () => resolveFlowTimeZone,
107
+ resolvePreviewUploadId: () => import_meta_whatsapp_contracts14.resolvePreviewUploadId,
94
108
  runMetaWhatsAppMigrations: () => runMetaWhatsAppMigrations,
95
109
  sessions: () => sessions,
96
110
  settings: () => settings,
97
- toPreviewMediaId: () => import_meta_whatsapp_contracts9.toPreviewMediaId,
111
+ toPreviewMediaId: () => import_meta_whatsapp_contracts14.toPreviewMediaId,
98
112
  toSessionContract: () => toSessionContract,
99
113
  transcriptionRetryAfterSeconds: () => transcriptionRetryAfterSeconds,
100
114
  verifyWebhookChallenge: () => verifyWebhookChallenge,
@@ -104,7 +118,8 @@ module.exports = __toCommonJS(index_exports);
104
118
 
105
119
  // src/createMetaWhatsAppModule.ts
106
120
  var import_meta_whatsapp_provider = require("@adatechnology/meta-whatsapp-provider");
107
- var import_meta_whatsapp_contracts14 = 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");
108
123
 
109
124
  // src/repositories/SessionRepository.ts
110
125
  var import_drizzle_orm2 = require("drizzle-orm");
@@ -493,6 +508,21 @@ var SessionRepository = class {
493
508
  updatedAt: import_drizzle_orm2.sql`now()`
494
509
  }).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(sessions.companyId, companyId), (0, import_drizzle_orm2.eq)(sessions.whatsappNumber, whatsappNumber)));
495
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
+ }
496
526
  // Marca a chegada de uma mensagem DO CLIENTE. É este carimbo — e não lastActivity, que também
497
527
  // se move em ações do atendente/bot — que define a janela de 24h do WhatsApp: fora dela, só
498
528
  // template aprovado reabre a conversa (ver WindowExpiredError nos contracts).
@@ -1376,13 +1406,6 @@ function toSessionContract(row) {
1376
1406
  };
1377
1407
  }
1378
1408
  __name(toSessionContract, "toSessionContract");
1379
- function extractAnswer(message) {
1380
- const interactive = message.interactive;
1381
- if (interactive?.button_reply) return interactive.button_reply.id;
1382
- if (interactive?.list_reply) return interactive.list_reply.id;
1383
- return message.text?.body;
1384
- }
1385
- __name(extractAnswer, "extractAnswer");
1386
1409
  var InboundEffectsDispatcher = class {
1387
1410
  static {
1388
1411
  __name(this, "InboundEffectsDispatcher");
@@ -1416,7 +1439,13 @@ var InboundEffectsDispatcher = class {
1416
1439
  profileName: job.profileName
1417
1440
  });
1418
1441
  if (outcome?.outcome === "handled") return;
1419
- void extractAnswer(message);
1442
+ await this.params.flowRunner?.handle({
1443
+ companyId,
1444
+ message,
1445
+ ...job.profileName === void 0 ? {} : {
1446
+ profileName: job.profileName
1447
+ }
1448
+ });
1420
1449
  }
1421
1450
  async runStatusEffects(job) {
1422
1451
  const sessionRow = await this.params.sessionRepository.getContext(job.companyId, job.whatsappNumber);
@@ -2037,6 +2066,7 @@ var FlowInterpreter = class {
2037
2066
  return this.moveTo(input, resolveNext(node, branch));
2038
2067
  }
2039
2068
  if (node.type === "action") {
2069
+ if (!node.actionKind) return this.moveTo(input, resolveNext(node, void 0));
2040
2070
  const handler = node.actionKind ? this.actionHandlers.get(node.actionKind) : void 0;
2041
2071
  if (!handler) return {
2042
2072
  kind: "terminal",
@@ -2058,7 +2088,7 @@ var FlowInterpreter = class {
2058
2088
  context: contextAfterAction
2059
2089
  }, nextNodeId2);
2060
2090
  }
2061
- const isChoice = node.type === "menu" || node.questionType === "choice";
2091
+ const isChoice = node.type === "menu" || node.type === "dynamic_choice" || node.questionType === "choice";
2062
2092
  if (input.userAnswer === void 0) {
2063
2093
  return {
2064
2094
  kind: "awaiting-answer",
@@ -2066,9 +2096,10 @@ var FlowInterpreter = class {
2066
2096
  context: input.context
2067
2097
  };
2068
2098
  }
2099
+ const storedValue = input.answerValue !== void 0 ? input.answerValue : input.userAnswer;
2069
2100
  const updatedContext = node.contextKey ? {
2070
2101
  ...input.context,
2071
- [node.contextKey]: input.userAnswer
2102
+ [node.contextKey]: storedValue
2072
2103
  } : input.context;
2073
2104
  const answerId = isChoice ? input.userAnswer : void 0;
2074
2105
  const nextNodeId = resolveNext(node, answerId);
@@ -2111,6 +2142,8 @@ var FlowInterpreter = class {
2111
2142
  const visited = [
2112
2143
  input.currentNodeId
2113
2144
  ];
2145
+ const initialNode = input.graph.nodes[input.currentNodeId];
2146
+ if (options?.enterInitialNode && initialNode) await options.onNodeEntered?.(initialNode, input.context);
2114
2147
  let current = input;
2115
2148
  let steps = 0;
2116
2149
  while (steps < maxSteps) {
@@ -2122,11 +2155,14 @@ var FlowInterpreter = class {
2122
2155
  steps
2123
2156
  };
2124
2157
  visited.push(result.nodeId);
2158
+ const enteredNode = current.graph.nodes[result.nodeId];
2159
+ if (enteredNode) await options?.onNodeEntered?.(enteredNode, result.context);
2125
2160
  current = {
2126
2161
  ...current,
2127
2162
  currentNodeId: result.nodeId,
2128
2163
  context: result.context,
2129
- userAnswer: void 0
2164
+ userAnswer: void 0,
2165
+ answerValue: void 0
2130
2166
  };
2131
2167
  }
2132
2168
  return {
@@ -2138,6 +2174,962 @@ var FlowInterpreter = class {
2138
2174
  }
2139
2175
  };
2140
2176
 
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";
2203
+ }
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
2220
+ };
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
2259
+ });
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}`;
2317
+ });
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
+ };
2341
+ }
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
+ }))
2353
+ };
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
+
2141
3133
  // src/flows/createSendMediaAction.ts
2142
3134
  function mediaTypeFor2(mimeType) {
2143
3135
  if (mimeType.startsWith("image/")) return "image";
@@ -2303,7 +3295,7 @@ async function listAvailableProducts(params) {
2303
3295
  __name(listAvailableProducts, "listAvailableProducts");
2304
3296
 
2305
3297
  // src/repositories/FlowMediaRepository.ts
2306
- var import_drizzle_orm7 = require("drizzle-orm");
3298
+ var import_drizzle_orm8 = require("drizzle-orm");
2307
3299
  var FlowMediaRepository = class {
2308
3300
  static {
2309
3301
  __name(this, "FlowMediaRepository");
@@ -2313,18 +3305,18 @@ var FlowMediaRepository = class {
2313
3305
  this.db = db;
2314
3306
  }
2315
3307
  locationFilter(location) {
2316
- 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));
2317
3309
  }
2318
3310
  // O que o nó realmente envia, na ordem de envio. `active` filtrado aqui e não no chamador:
2319
3311
  // é a razão de a coluna existir, e um chamador que esquecesse do filtro mandaria ao cliente
2320
3312
  // justamente o material que alguém desligou.
2321
3313
  async listActive(location) {
2322
- 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));
2323
3315
  }
2324
3316
  // Inclui os desligados — é a visão do editor, onde desligar precisa continuar visível para
2325
3317
  // poder ser religado.
2326
3318
  async listAll(location) {
2327
- 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));
2328
3320
  }
2329
3321
  /**
2330
3322
  * Anexa um arquivo já existente no storage ao nó.
@@ -2355,7 +3347,7 @@ var FlowMediaRepository = class {
2355
3347
  caption: params.caption ?? null,
2356
3348
  sortOrder: params.sortOrder ?? 0,
2357
3349
  active: true,
2358
- updatedAt: import_drizzle_orm7.sql`now()`
3350
+ updatedAt: import_drizzle_orm8.sql`now()`
2359
3351
  }
2360
3352
  }).returning();
2361
3353
  return row;
@@ -2371,8 +3363,8 @@ var FlowMediaRepository = class {
2371
3363
  ...params.active !== void 0 ? {
2372
3364
  active: params.active
2373
3365
  } : {},
2374
- updatedAt: import_drizzle_orm7.sql`now()`
2375
- }).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();
2376
3368
  return row;
2377
3369
  }
2378
3370
  /**
@@ -2381,17 +3373,17 @@ var FlowMediaRepository = class {
2381
3373
  * host, que é dono da biblioteca de arquivos.
2382
3374
  */
2383
3375
  async detach(params) {
2384
- 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)));
2385
3377
  }
2386
3378
  // Chamado ao salvar o grafo: nós apagados no editor deixam linhas que nada mais alcança.
2387
3379
  async detachRemovedNodes(params) {
2388
- const condition = params.existingNodeIds.length === 0 ? void 0 : import_drizzle_orm7.sql`${flowMedia.nodeId} NOT IN ${params.existingNodeIds}`;
2389
- 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));
2390
3382
  }
2391
3383
  };
2392
3384
 
2393
3385
  // src/repositories/FlowMediaIdRepository.ts
2394
- var import_drizzle_orm8 = require("drizzle-orm");
3386
+ var import_drizzle_orm9 = require("drizzle-orm");
2395
3387
  var FlowMediaIdRepository = class {
2396
3388
  static {
2397
3389
  __name(this, "FlowMediaIdRepository");
@@ -2403,7 +3395,7 @@ var FlowMediaIdRepository = class {
2403
3395
  async get(params) {
2404
3396
  const rows = await this.db.select({
2405
3397
  ids: flowMedia.metaMediaIds
2406
- }).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);
2407
3399
  return rows[0]?.ids?.[params.senderKey];
2408
3400
  }
2409
3401
  /**
@@ -2415,23 +3407,23 @@ var FlowMediaIdRepository = class {
2415
3407
  */
2416
3408
  async set(params) {
2417
3409
  await this.db.update(flowMedia).set({
2418
- metaMediaIds: import_drizzle_orm8.sql`jsonb_set(${flowMedia.metaMediaIds}, ARRAY[${params.senderKey}::text], to_jsonb(${params.mediaId}::text), true)`
2419
- }).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));
2420
3412
  }
2421
3413
  /** Remove só a chave deste número — o id do outro número continua válido. */
2422
3414
  async clear(params) {
2423
3415
  await this.db.update(flowMedia).set({
2424
- metaMediaIds: import_drizzle_orm8.sql`${flowMedia.metaMediaIds} - ${params.senderKey}::text`
2425
- }).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));
2426
3418
  }
2427
3419
  };
2428
3420
 
2429
3421
  // src/channel/WhatsAppChannelAdapter.ts
2430
3422
  var import_meta_graph_core2 = require("@adatechnology/meta-graph-core");
2431
- var import_meta_whatsapp_contracts10 = require("@adatechnology/meta-whatsapp-contracts");
3423
+ var import_meta_whatsapp_contracts15 = require("@adatechnology/meta-whatsapp-contracts");
2432
3424
 
2433
3425
  // src/channel/previewMedia.ts
2434
- var import_meta_whatsapp_contracts9 = require("@adatechnology/meta-whatsapp-contracts");
3426
+ var import_meta_whatsapp_contracts14 = require("@adatechnology/meta-whatsapp-contracts");
2435
3427
 
2436
3428
  // src/channel/WhatsAppChannelAdapter.ts
2437
3429
  var WhatsAppChannelAdapter = class {
@@ -2440,25 +3432,40 @@ var WhatsAppChannelAdapter = class {
2440
3432
  }
2441
3433
  messages;
2442
3434
  previewMedia;
2443
- constructor(messages2, previewMedia) {
3435
+ previewContacts;
3436
+ constructor(messages2, previewMedia, previewContacts) {
2444
3437
  this.messages = messages2;
2445
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()}`;
2446
3445
  }
2447
3446
  async translateErrors(operation) {
2448
3447
  try {
2449
3448
  return await operation();
2450
3449
  } catch (error) {
2451
- if (error instanceof import_meta_graph_core2.WhatsAppWindowExpiredError) throw new import_meta_whatsapp_contracts10.WindowExpiredError();
3450
+ if (error instanceof import_meta_graph_core2.WhatsAppWindowExpiredError) throw new import_meta_whatsapp_contracts15.WindowExpiredError();
2452
3451
  throw error;
2453
3452
  }
2454
3453
  }
2455
3454
  async sendText(to, body) {
3455
+ const previewId = this.previewMessageId(to);
3456
+ if (previewId) return {
3457
+ externalMessageId: previewId
3458
+ };
2456
3459
  const result = await this.translateErrors(() => this.messages.sendText(to, body));
2457
3460
  return {
2458
3461
  externalMessageId: result.waMessageId
2459
3462
  };
2460
3463
  }
2461
3464
  async sendMedia(params) {
3465
+ const previewId = this.previewMessageId(params.to);
3466
+ if (previewId) return {
3467
+ externalMessageId: previewId
3468
+ };
2462
3469
  const result = await this.translateErrors(() => this.messages.sendMedia(params));
2463
3470
  return {
2464
3471
  externalMessageId: result.waMessageId,
@@ -2466,12 +3473,20 @@ var WhatsAppChannelAdapter = class {
2466
3473
  };
2467
3474
  }
2468
3475
  async sendTemplate(params) {
3476
+ const previewId = this.previewMessageId(params.to);
3477
+ if (previewId) return {
3478
+ externalMessageId: previewId
3479
+ };
2469
3480
  const result = await this.translateErrors(() => this.messages.sendTemplate(params));
2470
3481
  return {
2471
3482
  externalMessageId: result.waMessageId
2472
3483
  };
2473
3484
  }
2474
3485
  async sendInteractiveList(params) {
3486
+ const previewId = this.previewMessageId(params.to);
3487
+ if (previewId) return {
3488
+ externalMessageId: previewId
3489
+ };
2475
3490
  const sections = (params.sections ?? [
2476
3491
  {
2477
3492
  rows: params.rows ?? []
@@ -2497,6 +3512,10 @@ var WhatsAppChannelAdapter = class {
2497
3512
  };
2498
3513
  }
2499
3514
  async sendInteractiveButtons(params) {
3515
+ const previewId = this.previewMessageId(params.to);
3516
+ if (previewId) return {
3517
+ externalMessageId: previewId
3518
+ };
2500
3519
  const result = await this.translateErrors(() => this.messages.sendInteractiveButtons({
2501
3520
  to: params.to,
2502
3521
  bodyText: params.body,
@@ -2507,6 +3526,10 @@ var WhatsAppChannelAdapter = class {
2507
3526
  };
2508
3527
  }
2509
3528
  async sendProductList(params) {
3529
+ const previewId = this.previewMessageId(params.to);
3530
+ if (previewId) return {
3531
+ externalMessageId: previewId
3532
+ };
2510
3533
  const result = await this.translateErrors(() => this.messages.sendProductListMessage({
2511
3534
  to: params.to,
2512
3535
  headerText: params.headerText,
@@ -2527,7 +3550,7 @@ var WhatsAppChannelAdapter = class {
2527
3550
  * tentar buscá-lo lá renderia um 404 confuso em vez do áudio que o operador acabou de gravar.
2528
3551
  */
2529
3552
  async fetchMediaAsBase64(mediaId) {
2530
- const uploadId = this.previewMedia?.isEnabled ? (0, import_meta_whatsapp_contracts9.resolvePreviewUploadId)(mediaId) : void 0;
3553
+ const uploadId = this.previewMedia?.isEnabled ? (0, import_meta_whatsapp_contracts14.resolvePreviewUploadId)(mediaId) : void 0;
2531
3554
  if (uploadId) {
2532
3555
  const buffer = await this.previewMedia.objectStorage.getObject(uploadId);
2533
3556
  return {
@@ -2540,19 +3563,19 @@ var WhatsAppChannelAdapter = class {
2540
3563
  };
2541
3564
 
2542
3565
  // src/channel/ReceiveWebhook.use-case.ts
2543
- var import_meta_whatsapp_contracts13 = require("@adatechnology/meta-whatsapp-contracts");
3566
+ var import_meta_whatsapp_contracts18 = require("@adatechnology/meta-whatsapp-contracts");
2544
3567
 
2545
3568
  // src/channel/webhookSecurity.ts
2546
3569
  var import_meta_graph_core3 = require("@adatechnology/meta-graph-core");
2547
- var import_meta_whatsapp_contracts11 = require("@adatechnology/meta-whatsapp-contracts");
3570
+ var import_meta_whatsapp_contracts16 = require("@adatechnology/meta-whatsapp-contracts");
2548
3571
  var WEBHOOK_NONCE_NAMESPACE = "meta-whatsapp";
2549
3572
  function verifyWebhookChallenge(params) {
2550
- if (!(0, import_meta_graph_core3.isValidWebhookChallenge)(params)) throw new import_meta_whatsapp_contracts11.InvalidWebhookSignatureError();
3573
+ if (!(0, import_meta_graph_core3.isValidWebhookChallenge)(params)) throw new import_meta_whatsapp_contracts16.InvalidWebhookSignatureError();
2551
3574
  return params.challenge;
2552
3575
  }
2553
3576
  __name(verifyWebhookChallenge, "verifyWebhookChallenge");
2554
3577
  function verifyWebhookSignature(params) {
2555
- if (!(0, import_meta_graph_core3.isValidWebhookSignature)(params)) throw new import_meta_whatsapp_contracts11.InvalidWebhookSignatureError();
3578
+ if (!(0, import_meta_graph_core3.isValidWebhookSignature)(params)) throw new import_meta_whatsapp_contracts16.InvalidWebhookSignatureError();
2556
3579
  }
2557
3580
  __name(verifyWebhookSignature, "verifyWebhookSignature");
2558
3581
  function deliveryKey(signatureHeader) {
@@ -2572,10 +3595,10 @@ async function confirmWebhookDelivery(params) {
2572
3595
  __name(confirmWebhookDelivery, "confirmWebhookDelivery");
2573
3596
 
2574
3597
  // src/channel/IngestInboundMedia.use-case.ts
2575
- var import_drizzle_orm9 = require("drizzle-orm");
3598
+ var import_drizzle_orm10 = require("drizzle-orm");
2576
3599
 
2577
3600
  // src/use-cases/TranscribeAudio.use-case.ts
2578
- var import_meta_whatsapp_contracts12 = require("@adatechnology/meta-whatsapp-contracts");
3601
+ var import_meta_whatsapp_contracts17 = require("@adatechnology/meta-whatsapp-contracts");
2579
3602
 
2580
3603
  // src/transcription.types.ts
2581
3604
  var TRANSCRIPTION_STATUS = {
@@ -2636,7 +3659,7 @@ var TranscribeAudioUseCase = class {
2636
3659
  }
2637
3660
  if (this.dependencies.resolvePolicy) {
2638
3661
  const policy = await this.dependencies.resolvePolicy(params.companyId);
2639
- if (!policy.isEnabled) throw new import_meta_whatsapp_contracts12.TranscriptionDisabledError();
3662
+ if (!policy.isEnabled) throw new import_meta_whatsapp_contracts17.TranscriptionDisabledError();
2640
3663
  }
2641
3664
  const audio = extractAudioReference(message);
2642
3665
  const buffer = await this.dependencies.objectStorage.getObject(audio.uploadId);
@@ -2713,11 +3736,11 @@ function extractAudioReference(message) {
2713
3736
  const audio = payload["audio"];
2714
3737
  const mimeType = typeof payload["mimeType"] === "string" ? payload["mimeType"] : audio?.mime_type;
2715
3738
  if (!isAudioMimeType(mimeType) && !audio) {
2716
- throw new import_meta_whatsapp_contracts12.MessageNotAudioError(message.id, message.type);
3739
+ throw new import_meta_whatsapp_contracts17.MessageNotAudioError(message.id, message.type);
2717
3740
  }
2718
3741
  const uploadId = payload["uploadId"];
2719
3742
  if (typeof uploadId !== "string" || uploadId.length === 0) {
2720
- throw new import_meta_whatsapp_contracts12.AudioNotIngestedError(message.id);
3743
+ throw new import_meta_whatsapp_contracts17.AudioNotIngestedError(message.id);
2721
3744
  }
2722
3745
  return {
2723
3746
  uploadId,
@@ -2744,7 +3767,7 @@ var IngestInboundMediaUseCase = class {
2744
3767
  this.transcription = transcription;
2745
3768
  }
2746
3769
  async execute(params) {
2747
- 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);
2748
3771
  if (!message) throw new Error(`Mensagem ${params.messageId} n\xE3o encontrada para ingest\xE3o de m\xEDdia`);
2749
3772
  const payload = message.payload ?? {};
2750
3773
  if (payload["uploadId"] && payload["sourceMediaId"] === params.sourceMediaId) {
@@ -2775,7 +3798,7 @@ var IngestInboundMediaUseCase = class {
2775
3798
  };
2776
3799
  await this.db.update(messages).set({
2777
3800
  payload: updatedPayload
2778
- }).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)));
2779
3802
  await this.documentRepository?.link({
2780
3803
  companyId: params.companyId,
2781
3804
  sessionId: message.sessionId,
@@ -2933,8 +3956,8 @@ function extractPayload(message, { isLocationRedacted } = DEFAULT_EXTRACTION_OPT
2933
3956
  }
2934
3957
  __name(extractPayload, "extractPayload");
2935
3958
  var ACCOUNT_EVENT_FIELDS = [
2936
- import_meta_whatsapp_contracts13.WHATSAPP_WEBHOOK_FIELDS.TEMPLATE_STATUS_UPDATE,
2937
- import_meta_whatsapp_contracts13.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
2938
3961
  ];
2939
3962
  function isAccountEventField(field) {
2940
3963
  return field !== void 0 && ACCOUNT_EVENT_FIELDS.includes(field);
@@ -2954,6 +3977,9 @@ var ReceiveWebhookUseCase = class {
2954
3977
  } : {},
2955
3978
  ...params.realtime ? {
2956
3979
  realtime: params.realtime
3980
+ } : {},
3981
+ ...params.flowRunner ? {
3982
+ flowRunner: params.flowRunner
2957
3983
  } : {}
2958
3984
  });
2959
3985
  }
@@ -2973,7 +3999,7 @@ var ReceiveWebhookUseCase = class {
2973
3999
  ...EMPTY_RESULT
2974
4000
  };
2975
4001
  const rawText = typeof input.rawBody === "string" ? input.rawBody : input.rawBody.toString("utf8");
2976
- const parsed = import_meta_whatsapp_contracts13.whatsAppWebhookPayloadSchema.safeParse(JSON.parse(rawText));
4002
+ const parsed = import_meta_whatsapp_contracts18.whatsAppWebhookPayloadSchema.safeParse(JSON.parse(rawText));
2977
4003
  if (!parsed.success) {
2978
4004
  await this.params.hooks?.onUnhandledWebhookEvent?.({
2979
4005
  field: void 0,
@@ -3006,7 +4032,7 @@ var ReceiveWebhookUseCase = class {
3006
4032
  continue;
3007
4033
  }
3008
4034
  for (const message of change.value.messages ?? []) {
3009
- const profileName = (0, import_meta_whatsapp_contracts13.resolveContactProfileName)({
4035
+ const profileName = (0, import_meta_whatsapp_contracts18.resolveContactProfileName)({
3010
4036
  contacts: change.value.contacts,
3011
4037
  from: message.from
3012
4038
  });
@@ -3044,8 +4070,8 @@ var ReceiveWebhookUseCase = class {
3044
4070
  // Devolve `false` quando o corpo não bate com o schema do field — o chamador conta como não
3045
4071
  // tratado. O host é avisado nos dois casos, mas com `reason` diferente.
3046
4072
  async handleAccountEvent(change) {
3047
- if (change.field === import_meta_whatsapp_contracts13.WHATSAPP_WEBHOOK_FIELDS.TEMPLATE_STATUS_UPDATE) {
3048
- const update = import_meta_whatsapp_contracts13.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);
3049
4075
  if (!update.success) {
3050
4076
  await this.params.hooks?.onUnhandledWebhookEvent?.({
3051
4077
  field: change.field,
@@ -3057,7 +4083,7 @@ var ReceiveWebhookUseCase = class {
3057
4083
  await this.params.hooks?.onTemplateStatusUpdate?.(update.data);
3058
4084
  return true;
3059
4085
  }
3060
- const quality = import_meta_whatsapp_contracts13.whatsAppPhoneNumberQualityUpdateSchema.safeParse(change.value);
4086
+ const quality = import_meta_whatsapp_contracts18.whatsAppPhoneNumberQualityUpdateSchema.safeParse(change.value);
3061
4087
  if (!quality.success) {
3062
4088
  await this.params.hooks?.onUnhandledWebhookEvent?.({
3063
4089
  field: change.field,
@@ -3188,7 +4214,7 @@ var StorePreviewMediaUseCase = class {
3188
4214
  key
3189
4215
  });
3190
4216
  return {
3191
- mediaId: (0, import_meta_whatsapp_contracts9.toPreviewMediaId)(uploadId),
4217
+ mediaId: (0, import_meta_whatsapp_contracts14.toPreviewMediaId)(uploadId),
3192
4218
  uploadId
3193
4219
  };
3194
4220
  }
@@ -3210,7 +4236,9 @@ function createMetaWhatsAppModule(params) {
3210
4236
  isEnabled: true,
3211
4237
  objectStorage: providers.objectStorage
3212
4238
  } : void 0;
3213
- const channel = new WhatsAppChannelAdapter(messageProvider, previewMediaSupport);
4239
+ const channel = new WhatsAppChannelAdapter(messageProvider, previewMediaSupport, params.features?.previewContacts ? {
4240
+ isEnabled: true
4241
+ } : void 0);
3214
4242
  const sessionRepository = new SessionRepository(db);
3215
4243
  const messageRepository = new MessageRepository(db);
3216
4244
  const settingsRepository = new SettingsRepository(db);
@@ -3221,6 +4249,40 @@ function createMetaWhatsAppModule(params) {
3221
4249
  const flowMediaRepository = new FlowMediaRepository(db);
3222
4250
  const logMessage = new LogMessageUseCase(sessionRepository, messageRepository, providers.realtime, providers.moderator);
3223
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
+ }
3224
4286
  const receiveWebhook = new ReceiveWebhookUseCase({
3225
4287
  appSecret: config.appSecret,
3226
4288
  phoneNumberId: config.phoneNumberId,
@@ -3234,11 +4296,13 @@ function createMetaWhatsAppModule(params) {
3234
4296
  ...providers.inboundQueue ? {
3235
4297
  inboundQueue: providers.inboundQueue
3236
4298
  } : {},
3237
- redactInboundLocation: params.features?.redactInboundLocation ?? false
4299
+ redactInboundLocation: params.features?.redactInboundLocation ?? false,
4300
+ ...flowRunner ? {
4301
+ flowRunner
4302
+ } : {}
3238
4303
  });
3239
- const flowInterpreter = flowEngineEnabled ? new FlowInterpreter() : void 0;
3240
4304
  if (flowInterpreter && providers.objectStorage?.getObject) {
3241
- flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts14.FLOW_ACTION_KIND.SEND_MEDIA, createSendMediaAction({
4305
+ flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts19.FLOW_ACTION_KIND.SEND_MEDIA, createSendMediaAction({
3242
4306
  flowMediaRepository,
3243
4307
  objectStorage: providers.objectStorage,
3244
4308
  logMessage,
@@ -3255,7 +4319,7 @@ function createMetaWhatsAppModule(params) {
3255
4319
  }));
3256
4320
  }
3257
4321
  if (flowInterpreter && providers.catalog && config.catalogId) {
3258
- flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts14.FLOW_ACTION_KIND.SEND_PRODUCT_LIST, createSendProductListAction({
4322
+ flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts19.FLOW_ACTION_KIND.SEND_PRODUCT_LIST, createSendProductListAction({
3259
4323
  catalog: providers.catalog,
3260
4324
  catalogId: config.catalogId,
3261
4325
  logMessage,
@@ -3307,7 +4371,7 @@ function createMetaWhatsAppModule(params) {
3307
4371
  takeover: new TakeoverConversationUseCase(sessionRepository, providers.realtime, hooks),
3308
4372
  release: new ReleaseConversationUseCase(sessionRepository, providers.realtime, hooks),
3309
4373
  // Marca o pedido de atendimento (fila "aguardando atendimento") e dispara `onHumanRequested`.
3310
- requestHuman: new RequestHumanConversationUseCase(sessionRepository, providers.realtime, hooks),
4374
+ requestHuman,
3311
4375
  list: new ListConversationsUseCase(sessionRepository),
3312
4376
  listMessages: new ListMessagesUseCase(sessionRepository, messageRepository),
3313
4377
  listDocuments,
@@ -3346,6 +4410,18 @@ function createMetaWhatsAppModule(params) {
3346
4410
  webhook: {
3347
4411
  receive: receiveWebhook,
3348
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"),
3349
4425
  verifyChallenge: /* @__PURE__ */ __name((query) => verifyWebhookChallenge({
3350
4426
  ...query,
3351
4427
  expectedToken: config.webhookVerifyToken
@@ -3359,6 +4435,9 @@ function createMetaWhatsAppModule(params) {
3359
4435
  } : {},
3360
4436
  ...providers.realtime ? {
3361
4437
  realtime: providers.realtime
4438
+ } : {},
4439
+ ...flowRunner ? {
4440
+ flowRunner
3362
4441
  } : {}
3363
4442
  }), hooks)
3364
4443
  },
@@ -3366,6 +4445,12 @@ function createMetaWhatsAppModule(params) {
3366
4445
  flows: flowInterpreter ? {
3367
4446
  interpreter: flowInterpreter,
3368
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"),
3369
4454
  get: new GetFlowGraphUseCase(flowGraphRepository),
3370
4455
  list: new ListFlowGraphsUseCase(flowGraphRepository),
3371
4456
  create: new CreateFlowGraphUseCase(flowGraphRepository),
@@ -3493,18 +4578,26 @@ __name(redeemSseTicket, "redeemSseTicket");
3493
4578
  CreateFlowGraphUseCase,
3494
4579
  DEFAULT_FALLBACK_LIST_LABEL,
3495
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,
3496
4585
  DeleteConversationUseCase,
3497
4586
  DeleteFlowGraphUseCase,
3498
4587
  DocumentRepository,
3499
4588
  ExportConversationUseCase,
4589
+ FLOW_RUNTIME_CONTEXT_KEY,
3500
4590
  FlowGraphCache,
3501
4591
  FlowGraphRepository,
4592
+ FlowHandoff,
3502
4593
  FlowInterpreter,
3503
4594
  FlowMediaIdRepository,
3504
4595
  FlowMediaRepository,
4596
+ FlowRunner,
3505
4597
  GetFlowGraphUseCase,
3506
4598
  GetLiveFlowPositionsUseCase,
3507
4599
  INBOUND_LOCATION_CONTENT,
4600
+ InProcessFlowTurnLock,
3508
4601
  InboundEffectsDispatcher,
3509
4602
  IngestInboundMediaUseCase,
3510
4603
  InvalidFlowGraphError,
@@ -3519,6 +4612,7 @@ __name(redeemSseTicket, "redeemSseTicket");
3519
4612
  OptimisticLockError,
3520
4613
  PREVIEW_MEDIA_ID_PREFIX,
3521
4614
  PRODUCT_LIST_LIMIT,
4615
+ PostgresAdvisoryFlowTurnLock,
3522
4616
  ProcessInboundDispatchUseCase,
3523
4617
  PurgeExpiredDocumentsUseCase,
3524
4618
  ReceiveWebhookUseCase,
@@ -3538,6 +4632,7 @@ __name(redeemSseTicket, "redeemSseTicket");
3538
4632
  WEBHOOK_CLAIM_TTL_SECONDS,
3539
4633
  WEBHOOK_NONCE_TTL_SECONDS,
3540
4634
  WhatsAppChannelAdapter,
4635
+ buildFlowChoiceMessage,
3541
4636
  buildInboundJobId,
3542
4637
  claimWebhookDelivery,
3543
4638
  confirmWebhookDelivery,
@@ -3550,14 +4645,18 @@ __name(redeemSseTicket, "redeemSseTicket");
3550
4645
  flowGraphs,
3551
4646
  flowMedia,
3552
4647
  isAudioMimeType,
4648
+ isChoiceNode,
3553
4649
  isRetriableTranscriptionError,
3554
4650
  isUnsupportedTranscriptionError,
3555
4651
  issueSseTicket,
3556
4652
  messages,
3557
4653
  metaWhatsAppMigrationsFolder,
3558
4654
  metaWhatsAppSchema,
4655
+ readFlowInbound,
3559
4656
  redeemSseTicket,
3560
4657
  resolveFailureStatus,
4658
+ resolveFlowAnswer,
4659
+ resolveFlowTimeZone,
3561
4660
  resolvePreviewUploadId,
3562
4661
  runMetaWhatsAppMigrations,
3563
4662
  sessions,