@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.d.ts CHANGED
@@ -1,7 +1,8 @@
1
+ import { PreviewInboundCommand, PreviewPayloadEnvelope } from '@adatechnology/meta-whatsapp-contracts/testing';
1
2
  import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
2
3
  import { PgAsyncDatabase, PgQueryResultHKT } from 'drizzle-orm/pg-core';
3
4
  import * as _adatechnology_meta_whatsapp_contracts from '@adatechnology/meta-whatsapp-contracts';
4
- import { TranscriptionMode, SessionState, SessionMode, ConversationSummary, MessageDirection, MessageSender, MessageStatus, WhatsAppStatusError, CacheInterface, FlowGraphData, FlowGraphSummary, LiveFlowPosition, WhatsAppSettings, RealtimeNotifierInterface, ChannelAdapterInterface, ObjectStorageInterface, InteractiveMessage, MetaWhatsAppHooks, FlowActionKind, FlowActionHandler, ConversationSession, WhatsAppMessage, WhatsAppStatus, SubjectResolverInterface, CatalogPort, SendChannelMediaParams, ChannelInteractiveListParams, ChannelInteractiveButtonsParams } from '@adatechnology/meta-whatsapp-contracts';
5
+ import { TranscriptionMode, SessionState, SessionMode, ConversationSummary, MessageDirection, MessageSender, MessageStatus, WhatsAppStatusError, CacheInterface, FlowGraphData, FlowGraphSummary, LiveFlowPosition, WhatsAppSettings, RealtimeNotifierInterface, ChannelAdapterInterface, ObjectStorageInterface, InteractiveMessage, MetaWhatsAppHooks, FlowActionKind, FlowActionHandler, ConversationSession, FlowNodeData, FlowAnswerRejection, FlowDateLocale, BusinessHours, InterpolateFlowTextOptions, DynamicChoiceProvider, WhatsAppMessage, WhatsAppStatus, SubjectResolverInterface, CatalogPort, SendChannelMediaParams, ChannelInteractiveListParams, ChannelInteractiveButtonsParams, FlowClock } from '@adatechnology/meta-whatsapp-contracts';
5
6
  export { PREVIEW_MEDIA_ID_PREFIX, TranscriptionMode, resolvePreviewUploadId, toPreviewMediaId } from '@adatechnology/meta-whatsapp-contracts';
6
7
  import { WhatsAppMessageProvider } from '@adatechnology/meta-whatsapp-provider';
7
8
  export { WEBHOOK_CLAIM_TTL_SECONDS, WEBHOOK_NONCE_TTL_SECONDS } from '@adatechnology/meta-graph-core';
@@ -1389,6 +1390,17 @@ declare class SessionRepository {
1389
1390
  patchContext<TSessionContext extends Record<string, unknown> = Record<string, unknown>>(companyId: string, whatsappNumber: string, patch: Partial<TSessionContext>): Promise<void>;
1390
1391
  readContext<TSessionContext extends Record<string, unknown> = Record<string, unknown>>(companyId: string, whatsappNumber: string): Promise<TSessionContext | undefined>;
1391
1392
  setFlowPosition(companyId: string, whatsappNumber: string, flowKey: string | null, currentNodeId: string | null): Promise<void>;
1393
+ /**
1394
+ * Posição no grafo e contexto numa escrita só — é o que o runner grava a cada mensagem. Em duas
1395
+ * escritas, uma falha no meio deixaria a conversa num nó novo com as respostas do anterior.
1396
+ * Não toca em `currentState`, `mode` nem `humanRequestedAt`: uma ação de encaminhamento que rodou
1397
+ * no mesmo passo já os mudou, e regravá-los desfaria isso.
1398
+ */
1399
+ saveFlowProgress(companyId: string, whatsappNumber: string, progress: {
1400
+ flowKey: string | null;
1401
+ currentNodeId: string | null;
1402
+ context: Record<string, unknown>;
1403
+ }): Promise<void>;
1392
1404
  touchInbound(companyId: string, whatsappNumber: string): Promise<void>;
1393
1405
  hoursSinceLastInbound(companyId: string, whatsappNumber: string): Promise<number | undefined>;
1394
1406
  setMode(companyId: string, whatsappNumber: string, mode: SessionMode, assignedUserId?: string | null, clearHumanRequest?: boolean): Promise<void>;
@@ -2137,6 +2149,11 @@ interface FlowStepInput {
2137
2149
  graph: FlowGraphData;
2138
2150
  currentNodeId: string;
2139
2151
  userAnswer?: string;
2152
+ /**
2153
+ * Valor a guardar em `contextKey` no lugar do texto cru — a data já convertida, o número já lido.
2154
+ * `userAnswer` continua sendo o que escolhe o ramo (`byAnswer`).
2155
+ */
2156
+ answerValue?: unknown;
2140
2157
  context: Record<string, unknown>;
2141
2158
  session: ConversationSession;
2142
2159
  channel: ChannelAdapterInterface;
@@ -2175,14 +2192,265 @@ type FlowRunResult = ({
2175
2192
  visited: string[];
2176
2193
  steps: number;
2177
2194
  };
2195
+ type FlowRunOptions = {
2196
+ maxSteps?: number;
2197
+ /**
2198
+ * Chamado ao entrar em cada nó, com o contexto daquele momento — é onde o runner envia o
2199
+ * `directMessage`. Uma ação que devolve contexto já está refletida no nó seguinte.
2200
+ */
2201
+ onNodeEntered?: (node: FlowNodeData, context: Record<string, unknown>) => Promise<void>;
2202
+ /** Também dispara `onNodeEntered` para o nó de partida (início de fluxo, salto por palavra-chave). */
2203
+ enterInitialNode?: boolean;
2204
+ };
2178
2205
  declare class FlowInterpreter {
2179
2206
  private readonly actionHandlers;
2180
2207
  registerFlowAction(kind: FlowActionKind, handler: FlowActionHandler): void;
2181
2208
  step(input: FlowStepInput): Promise<FlowStepResult>;
2182
2209
  private moveTo;
2183
- run(input: FlowStepInput, options?: {
2184
- maxSteps?: number;
2185
- }): Promise<FlowRunResult>;
2210
+ run(input: FlowStepInput, options?: FlowRunOptions): Promise<FlowRunResult>;
2211
+ }
2212
+
2213
+ /**
2214
+ * Copyright (c) 2026 Ada Technology. MIT License.
2215
+ *
2216
+ * Configuração do runner de fluxo. Tudo opcional: sem nada, o runner atende pelo fluxo `main`, com
2217
+ * os textos padrão em pt-BR e encaminhamento a uma pessoa depois de 2 respostas inválidas.
2218
+ */
2219
+
2220
+ /** `restart` volta ao início do fluxo de partida; `handoff` chama uma pessoa; `flow:<chave>` abre outro fluxo. */
2221
+ type FlowGlobalKeywordTarget = 'restart' | 'handoff' | `flow:${string}`;
2222
+ /** Palavras que valem em qualquer nó ("menu", "atendente"), comparadas sem acento e sem caixa. */
2223
+ type FlowGlobalKeyword = {
2224
+ readonly keywords: readonly string[];
2225
+ readonly target: FlowGlobalKeywordTarget;
2226
+ };
2227
+ type FlowHandoffConfig = {
2228
+ /** Mensagem dentro do horário (ou sempre, sem `businessHours`). Aceita `{{chave}}`. */
2229
+ readonly message?: string;
2230
+ /** Mensagem fora do horário. Ausente, vale `message`. */
2231
+ readonly outOfHoursMessage?: string;
2232
+ /** Fixo, ou resolvido por empresa a cada encaminhamento (o painel pode mudar sem deploy). */
2233
+ readonly businessHours?: BusinessHours | ((companyId: string) => Promise<BusinessHours | undefined>);
2234
+ };
2235
+ type FlowVariablesResolver = (params: {
2236
+ readonly session: ConversationSession;
2237
+ readonly profileName?: string;
2238
+ }) => Promise<Readonly<Record<string, unknown>>>;
2239
+ type FlowRunnerConfig = {
2240
+ /** Fluxo de quem chega sem conversa em andamento. Padrão `main`. */
2241
+ readonly startFlowKey?: string;
2242
+ readonly globalKeywords?: readonly FlowGlobalKeyword[];
2243
+ /** Respostas inválidas seguidas no mesmo nó antes de chamar uma pessoa. Padrão 2; o nó pode sobrescrever. */
2244
+ readonly maxInvalidAnswers?: number;
2245
+ /** Texto de nova tentativa quando o nó não declara `fallbackMessage`. */
2246
+ readonly defaultFallbackMessage?: string;
2247
+ /** Texto de nova tentativa por motivo, antes do padrão ("essa data já passou"). */
2248
+ readonly rejectionMessages?: Partial<Record<FlowAnswerRejection, string>>;
2249
+ /** Corpo de escolha quando o nó não tem `question` (a Meta exige corpo). */
2250
+ readonly choicePrompt?: string;
2251
+ readonly listButtonLabel?: string;
2252
+ /** Rótulo da linha que pede a próxima página de um `dynamic_choice`. */
2253
+ readonly seeMoreLabel?: string;
2254
+ readonly dateLocale?: FlowDateLocale;
2255
+ /**
2256
+ * Fuso de "hoje" na validação de data (IANA). Obrigatório — ou derivado de
2257
+ * `handoff.businessHours.timeZone` quando o horário é fixo: servidor em UTC aceitaria "hoje" errado
2258
+ * entre 21h e meia-noite no Brasil.
2259
+ */
2260
+ readonly timeZone?: string;
2261
+ /** Resposta que não casa com opção: `reask` (padrão) ou `default` (segue `next.default`). O nó sobrescreve. */
2262
+ readonly unmatchedChoice?: 'reask' | 'default';
2263
+ /** Resposta em áudio, imagem, localização… num nó que espera texto: avisa e repergunta, sem contar tentativa. */
2264
+ readonly nonTextAnswerMessage?: string;
2265
+ readonly handoff?: FlowHandoffConfig;
2266
+ /**
2267
+ * Conversa que pediu atendimento e saiu do fluxo: `silent` (padrão) não responde até alguém
2268
+ * assumir ou devolver ao bot — palavras globais continuam valendo; `continue` reabre o fluxo.
2269
+ */
2270
+ readonly whileAwaitingHuman?: 'silent' | 'continue';
2271
+ /** Variáveis do host para `{{chave}}` (dados do cadastro, por exemplo). O contexto do fluxo tem precedência. */
2272
+ readonly resolveVariables?: FlowVariablesResolver;
2273
+ readonly formatValue?: InterpolateFlowTextOptions['formatValue'];
2274
+ readonly dynamicChoiceProviders?: Readonly<Record<string, DynamicChoiceProvider>>;
2275
+ /** Saltos `flow:` seguidos numa mesma mensagem antes de desistir (protege de ciclo entre fluxos). Padrão 5. */
2276
+ readonly maxCrossFlowJumps?: number;
2277
+ /** Relógio injetável para teste. */
2278
+ readonly now?: () => Date;
2279
+ };
2280
+ type FlowRunnerOutcome = 'handled' | 'duplicate' | 'no-session' | 'human-mode' | 'awaiting-human' | 'no-flow';
2281
+
2282
+ /**
2283
+ * Copyright (c) 2026 Ada Technology. MIT License.
2284
+ *
2285
+ * Encaminhamento a uma pessoa: põe a conversa na fila (`requestHuman`, que dispara
2286
+ * `onHumanRequested` e `onConversationModeChanged`) e avisa o cliente com o texto certo para a hora.
2287
+ *
2288
+ * Um só caminho para os três gatilhos — o nó `handoff`, a palavra global e o excesso de respostas
2289
+ * inválidas. Três cópias divergiriam no texto e no horário.
2290
+ */
2291
+
2292
+ type FlowHandoffDependencies = {
2293
+ readonly requestHuman: RequestHumanConversationUseCase;
2294
+ readonly sendMessage: SendMessageUseCase;
2295
+ readonly startState: SessionState;
2296
+ readonly config: FlowHandoffConfig;
2297
+ readonly now: () => Date;
2298
+ readonly interpolation: InterpolateFlowTextOptions;
2299
+ readonly hooks?: Pick<MetaWhatsAppHooks, 'onFlowRunnerError'>;
2300
+ };
2301
+ type RequestFlowHandoffParams = {
2302
+ readonly companyId: string;
2303
+ readonly whatsappNumber: string;
2304
+ readonly variables: Readonly<Record<string, unknown>>;
2305
+ readonly node?: FlowNodeData;
2306
+ };
2307
+ declare class FlowHandoff {
2308
+ private readonly dependencies;
2309
+ constructor(dependencies: FlowHandoffDependencies);
2310
+ /** Devolve se caiu dentro do horário — vai para o contexto como `handoffWithinBusinessHours`. */
2311
+ request(params: RequestFlowHandoffParams): Promise<boolean>;
2312
+ /**
2313
+ * Handler do `actionKind: 'handoff'`. `actionParams.message` e `actionParams.outOfHoursMessage`
2314
+ * sobrescrevem os textos do runner para aquele nó.
2315
+ */
2316
+ createActionHandler(resolveVariables: (params: {
2317
+ session: ConversationSession;
2318
+ context: Record<string, unknown>;
2319
+ }) => Record<string, unknown>): FlowActionHandler;
2320
+ private reportFailure;
2321
+ private isWithinHours;
2322
+ private messageFor;
2323
+ }
2324
+
2325
+ /**
2326
+ * Copyright (c) 2026 Ada Technology. MIT License.
2327
+ *
2328
+ * Um turno do runner por conversa de cada vez. Duas mensagens do mesmo cliente processadas em
2329
+ * paralelo leriam a mesma posição, responderiam ao mesmo nó e a última gravação apagaria a outra.
2330
+ *
2331
+ * Porta, com implementação padrão no Postgres do próprio módulo; o host troca por outra (Redis,
2332
+ * fila particionada por conversa) quando quiser.
2333
+ */
2334
+
2335
+ type FlowTurnLockKey = {
2336
+ readonly companyId: string;
2337
+ readonly whatsappNumber: string;
2338
+ };
2339
+ interface FlowTurnLockInterface {
2340
+ withLock<TResult>(key: FlowTurnLockKey, work: () => Promise<TResult>): Promise<TResult>;
2341
+ }
2342
+ /**
2343
+ * `pg_advisory_xact_lock` numa transação que dura o turno. A transação não toca linha nenhuma —
2344
+ * só segura o lock (e uma conexão do pool) enquanto o turno roda; as escritas do turno usam a
2345
+ * conexão normal. O lock sai sozinho no fim da transação, inclusive se o processo morrer.
2346
+ *
2347
+ * Custo: uma conexão por conversa em atendimento simultâneo. Com muitas conversas ao mesmo tempo,
2348
+ * dimensione o pool ou injete outra implementação.
2349
+ */
2350
+ declare class PostgresAdvisoryFlowTurnLock implements FlowTurnLockInterface {
2351
+ private readonly db;
2352
+ constructor(db: MetaWhatsAppDatabase);
2353
+ withLock<TResult>(key: FlowTurnLockKey, work: () => Promise<TResult>): Promise<TResult>;
2354
+ }
2355
+ /** Lock dentro do processo: serve para uma instância só e para testes. Não protege entre réplicas. */
2356
+ declare class InProcessFlowTurnLock implements FlowTurnLockInterface {
2357
+ private readonly tails;
2358
+ withLock<TResult>(key: FlowTurnLockKey, work: () => Promise<TResult>): Promise<TResult>;
2359
+ }
2360
+
2361
+ /**
2362
+ * Copyright (c) 2026 Ada Technology. MIT License.
2363
+ *
2364
+ * Runner de fluxo: o que faltava entre o `FlowInterpreter` (máquina de estados pura) e o cliente.
2365
+ * Carrega o grafo publicado, entende a resposta, avança o interpretador, grava posição e contexto e
2366
+ * fala com o cliente — pergunta, botões/lista, `directMessage`, nova tentativa e encaminhamento.
2367
+ *
2368
+ * Antes dele, cada host escrevia o próprio driver (centenas de linhas) e o motor de fluxo do pacote
2369
+ * não fazia nada sozinho depois do `onMessageReceived`.
2370
+ */
2371
+
2372
+ type FlowRunnerDependencies = {
2373
+ readonly interpreter: FlowInterpreter;
2374
+ readonly flowGraphRepository: Pick<FlowGraphRepository, 'get'>;
2375
+ readonly sessionRepository: SessionRepository;
2376
+ readonly sendMessage: SendMessageUseCase;
2377
+ readonly channel: ChannelAdapterInterface;
2378
+ readonly handoff: FlowHandoff;
2379
+ readonly lock: FlowTurnLockInterface;
2380
+ readonly startState: SessionState;
2381
+ readonly config: FlowRunnerConfig;
2382
+ readonly hooks?: Pick<MetaWhatsAppHooks, 'onFlowRunnerError'>;
2383
+ };
2384
+ type HandleFlowMessageParams = {
2385
+ readonly companyId: string;
2386
+ readonly message: WhatsAppMessage;
2387
+ readonly profileName?: string;
2388
+ };
2389
+ type StartFlowParams = {
2390
+ readonly companyId: string;
2391
+ readonly whatsappNumber: string;
2392
+ /** Ausente, o fluxo de partida. */
2393
+ readonly flowKey?: string;
2394
+ readonly profileName?: string;
2395
+ };
2396
+ /** Fuso do runner: o configurado, ou o do horário de atendimento fixo. Sem nenhum, falha no boot. */
2397
+ declare function resolveFlowTimeZone(config: FlowRunnerConfig): string;
2398
+ declare class FlowRunner {
2399
+ private readonly dependencies;
2400
+ private readonly renderer;
2401
+ private readonly timeZone;
2402
+ private readonly turnVariables;
2403
+ constructor(dependencies: FlowRunnerDependencies);
2404
+ registerDynamicChoiceProvider(key: string, provider: DynamicChoiceProvider): void;
2405
+ /**
2406
+ * Variáveis para `{{chave}}`. As do host (`resolveVariables`, `contactName`, `contactFirstName`)
2407
+ * vencem as respostas do cliente: um `contextKey` chamado `contactName` não pode trocar o nome que
2408
+ * o sistema conhece pelo que o cliente digitou.
2409
+ */
2410
+ variablesFor(params: {
2411
+ session: ConversationSession;
2412
+ context: Record<string, unknown>;
2413
+ }): Record<string, unknown>;
2414
+ /** Atende uma mensagem. Um turno por conversa de cada vez (`lock`); reentrega da mesma mensagem é ignorada. */
2415
+ handle(params: HandleFlowMessageParams): Promise<FlowRunnerOutcome>;
2416
+ /** Abre um fluxo para a conversa sem esperar mensagem — ex.: ao devolver a conversa ao bot. */
2417
+ start(params: StartFlowParams): Promise<FlowRunnerOutcome>;
2418
+ private handleLocked;
2419
+ private route;
2420
+ private guard;
2421
+ /** Primeira escrita do turno: grava o id da mensagem antes de qualquer efeito externo. */
2422
+ private claim;
2423
+ private openTurn;
2424
+ private startFlowKey;
2425
+ private clock;
2426
+ private loadGraph;
2427
+ private globalKeywordTarget;
2428
+ private keywordJumpAtStart;
2429
+ /**
2430
+ * Palavra global vale mesmo com a conversa aguardando atendimento. Reiniciar NÃO tira o pedido da
2431
+ * fila (`humanRequestedAt` continua): a equipe ainda responde, e o cliente pode usar o bot enquanto
2432
+ * espera; quando o fluxo terminar, o runner volta ao silêncio.
2433
+ */
2434
+ private applyGlobalTarget;
2435
+ private answerNode;
2436
+ private followsDefaultWhenUnmatched;
2437
+ private handleInvalid;
2438
+ private fallbackText;
2439
+ private handOff;
2440
+ private jumpTo;
2441
+ private runFrom;
2442
+ /** Grava a posição no nó e pergunta. Para `dynamic_choice`, busca a página antes de gravar. */
2443
+ private awaitAnswer;
2444
+ private say;
2445
+ private send;
2446
+ private save;
2447
+ private reportMissingFlow;
2448
+ /**
2449
+ * Nunca relança: só é chamado depois de o turno ter sido gravado, e relançar faria a fila repetir
2450
+ * uma mensagem já marcada como tratada. Sem gancho, o erro é descartado (a conversa fica no último
2451
+ * ponto gravado e a próxima mensagem do cliente segue dali); gancho que falha também não derruba.
2452
+ */
2453
+ private report;
2186
2454
  }
2187
2455
 
2188
2456
  type FlowMediaLocation = {
@@ -2356,6 +2624,8 @@ declare class InboundEffectsDispatcher {
2356
2624
  sessionRepository: SessionRepository;
2357
2625
  hooks?: MetaWhatsAppHooks;
2358
2626
  realtime?: RealtimeNotifierInterface;
2627
+ /** Presente quando `features.flowRunner` está ligado: o módulo dirige o fluxo depois do hook. */
2628
+ flowRunner?: Pick<FlowRunner, 'handle'>;
2359
2629
  });
2360
2630
  run(job: InboundDispatchJob): Promise<void>;
2361
2631
  runMessageEffects(job: InboundMessageEffectsJob): Promise<void>;
@@ -2406,6 +2676,8 @@ declare class ReceiveWebhookUseCase {
2406
2676
  inboundQueue?: InboundDispatchQueueInterface;
2407
2677
  /** Não grava `location` no transcript; ver `MetaWhatsAppModuleFeatures.redactInboundLocation`. */
2408
2678
  redactInboundLocation?: boolean;
2679
+ /** Runner de fluxo (`features.flowRunner`); ausente, o host dirige a conversa. */
2680
+ flowRunner?: Pick<FlowRunner, 'handle'>;
2409
2681
  });
2410
2682
  private readonly dispatcher;
2411
2683
  execute(input: ReceiveWebhookParams): Promise<ReceiveWebhookResult>;
@@ -2662,6 +2934,24 @@ interface MetaWhatsAppModuleFeatures {
2662
2934
  * fila do host. Linhas já gravadas se redigem com `conversations.redactInboundLocations`.
2663
2935
  */
2664
2936
  redactInboundLocation?: boolean;
2937
+ /**
2938
+ * O módulo dirige a conversa pelo grafo publicado depois do `onMessageReceived` devolver
2939
+ * `'continue'`: pergunta, valida, avança, grava e encaminha. `true` usa os padrões; o objeto
2940
+ * configura (fluxo de partida, palavras globais, horário de atendimento, textos — ver
2941
+ * `FlowRunnerConfig`).
2942
+ *
2943
+ * **Desligado por omissão**: host que já dirige o próprio fluxo depois do `'continue'` passaria a
2944
+ * receber duas respostas. Exige `flowEngine` (padrão ligado).
2945
+ */
2946
+ flowRunner?: boolean | FlowRunnerConfig;
2947
+ /**
2948
+ * Respostas a contatos do simulador (número começando com `0`, ver `isPreviewContact`) não chamam
2949
+ * a Meta: o canal devolve `preview.<uuid>` e o resto (janela, transcript, SSE) segue igual.
2950
+ *
2951
+ * **Desligado por omissão.** Nenhum número real começa com `0`, mas ligar é declarar que este
2952
+ * ambiente atende simulador — decisão visível onde o módulo é montado, como `previewMedia`.
2953
+ */
2954
+ previewContacts?: boolean;
2665
2955
  }
2666
2956
  /**
2667
2957
  * Transcrição de áudio. Ausente = desligada, e as colunas ficam nulas ("não avaliado").
@@ -2706,6 +2996,11 @@ interface MetaWhatsAppModuleProviders {
2706
2996
  * transcrever um áudio já salvo significa ler os bytes de volta.
2707
2997
  */
2708
2998
  transcription?: MetaWhatsAppTranscriptionConfig;
2999
+ /**
3000
+ * Um turno do runner por conversa. Padrão: `pg_advisory_xact_lock` no `db` do módulo (uma conexão
3001
+ * do pool por conversa em atendimento simultâneo). Troque por um lock distribuído próprio se preferir.
3002
+ */
3003
+ flowTurnLock?: FlowTurnLockInterface;
2709
3004
  }
2710
3005
  interface CreateMetaWhatsAppModuleParams {
2711
3006
  db: MetaWhatsAppDatabase;
@@ -2756,6 +3051,140 @@ declare function createMetaWhatsAppModule(params: CreateMetaWhatsAppModuleParams
2756
3051
  previewMedia: StorePreviewMediaUseCase | undefined;
2757
3052
  webhook: {
2758
3053
  receive: ReceiveWebhookUseCase;
3054
+ /**
3055
+ * Comando do simulador (ponte do `conversations-ui`) → payload da Meta com o `phone_number_id`
3056
+ * DESTE módulo. Montar com o padrão do builder fazia o filtro de número descartar a entrega.
3057
+ * Quem assina e entrega em `receive` é a rota do host.
3058
+ */
3059
+ buildPreviewPayload: (command: PreviewInboundCommand, envelope?: Omit<PreviewPayloadEnvelope, "phoneNumberId">) => {
3060
+ object: string;
3061
+ entry: {
3062
+ id: string;
3063
+ changes: {
3064
+ value: {
3065
+ messages?: {
3066
+ id: string;
3067
+ type: string;
3068
+ from: string;
3069
+ timestamp: string;
3070
+ text?: {
3071
+ body: string;
3072
+ } | undefined;
3073
+ image?: {
3074
+ id: string;
3075
+ mime_type: string;
3076
+ sha256?: string | undefined;
3077
+ caption?: string | undefined;
3078
+ filename?: string | undefined;
3079
+ } | undefined;
3080
+ audio?: {
3081
+ id: string;
3082
+ mime_type: string;
3083
+ sha256?: string | undefined;
3084
+ caption?: string | undefined;
3085
+ filename?: string | undefined;
3086
+ } | undefined;
3087
+ video?: {
3088
+ id: string;
3089
+ mime_type: string;
3090
+ sha256?: string | undefined;
3091
+ caption?: string | undefined;
3092
+ filename?: string | undefined;
3093
+ } | undefined;
3094
+ document?: {
3095
+ id: string;
3096
+ mime_type: string;
3097
+ sha256?: string | undefined;
3098
+ caption?: string | undefined;
3099
+ filename?: string | undefined;
3100
+ } | undefined;
3101
+ sticker?: {
3102
+ id: string;
3103
+ mime_type: string;
3104
+ sha256?: string | undefined;
3105
+ caption?: string | undefined;
3106
+ filename?: string | undefined;
3107
+ } | undefined;
3108
+ interactive?: {
3109
+ type: string;
3110
+ button_reply?: {
3111
+ id: string;
3112
+ title: string;
3113
+ } | undefined;
3114
+ list_reply?: {
3115
+ id: string;
3116
+ title: string;
3117
+ } | undefined;
3118
+ } | undefined;
3119
+ button?: {
3120
+ text: string;
3121
+ payload?: string | undefined;
3122
+ } | undefined;
3123
+ order?: {
3124
+ catalog_id: string;
3125
+ product_items: {
3126
+ product_retailer_id: string;
3127
+ quantity: number;
3128
+ item_price: number;
3129
+ currency: string;
3130
+ }[];
3131
+ text?: string | undefined;
3132
+ } | undefined;
3133
+ location?: {
3134
+ latitude: number;
3135
+ longitude: number;
3136
+ name?: string | undefined;
3137
+ address?: string | undefined;
3138
+ url?: string | undefined;
3139
+ } | undefined;
3140
+ context?: {
3141
+ id?: string | undefined;
3142
+ from?: string | undefined;
3143
+ referred_product?: {
3144
+ catalog_id: string;
3145
+ product_retailer_id: string;
3146
+ } | undefined;
3147
+ } | undefined;
3148
+ }[] | undefined;
3149
+ message_echoes?: {
3150
+ id: string;
3151
+ type: string;
3152
+ from: string;
3153
+ timestamp: string;
3154
+ }[] | undefined;
3155
+ messaging_product?: string | undefined;
3156
+ contacts?: {
3157
+ wa_id: string;
3158
+ profile?: {
3159
+ name: string;
3160
+ } | undefined;
3161
+ }[] | undefined;
3162
+ statuses?: {
3163
+ id: string;
3164
+ status: "sent" | "delivered" | "read" | "failed";
3165
+ timestamp: string;
3166
+ recipient_id?: string | undefined;
3167
+ errors?: {
3168
+ code?: number | undefined;
3169
+ message?: string | undefined;
3170
+ title?: string | undefined;
3171
+ href?: string | undefined;
3172
+ error_data?: {
3173
+ details?: string | undefined;
3174
+ } | undefined;
3175
+ }[] | undefined;
3176
+ }[] | undefined;
3177
+ metadata?: {
3178
+ display_phone_number: string;
3179
+ phone_number_id: string;
3180
+ } | undefined;
3181
+ } & {
3182
+ [k: string]: unknown;
3183
+ };
3184
+ field?: string | undefined;
3185
+ }[];
3186
+ }[];
3187
+ };
2759
3188
  verifyChallenge: (query: {
2760
3189
  mode: string | null;
2761
3190
  token: string | null;
@@ -2766,6 +3195,8 @@ declare function createMetaWhatsAppModule(params: CreateMetaWhatsAppModuleParams
2766
3195
  flows: {
2767
3196
  interpreter: FlowInterpreter;
2768
3197
  registerFlowAction: (kind: FlowActionKind, handler: FlowActionHandler) => void;
3198
+ runner: FlowRunner | undefined;
3199
+ registerDynamicChoiceProvider: (key: string, provider: DynamicChoiceProvider) => void;
2769
3200
  get: GetFlowGraphUseCase;
2770
3201
  list: ListFlowGraphsUseCase;
2771
3202
  create: CreateFlowGraphUseCase;
@@ -2796,6 +3227,15 @@ type PreviewMediaSupport = {
2796
3227
  /** Mime a devolver, já que o storage guarda bytes e não o tipo. Padrão `audio/ogg`. */
2797
3228
  readonly defaultMimeType?: string;
2798
3229
  };
3230
+ /**
3231
+ * Respostas a contatos do simulador (`isPreviewContact`). Ligado, todo envio para um número que
3232
+ * começa com `0` volta `preview.<uuid>` sem chamar a Meta — janela, transcript, SSE e status seguem
3233
+ * iguais, então o simulador vê exatamente o que o cliente veria. Nenhum `wa_id` real começa com `0`.
3234
+ */
3235
+ type PreviewContactsSupport = {
3236
+ readonly isEnabled: boolean;
3237
+ readonly generateId?: () => string;
3238
+ };
2799
3239
  declare class WhatsAppChannelAdapter implements ChannelAdapterInterface {
2800
3240
  private readonly messages;
2801
3241
  /**
@@ -2803,12 +3243,15 @@ declare class WhatsAppChannelAdapter implements ChannelAdapterInterface {
2803
3243
  * que atualizar o pacote não abre nada em quem não pediu.
2804
3244
  */
2805
3245
  private readonly previewMedia?;
3246
+ private readonly previewContacts?;
2806
3247
  constructor(messages: WhatsAppMessageProvider,
2807
3248
  /**
2808
3249
  * Ausente, o adaptador se comporta como sempre: todo id vai para a Graph API. É o que garante
2809
3250
  * que atualizar o pacote não abre nada em quem não pediu.
2810
3251
  */
2811
- previewMedia?: PreviewMediaSupport | undefined);
3252
+ previewMedia?: PreviewMediaSupport | undefined, previewContacts?: PreviewContactsSupport | undefined);
3253
+ /** `preview.<uuid>` quando o destino é contato do simulador e o recurso está ligado. */
3254
+ private previewMessageId;
2812
3255
  private translateErrors;
2813
3256
  sendText(to: string, body: string): Promise<{
2814
3257
  externalMessageId: string | null;
@@ -2903,6 +3346,115 @@ declare function redeemSseTicket(store: TicketStoreInterface, ticket: string): P
2903
3346
  whatsappNumber: string;
2904
3347
  } | null>;
2905
3348
 
3349
+ /**
3350
+ * Copyright (c) 2026 Ada Technology. MIT License.
3351
+ *
3352
+ * O que a mensagem do cliente oferece como resposta. Toque em botão/lista é `reply` (o id é
3353
+ * confiável); texto e botão de template são `text` (passam por casamento de rótulo); áudio, imagem,
3354
+ * localização e afins são `unsupported` — o runner avisa e repergunta sem contar tentativa.
3355
+ */
3356
+
3357
+ type FlowInbound = {
3358
+ readonly kind: 'reply';
3359
+ readonly answer: string;
3360
+ } | {
3361
+ readonly kind: 'text';
3362
+ readonly answer: string;
3363
+ } | {
3364
+ readonly kind: 'unsupported';
3365
+ };
3366
+ declare function readFlowInbound(message: WhatsAppMessage): FlowInbound;
3367
+
3368
+ /**
3369
+ * Copyright (c) 2026 Ada Technology. MIT License.
3370
+ *
3371
+ * Textos padrão do runner (pt-BR). Todos substituíveis por `FlowRunnerConfig` ou pelo próprio nó.
3372
+ */
3373
+ declare const DEFAULT_START_FLOW_KEY = "main";
3374
+ declare const DEFAULT_MAX_INVALID_ANSWERS = 2;
3375
+ declare const DEFAULT_FLOW_TEXT: {
3376
+ readonly FALLBACK: "Não entendi. Pode responder de novo?";
3377
+ readonly CHOICE_PROMPT: "Escolha uma opção:";
3378
+ readonly LIST_BUTTON_LABEL: "Ver opções";
3379
+ readonly SEE_MORE: "Ver mais";
3380
+ readonly NON_TEXT_ANSWER: "Por aqui eu entendo só texto. Pode escrever a resposta?";
3381
+ readonly MORE_OPTIONS_TRUNCATED: "…";
3382
+ readonly HANDOFF: "Vou chamar uma pessoa da equipe para continuar por aqui.";
3383
+ readonly HANDOFF_OUT_OF_HOURS: "Nossa equipe está fora do horário agora. Sua mensagem ficou registrada e respondemos assim que voltarmos.";
3384
+ };
3385
+ /** Id da linha "ver mais" de um `dynamic_choice`. Começa com `__` para não colidir com id do host. */
3386
+ declare const DYNAMIC_CHOICE_MORE_ID = "__more__";
3387
+ /**
3388
+ * Chave reservada do contexto com o estado do runner (tentativas inválidas, página do
3389
+ * `dynamic_choice`). Fica no contexto porque é estado da conversa e precisa sobreviver entre
3390
+ * mensagens; o prefixo `__` a separa das respostas do cliente.
3391
+ */
3392
+ declare const FLOW_RUNTIME_CONTEXT_KEY = "__flow";
3393
+
3394
+ /**
3395
+ * Copyright (c) 2026 Ada Technology. MIT License.
3396
+ *
3397
+ * Escolha → mensagem do canal. Botão com até 3 opções simples, lista com descrição/seção ou com 4+,
3398
+ * e texto numerado quando nem a lista cabe nos tetos da Meta.
3399
+ *
3400
+ * O texto numerado é a rede de segurança: passar de um teto faz a Graph API recusar a mensagem
3401
+ * inteira e o cliente ver silêncio. Numerado, ele ainda responde "2" e o runner entende.
3402
+ */
3403
+
3404
+ type FlowChoiceOption = {
3405
+ readonly id: string;
3406
+ readonly title: string;
3407
+ readonly description?: string;
3408
+ readonly section?: string;
3409
+ };
3410
+ type FlowOutboundMessage = {
3411
+ readonly kind: 'text';
3412
+ readonly body: string;
3413
+ } | {
3414
+ readonly kind: 'interactive';
3415
+ readonly interactive: InteractiveMessage;
3416
+ };
3417
+ type BuildFlowChoiceMessageParams = {
3418
+ readonly body: string;
3419
+ readonly options: readonly FlowChoiceOption[];
3420
+ readonly listButtonLabel: string;
3421
+ };
3422
+ declare function buildFlowChoiceMessage(params: BuildFlowChoiceMessageParams): FlowOutboundMessage;
3423
+
3424
+ /**
3425
+ * Copyright (c) 2026 Ada Technology. MIT License.
3426
+ *
3427
+ * O que a mensagem do cliente significa para o nó em que a conversa parou. Pura: o runner decide o
3428
+ * que fazer com a decisão (avançar, saltar, pedir de novo).
3429
+ */
3430
+
3431
+ type FlowAnswerDecision = {
3432
+ readonly kind: 'answer';
3433
+ readonly userAnswer: string;
3434
+ readonly value?: unknown;
3435
+ } | {
3436
+ readonly kind: 'jump';
3437
+ readonly target: string;
3438
+ } | {
3439
+ readonly kind: 'see-more';
3440
+ } | {
3441
+ readonly kind: 'invalid';
3442
+ readonly rejection?: FlowAnswerRejection;
3443
+ };
3444
+ type ResolveFlowAnswerParams = {
3445
+ readonly node: FlowNodeData;
3446
+ /** Texto, ou o id de botão/linha. `undefined` para mídia, localização e afins. */
3447
+ readonly answer: string | undefined;
3448
+ /** Veio de toque em botão/lista — o id é confiável e não passa por casamento de texto. */
3449
+ readonly isInteractiveReply: boolean;
3450
+ readonly context: Readonly<Record<string, unknown>>;
3451
+ readonly clock: FlowClock;
3452
+ /** Opções exibidas na última página de um `dynamic_choice` (id, título), incluindo "ver mais". */
3453
+ readonly dynamicOptions?: readonly (readonly [string, string])[];
3454
+ };
3455
+ declare function isChoiceNode(node: FlowNodeData): boolean;
3456
+ declare function resolveFlowAnswer(params: ResolveFlowAnswerParams): FlowAnswerDecision;
3457
+
2906
3458
  /**
2907
3459
  * Porta de escrita no transcript, e não a classe `LogMessageUseCase`.
2908
3460
  *
@@ -3031,4 +3583,4 @@ declare class FlowMediaIdRepository implements FlowMediaIdStore {
3031
3583
  }): Promise<void>;
3032
3584
  }
3033
3585
 
3034
- export { type AttachFlowMediaParams, type AudioTranscriber, type CompanyDocumentView, type CompanyDocumentsPage, type ConversationDocumentView, type ConversationDocumentsPage, type CountInboundLocationsParams, type CountInboundLocationsResult, CountInboundLocationsUseCase, type CreateFlowGraphParams, CreateFlowGraphUseCase, type CreateMetaWhatsAppModuleParams, type CreateSendMediaActionParams, type CreateSendProductListActionParams, DEFAULT_FALLBACK_LIST_LABEL, DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS, type DeleteConversationParams, type DeleteConversationResult, DeleteConversationUseCase, DeleteFlowGraphUseCase, DocumentRepository, type DocumentRow, type DrizzleMigrateFunction, type ExportConversationParams, type ExportConversationResult, ExportConversationUseCase, FlowGraphCache, FlowGraphRepository, type FlowGraphRow, FlowInterpreter, type FlowMediaIdCache, FlowMediaIdRepository, type FlowMediaIdStore, type FlowMediaLocation, FlowMediaRepository, type FlowMediaRow, type FlowMediaTranscriptLogger, type FlowRunResult, type FlowStepInput, type FlowStepResult, GetFlowGraphUseCase, GetLiveFlowPositionsUseCase, INBOUND_LOCATION_CONTENT, type InboundDispatchJob, type InboundDispatchQueueInterface, InboundEffectsDispatcher, type InboundMediaDescriptor, type InboundMessageEffectsJob, type InboundStatusEffectsJob, type IngestInboundMediaParams, type IngestInboundMediaResult, IngestInboundMediaUseCase, type IngestTranscriptionOptions, type InsertMessageParams, InvalidFlowGraphError, type LinkDocumentParams, type ListCompanyDocumentsParams, ListCompanyDocumentsUseCase, type ListConversationDocumentsParams, ListConversationDocumentsUseCase, type ListConversationsFilters, type ListConversationsParams, ListConversationsUseCase, type ListDocumentsParams, type ListDocumentsResult, ListFlowGraphsUseCase, type ListMessagesParams, ListMessagesUseCase, type LogMessageParams, LogMessageUseCase, META_WHATSAPP_MIGRATIONS_TABLE, type MessageModerator, MessageRepository, type MessageRow, type MetaWhatsAppDatabase, type MetaWhatsAppMigrationsFolderParams, type MetaWhatsAppMigrationsLayout, type MetaWhatsAppModule, type MetaWhatsAppModuleConfig, type MetaWhatsAppModuleFeatures, type MetaWhatsAppModuleProviders, type MetaWhatsAppTranscriptionConfig, type NewDocumentRow, type NewFlowGraphRow, type NewFlowMediaRow, type NewMessageRow, type NewSessionRow, type NewSettingsRow, type NonceStoreInterface, OptimisticLockError, PRODUCT_LIST_LIMIT, type PreviewMediaSupport, ProcessInboundDispatchUseCase, type PurgeExpiredDocumentsParams, type PurgeExpiredDocumentsResult, PurgeExpiredDocumentsUseCase, type RealtimeRelay, type ReceiveWebhookParams, type ReceiveWebhookResult, ReceiveWebhookUseCase, type RedactInboundLocationsParams, type RedactInboundLocationsResult, RedactInboundLocationsUseCase, type ReleaseConversationParams, ReleaseConversationUseCase, type ListMessagesParams$1 as RepositoryListMessagesParams, type RequestHumanConversationParams, RequestHumanConversationUseCase, type ResolveTranscriptionPolicyDependencies, type RunMetaWhatsAppMigrationsParams, type SaveFlowGraphParams, SaveFlowGraphUseCase, type SaveTranscriptionByWaMessageIdParams, type SaveTranscriptionParams, type SendInteractiveParams, type SendMediaParams, SendMessageUseCase, type SendTemplateParams, type SendTextParams, SessionRepository, type SessionRow, SettingsRepository, type SettingsRow, SseHub, type SseListener, type StorePreviewMediaParams, type StorePreviewMediaResult, StorePreviewMediaUseCase, TRANSCRIPTION_MODE, TRANSCRIPTION_STATUS, type TakeoverConversationParams, TakeoverConversationUseCase, type TicketStoreInterface, type TranscribeAudioDependencies, type TranscribeAudioParams, type TranscribeAudioResult, TranscribeAudioUseCase, type TranscriptionPolicy, type TranscriptionPolicyDefaults, type TranscriptionPolicyResolver, type TranscriptionStatus, type UpdateFlowMediaParams, WhatsAppChannelAdapter, buildInboundJobId, claimWebhookDelivery, confirmWebhookDelivery, createMetaWhatsAppModule, createSendMediaAction, createSendProductListAction, createTranscriptionPolicyResolver, documents, extractMediaDescriptor, flowGraphs, flowMedia, isAudioMimeType, isRetriableTranscriptionError, isUnsupportedTranscriptionError, issueSseTicket, messages, metaWhatsAppMigrationsFolder, metaWhatsAppSchema, redeemSseTicket, resolveFailureStatus, runMetaWhatsAppMigrations, sessions, settings, toSessionContract, transcriptionRetryAfterSeconds, verifyWebhookChallenge, verifyWebhookSignature };
3586
+ export { type AttachFlowMediaParams, type AudioTranscriber, type BuildFlowChoiceMessageParams, type CompanyDocumentView, type CompanyDocumentsPage, type ConversationDocumentView, type ConversationDocumentsPage, type CountInboundLocationsParams, type CountInboundLocationsResult, CountInboundLocationsUseCase, type CreateFlowGraphParams, CreateFlowGraphUseCase, type CreateMetaWhatsAppModuleParams, type CreateSendMediaActionParams, type CreateSendProductListActionParams, DEFAULT_FALLBACK_LIST_LABEL, DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS, DEFAULT_FLOW_TEXT, DEFAULT_MAX_INVALID_ANSWERS, DEFAULT_START_FLOW_KEY, DYNAMIC_CHOICE_MORE_ID, type DeleteConversationParams, type DeleteConversationResult, DeleteConversationUseCase, DeleteFlowGraphUseCase, DocumentRepository, type DocumentRow, type DrizzleMigrateFunction, type ExportConversationParams, type ExportConversationResult, ExportConversationUseCase, FLOW_RUNTIME_CONTEXT_KEY, type FlowAnswerDecision, type FlowChoiceOption, type FlowGlobalKeyword, type FlowGlobalKeywordTarget, FlowGraphCache, FlowGraphRepository, type FlowGraphRow, FlowHandoff, type FlowHandoffConfig, type FlowHandoffDependencies, type FlowInbound, FlowInterpreter, type FlowMediaIdCache, FlowMediaIdRepository, type FlowMediaIdStore, type FlowMediaLocation, FlowMediaRepository, type FlowMediaRow, type FlowMediaTranscriptLogger, type FlowOutboundMessage, type FlowRunOptions, type FlowRunResult, FlowRunner, type FlowRunnerConfig, type FlowRunnerDependencies, type FlowRunnerOutcome, type FlowStepInput, type FlowStepResult, type FlowTurnLockInterface, type FlowTurnLockKey, type FlowVariablesResolver, GetFlowGraphUseCase, GetLiveFlowPositionsUseCase, type HandleFlowMessageParams, INBOUND_LOCATION_CONTENT, InProcessFlowTurnLock, type InboundDispatchJob, type InboundDispatchQueueInterface, InboundEffectsDispatcher, type InboundMediaDescriptor, type InboundMessageEffectsJob, type InboundStatusEffectsJob, type IngestInboundMediaParams, type IngestInboundMediaResult, IngestInboundMediaUseCase, type IngestTranscriptionOptions, type InsertMessageParams, InvalidFlowGraphError, type LinkDocumentParams, type ListCompanyDocumentsParams, ListCompanyDocumentsUseCase, type ListConversationDocumentsParams, ListConversationDocumentsUseCase, type ListConversationsFilters, type ListConversationsParams, ListConversationsUseCase, type ListDocumentsParams, type ListDocumentsResult, ListFlowGraphsUseCase, type ListMessagesParams, ListMessagesUseCase, type LogMessageParams, LogMessageUseCase, META_WHATSAPP_MIGRATIONS_TABLE, type MessageModerator, MessageRepository, type MessageRow, type MetaWhatsAppDatabase, type MetaWhatsAppMigrationsFolderParams, type MetaWhatsAppMigrationsLayout, type MetaWhatsAppModule, type MetaWhatsAppModuleConfig, type MetaWhatsAppModuleFeatures, type MetaWhatsAppModuleProviders, type MetaWhatsAppTranscriptionConfig, type NewDocumentRow, type NewFlowGraphRow, type NewFlowMediaRow, type NewMessageRow, type NewSessionRow, type NewSettingsRow, type NonceStoreInterface, OptimisticLockError, PRODUCT_LIST_LIMIT, PostgresAdvisoryFlowTurnLock, type PreviewContactsSupport, type PreviewMediaSupport, ProcessInboundDispatchUseCase, type PurgeExpiredDocumentsParams, type PurgeExpiredDocumentsResult, PurgeExpiredDocumentsUseCase, type RealtimeRelay, type ReceiveWebhookParams, type ReceiveWebhookResult, ReceiveWebhookUseCase, type RedactInboundLocationsParams, type RedactInboundLocationsResult, RedactInboundLocationsUseCase, type ReleaseConversationParams, ReleaseConversationUseCase, type ListMessagesParams$1 as RepositoryListMessagesParams, type RequestFlowHandoffParams, type RequestHumanConversationParams, RequestHumanConversationUseCase, type ResolveFlowAnswerParams, type ResolveTranscriptionPolicyDependencies, type RunMetaWhatsAppMigrationsParams, type SaveFlowGraphParams, SaveFlowGraphUseCase, type SaveTranscriptionByWaMessageIdParams, type SaveTranscriptionParams, type SendInteractiveParams, type SendMediaParams, SendMessageUseCase, type SendTemplateParams, type SendTextParams, SessionRepository, type SessionRow, SettingsRepository, type SettingsRow, SseHub, type SseListener, type StartFlowParams, type StorePreviewMediaParams, type StorePreviewMediaResult, StorePreviewMediaUseCase, TRANSCRIPTION_MODE, TRANSCRIPTION_STATUS, type TakeoverConversationParams, TakeoverConversationUseCase, type TicketStoreInterface, type TranscribeAudioDependencies, type TranscribeAudioParams, type TranscribeAudioResult, TranscribeAudioUseCase, type TranscriptionPolicy, type TranscriptionPolicyDefaults, type TranscriptionPolicyResolver, type TranscriptionStatus, type UpdateFlowMediaParams, WhatsAppChannelAdapter, buildFlowChoiceMessage, buildInboundJobId, claimWebhookDelivery, confirmWebhookDelivery, createMetaWhatsAppModule, createSendMediaAction, createSendProductListAction, createTranscriptionPolicyResolver, documents, extractMediaDescriptor, flowGraphs, flowMedia, isAudioMimeType, isChoiceNode, isRetriableTranscriptionError, isUnsupportedTranscriptionError, issueSseTicket, messages, metaWhatsAppMigrationsFolder, metaWhatsAppSchema, readFlowInbound, redeemSseTicket, resolveFailureStatus, resolveFlowAnswer, resolveFlowTimeZone, runMetaWhatsAppMigrations, sessions, settings, toSessionContract, transcriptionRetryAfterSeconds, verifyWebhookChallenge, verifyWebhookSignature };