@adatechnology/meta-whatsapp-module 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +58 -4
- package/dist/index.cjs +229 -63
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +109 -7
- package/dist/index.d.ts +109 -7
- package/dist/index.js +189 -24
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/dist/index.cjs
CHANGED
|
@@ -8,11 +8,11 @@ var __export = (target, all) => {
|
|
|
8
8
|
for (var name in all)
|
|
9
9
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
10
|
};
|
|
11
|
-
var __copyProps = (to, from, except,
|
|
11
|
+
var __copyProps = (to, from, except, desc4) => {
|
|
12
12
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
13
|
for (let key of __getOwnPropNames(from))
|
|
14
14
|
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc4 = __getOwnPropDesc(from, key)) || desc4.enumerable });
|
|
16
16
|
}
|
|
17
17
|
return to;
|
|
18
18
|
};
|
|
@@ -57,7 +57,7 @@ __export(index_exports, {
|
|
|
57
57
|
META_WHATSAPP_MIGRATIONS_TABLE: () => META_WHATSAPP_MIGRATIONS_TABLE,
|
|
58
58
|
MessageRepository: () => MessageRepository,
|
|
59
59
|
OptimisticLockError: () => OptimisticLockError,
|
|
60
|
-
PREVIEW_MEDIA_ID_PREFIX: () =>
|
|
60
|
+
PREVIEW_MEDIA_ID_PREFIX: () => import_meta_whatsapp_contracts15.PREVIEW_MEDIA_ID_PREFIX,
|
|
61
61
|
PRODUCT_LIST_LIMIT: () => PRODUCT_LIST_LIMIT,
|
|
62
62
|
PostgresAdvisoryFlowTurnLock: () => PostgresAdvisoryFlowTurnLock,
|
|
63
63
|
ProcessInboundDispatchUseCase: () => ProcessInboundDispatchUseCase,
|
|
@@ -103,12 +103,13 @@ __export(index_exports, {
|
|
|
103
103
|
redeemSseTicket: () => redeemSseTicket,
|
|
104
104
|
resolveFailureStatus: () => resolveFailureStatus,
|
|
105
105
|
resolveFlowAnswer: () => resolveFlowAnswer,
|
|
106
|
+
resolveFlowConfigText: () => resolveFlowConfigText,
|
|
106
107
|
resolveFlowTimeZone: () => resolveFlowTimeZone,
|
|
107
|
-
resolvePreviewUploadId: () =>
|
|
108
|
+
resolvePreviewUploadId: () => import_meta_whatsapp_contracts15.resolvePreviewUploadId,
|
|
108
109
|
runMetaWhatsAppMigrations: () => runMetaWhatsAppMigrations,
|
|
109
110
|
sessions: () => sessions,
|
|
110
111
|
settings: () => settings,
|
|
111
|
-
toPreviewMediaId: () =>
|
|
112
|
+
toPreviewMediaId: () => import_meta_whatsapp_contracts15.toPreviewMediaId,
|
|
112
113
|
toSessionContract: () => toSessionContract,
|
|
113
114
|
transcriptionRetryAfterSeconds: () => transcriptionRetryAfterSeconds,
|
|
114
115
|
verifyWebhookChallenge: () => verifyWebhookChallenge,
|
|
@@ -119,7 +120,7 @@ module.exports = __toCommonJS(index_exports);
|
|
|
119
120
|
// src/createMetaWhatsAppModule.ts
|
|
120
121
|
var import_meta_whatsapp_provider = require("@adatechnology/meta-whatsapp-provider");
|
|
121
122
|
var import_testing = require("@adatechnology/meta-whatsapp-contracts/testing");
|
|
122
|
-
var
|
|
123
|
+
var import_meta_whatsapp_contracts20 = require("@adatechnology/meta-whatsapp-contracts");
|
|
123
124
|
|
|
124
125
|
// src/repositories/SessionRepository.ts
|
|
125
126
|
var import_drizzle_orm2 = require("drizzle-orm");
|
|
@@ -828,7 +829,8 @@ var MessageRepository = class {
|
|
|
828
829
|
(0, import_drizzle_orm3.eq)(messages.sessionId, params.sessionId)
|
|
829
830
|
];
|
|
830
831
|
if (params.before) conditions.push((0, import_drizzle_orm3.lt)(messages.createdAt, new Date(params.before)));
|
|
831
|
-
|
|
832
|
+
const newestFirst = await this.db.select().from(messages).where((0, import_drizzle_orm3.and)(...conditions)).orderBy((0, import_drizzle_orm3.desc)(messages.createdAt), (0, import_drizzle_orm3.desc)(messages.id)).limit(params.limit ?? DEFAULT_LIMIT2);
|
|
833
|
+
return newestFirst.reverse();
|
|
832
834
|
}
|
|
833
835
|
};
|
|
834
836
|
|
|
@@ -1111,6 +1113,7 @@ var LogMessageUseCase = class {
|
|
|
1111
1113
|
await this.sessionRepository.touchInbound(params.companyId, params.whatsappNumber);
|
|
1112
1114
|
}
|
|
1113
1115
|
this.realtime?.emit(`conv:${params.whatsappNumber}`, "message", {
|
|
1116
|
+
companyId: params.companyId,
|
|
1114
1117
|
direction: params.direction,
|
|
1115
1118
|
sender: params.sender
|
|
1116
1119
|
});
|
|
@@ -1329,6 +1332,7 @@ var TakeoverConversationUseCase = class {
|
|
|
1329
1332
|
async execute(params) {
|
|
1330
1333
|
await this.sessionRepository.takeover(params.companyId, params.whatsappNumber, params.agentUserId);
|
|
1331
1334
|
this.realtime?.emit(`conv:${params.whatsappNumber}`, "mode-changed", {
|
|
1335
|
+
companyId: params.companyId,
|
|
1332
1336
|
mode: "human",
|
|
1333
1337
|
assignedUserId: params.agentUserId
|
|
1334
1338
|
});
|
|
@@ -1361,6 +1365,7 @@ var ReleaseConversationUseCase = class {
|
|
|
1361
1365
|
async execute(params) {
|
|
1362
1366
|
await this.sessionRepository.release(params.companyId, params.whatsappNumber);
|
|
1363
1367
|
this.realtime?.emit(`conv:${params.whatsappNumber}`, "mode-changed", {
|
|
1368
|
+
companyId: params.companyId,
|
|
1364
1369
|
mode: "bot",
|
|
1365
1370
|
assignedUserId: null
|
|
1366
1371
|
});
|
|
@@ -1507,6 +1512,7 @@ var RequestHumanConversationUseCase = class {
|
|
|
1507
1512
|
const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
|
|
1508
1513
|
if (!session) throw new import_meta_whatsapp_contracts3.SessionNotFoundError(params.whatsappNumber);
|
|
1509
1514
|
this.realtime?.emit(`conv:${params.whatsappNumber}`, "human-requested", {
|
|
1515
|
+
companyId: params.companyId,
|
|
1510
1516
|
humanRequestedAt: session.humanRequestedAt?.toISOString() ?? null
|
|
1511
1517
|
});
|
|
1512
1518
|
this.realtime?.emit("global", "data-changed", {});
|
|
@@ -2175,7 +2181,7 @@ var FlowInterpreter = class {
|
|
|
2175
2181
|
};
|
|
2176
2182
|
|
|
2177
2183
|
// src/flows/FlowRunner.ts
|
|
2178
|
-
var
|
|
2184
|
+
var import_meta_whatsapp_contracts13 = require("@adatechnology/meta-whatsapp-contracts");
|
|
2179
2185
|
|
|
2180
2186
|
// src/flows/resolveFlowAnswer.ts
|
|
2181
2187
|
var import_meta_whatsapp_contracts9 = require("@adatechnology/meta-whatsapp-contracts");
|
|
@@ -2213,7 +2219,7 @@ function matchOption(answer, options, isInteractiveReply) {
|
|
|
2213
2219
|
}
|
|
2214
2220
|
__name(matchOption, "matchOption");
|
|
2215
2221
|
function resolveChoice(params, answer) {
|
|
2216
|
-
const optionId = matchOption(answer, params.node.options ?? [], params.isInteractiveReply);
|
|
2222
|
+
const optionId = matchOption(answer, params.options ?? params.node.options ?? [], params.isInteractiveReply);
|
|
2217
2223
|
if (optionId) return {
|
|
2218
2224
|
kind: "answer",
|
|
2219
2225
|
userAnswer: optionId
|
|
@@ -2519,6 +2525,51 @@ function readFlowInbound(message) {
|
|
|
2519
2525
|
}
|
|
2520
2526
|
__name(readFlowInbound, "readFlowInbound");
|
|
2521
2527
|
|
|
2528
|
+
// src/flows/matchGlobalKeyword.ts
|
|
2529
|
+
var import_meta_whatsapp_contracts12 = require("@adatechnology/meta-whatsapp-contracts");
|
|
2530
|
+
function matchGlobalKeyword(text2, entries) {
|
|
2531
|
+
const normalized = (0, import_meta_whatsapp_contracts12.normalizeFlowText)(text2);
|
|
2532
|
+
if (normalized.length === 0) return void 0;
|
|
2533
|
+
const padded = ` ${normalized} `;
|
|
2534
|
+
let best;
|
|
2535
|
+
for (const entry of entries) {
|
|
2536
|
+
const isWordMatch = entry.match === "word";
|
|
2537
|
+
for (const keyword of entry.keywords) {
|
|
2538
|
+
const normalizedKeyword = (0, import_meta_whatsapp_contracts12.normalizeFlowText)(keyword);
|
|
2539
|
+
if (normalizedKeyword.length === 0) continue;
|
|
2540
|
+
const isMatch = isWordMatch ? padded.includes(` ${normalizedKeyword} `) : normalizedKeyword === normalized;
|
|
2541
|
+
if (isMatch && (!best || normalizedKeyword.length > best.length)) {
|
|
2542
|
+
best = {
|
|
2543
|
+
length: normalizedKeyword.length,
|
|
2544
|
+
target: entry.target
|
|
2545
|
+
};
|
|
2546
|
+
}
|
|
2547
|
+
}
|
|
2548
|
+
}
|
|
2549
|
+
return best?.target;
|
|
2550
|
+
}
|
|
2551
|
+
__name(matchGlobalKeyword, "matchGlobalKeyword");
|
|
2552
|
+
|
|
2553
|
+
// src/flows/resolveFlowConfigText.ts
|
|
2554
|
+
async function resolveOne(text2, params) {
|
|
2555
|
+
if (typeof text2 !== "function") return text2;
|
|
2556
|
+
try {
|
|
2557
|
+
return await text2(params.context);
|
|
2558
|
+
} catch (error) {
|
|
2559
|
+
await params.onError?.(error);
|
|
2560
|
+
return void 0;
|
|
2561
|
+
}
|
|
2562
|
+
}
|
|
2563
|
+
__name(resolveOne, "resolveOne");
|
|
2564
|
+
async function resolveFlowConfigText(params) {
|
|
2565
|
+
for (const text2 of params.chain) {
|
|
2566
|
+
const resolved = await resolveOne(text2, params);
|
|
2567
|
+
if (resolved !== void 0) return resolved;
|
|
2568
|
+
}
|
|
2569
|
+
return void 0;
|
|
2570
|
+
}
|
|
2571
|
+
__name(resolveFlowConfigText, "resolveFlowConfigText");
|
|
2572
|
+
|
|
2522
2573
|
// src/flows/FlowRunner.ts
|
|
2523
2574
|
function contactVariables(profileName) {
|
|
2524
2575
|
if (!profileName) return {};
|
|
@@ -2531,7 +2582,7 @@ __name(contactVariables, "contactVariables");
|
|
|
2531
2582
|
function resolveFlowTimeZone(config) {
|
|
2532
2583
|
const businessHours = config.handoff?.businessHours;
|
|
2533
2584
|
const timeZone = config.timeZone ?? (typeof businessHours === "object" ? businessHours.timeZone : void 0);
|
|
2534
|
-
if (!timeZone) throw new
|
|
2585
|
+
if (!timeZone) throw new import_meta_whatsapp_contracts13.ConfigMissingError("features.flowRunner.timeZone");
|
|
2535
2586
|
new Intl.DateTimeFormat("en-US", {
|
|
2536
2587
|
timeZone
|
|
2537
2588
|
});
|
|
@@ -2636,7 +2687,7 @@ var FlowRunner = class {
|
|
|
2636
2687
|
const graph = savedGraph ?? (isStale ? await this.loadGraph(turn.companyId, this.startFlowKey()) : void 0);
|
|
2637
2688
|
if (!graph) return "no-flow";
|
|
2638
2689
|
await this.claim(turn);
|
|
2639
|
-
if (isStale) await this.report(turn, savedFlowKey, turn.session.currentNodeId, "cross-flow", new
|
|
2690
|
+
if (isStale) await this.report(turn, savedFlowKey, turn.session.currentNodeId, "cross-flow", new import_meta_whatsapp_contracts13.FlowRunnerError("flow-not-found", savedFlowKey));
|
|
2640
2691
|
const node = !isStale && turn.session.currentNodeId ? graph.nodes[turn.session.currentNodeId] : void 0;
|
|
2641
2692
|
const context = {
|
|
2642
2693
|
...turn.session.context
|
|
@@ -2714,7 +2765,7 @@ var FlowRunner = class {
|
|
|
2714
2765
|
const { config } = this.dependencies;
|
|
2715
2766
|
return {
|
|
2716
2767
|
now: config.now?.() ?? /* @__PURE__ */ new Date(),
|
|
2717
|
-
locale: config.dateLocale ??
|
|
2768
|
+
locale: config.dateLocale ?? import_meta_whatsapp_contracts13.FLOW_DATE_LOCALE_PT_BR,
|
|
2718
2769
|
timeZone: this.timeZone
|
|
2719
2770
|
};
|
|
2720
2771
|
}
|
|
@@ -2722,8 +2773,7 @@ var FlowRunner = class {
|
|
|
2722
2773
|
return this.dependencies.flowGraphRepository.get(companyId, flowKey);
|
|
2723
2774
|
}
|
|
2724
2775
|
globalKeywordTarget(answer) {
|
|
2725
|
-
|
|
2726
|
-
return keywords.find((entry) => (0, import_meta_whatsapp_contracts12.matchesFlowKeyword)(answer, entry.keywords))?.target;
|
|
2776
|
+
return matchGlobalKeyword(answer, this.dependencies.config.globalKeywords ?? []);
|
|
2727
2777
|
}
|
|
2728
2778
|
keywordJumpAtStart(start, inbound) {
|
|
2729
2779
|
if (inbound.kind === "unsupported") return void 0;
|
|
@@ -2750,7 +2800,7 @@ var FlowRunner = class {
|
|
|
2750
2800
|
await this.handOff(turn, context);
|
|
2751
2801
|
return "handled";
|
|
2752
2802
|
}
|
|
2753
|
-
const flowKey = target === "restart" ? this.startFlowKey() : (0,
|
|
2803
|
+
const flowKey = target === "restart" ? this.startFlowKey() : (0, import_meta_whatsapp_contracts13.crossFlowKey)(target);
|
|
2754
2804
|
const graph = await this.loadGraph(turn.companyId, flowKey);
|
|
2755
2805
|
if (!graph) return "no-flow";
|
|
2756
2806
|
await this.claim(turn);
|
|
@@ -2768,8 +2818,13 @@ var FlowRunner = class {
|
|
|
2768
2818
|
const dynamic = runtime.dynamic?.nodeId === node.id ? runtime.dynamic : void 0;
|
|
2769
2819
|
const page = dynamic?.page ?? 0;
|
|
2770
2820
|
if (inbound.kind === "unsupported") {
|
|
2771
|
-
const text2 = this.
|
|
2772
|
-
|
|
2821
|
+
const text2 = await this.configText(turn, node, {
|
|
2822
|
+
chain: [
|
|
2823
|
+
this.dependencies.config.nonTextAnswerMessage
|
|
2824
|
+
],
|
|
2825
|
+
kind: "non-text-answer"
|
|
2826
|
+
});
|
|
2827
|
+
await this.say(turn, text2 ?? DEFAULT_FLOW_TEXT.NON_TEXT_ANSWER, context);
|
|
2773
2828
|
return this.awaitAnswer(turn, graph, node, context, page);
|
|
2774
2829
|
}
|
|
2775
2830
|
const decision = resolveFlowAnswer({
|
|
@@ -2780,6 +2835,9 @@ var FlowRunner = class {
|
|
|
2780
2835
|
clock: this.clock(),
|
|
2781
2836
|
...dynamic ? {
|
|
2782
2837
|
dynamicOptions: dynamic.options
|
|
2838
|
+
} : {},
|
|
2839
|
+
...isChoiceNode(node) ? {
|
|
2840
|
+
options: this.renderedOptions(turn, node, context)
|
|
2783
2841
|
} : {}
|
|
2784
2842
|
});
|
|
2785
2843
|
if (decision.kind === "jump") return this.jumpTo(turn, graph, decision.target, withRuntime(context, {}));
|
|
@@ -2793,7 +2851,16 @@ var FlowRunner = class {
|
|
|
2793
2851
|
enterInitialNode: false
|
|
2794
2852
|
});
|
|
2795
2853
|
}
|
|
2796
|
-
if (decision.kind === "invalid")
|
|
2854
|
+
if (decision.kind === "invalid") {
|
|
2855
|
+
return this.handleInvalid(turn, graph, node, context, {
|
|
2856
|
+
rejection: decision.rejection
|
|
2857
|
+
});
|
|
2858
|
+
}
|
|
2859
|
+
const hostRejection = await this.validateWithHost(turn, node, context, {
|
|
2860
|
+
answer: inbound.answer,
|
|
2861
|
+
value: decision.value
|
|
2862
|
+
});
|
|
2863
|
+
if (hostRejection) return this.handleInvalid(turn, graph, node, context, hostRejection);
|
|
2797
2864
|
await this.runFrom(turn, {
|
|
2798
2865
|
graph,
|
|
2799
2866
|
nodeId: node.id,
|
|
@@ -2805,11 +2872,68 @@ var FlowRunner = class {
|
|
|
2805
2872
|
enterInitialNode: false
|
|
2806
2873
|
});
|
|
2807
2874
|
}
|
|
2875
|
+
/** Títulos como o cliente os viu (`{{chave}}` resolvido): é contra eles que o texto digitado casa. */
|
|
2876
|
+
renderedOptions(turn, node, context) {
|
|
2877
|
+
const variables = {
|
|
2878
|
+
...context,
|
|
2879
|
+
...turn.baseVariables
|
|
2880
|
+
};
|
|
2881
|
+
return (node.options ?? []).map(([id, title]) => [
|
|
2882
|
+
id,
|
|
2883
|
+
this.renderer.interpolate(title, variables)
|
|
2884
|
+
]);
|
|
2885
|
+
}
|
|
2886
|
+
/**
|
|
2887
|
+
* Validador do host, só para pergunta (escolha já casou com opção) e nunca para resposta pulada.
|
|
2888
|
+
* Falha do validador não pode prender o cliente na pergunta: reporta e aceita.
|
|
2889
|
+
*/
|
|
2890
|
+
async validateWithHost(turn, node, context, answer) {
|
|
2891
|
+
const validator = this.dependencies.config.validateAnswer;
|
|
2892
|
+
if (!validator || isChoiceNode(node) || node.type === "dynamic_choice" || answer.value === null) return void 0;
|
|
2893
|
+
try {
|
|
2894
|
+
const result = await validator({
|
|
2895
|
+
companyId: turn.companyId,
|
|
2896
|
+
session: turn.session,
|
|
2897
|
+
node,
|
|
2898
|
+
answer: answer.answer.trim(),
|
|
2899
|
+
value: answer.value ?? answer.answer,
|
|
2900
|
+
context
|
|
2901
|
+
});
|
|
2902
|
+
if (!result || result.isValid) return void 0;
|
|
2903
|
+
return {
|
|
2904
|
+
rejection: "rejected-by-host",
|
|
2905
|
+
...result.message ? {
|
|
2906
|
+
message: result.message
|
|
2907
|
+
} : {}
|
|
2908
|
+
};
|
|
2909
|
+
} catch (error) {
|
|
2910
|
+
await this.report(turn, turn.session.flowKey, node.id, "validate-answer", error);
|
|
2911
|
+
return void 0;
|
|
2912
|
+
}
|
|
2913
|
+
}
|
|
2914
|
+
configText(turn, node, params) {
|
|
2915
|
+
return resolveFlowConfigText({
|
|
2916
|
+
chain: params.chain,
|
|
2917
|
+
context: {
|
|
2918
|
+
companyId: turn.companyId,
|
|
2919
|
+
whatsappNumber: turn.session.whatsappNumber,
|
|
2920
|
+
kind: params.kind,
|
|
2921
|
+
flowKey: turn.session.flowKey,
|
|
2922
|
+
...node ? {
|
|
2923
|
+
nodeId: node.id
|
|
2924
|
+
} : {},
|
|
2925
|
+
...params.rejection ? {
|
|
2926
|
+
rejection: params.rejection
|
|
2927
|
+
} : {}
|
|
2928
|
+
},
|
|
2929
|
+
onError: /* @__PURE__ */ __name((error) => this.report(turn, turn.session.flowKey, node?.id ?? null, "text", error), "onError")
|
|
2930
|
+
});
|
|
2931
|
+
}
|
|
2808
2932
|
followsDefaultWhenUnmatched(node) {
|
|
2809
2933
|
if (!isChoiceNode(node)) return false;
|
|
2810
2934
|
return (node.unmatchedChoice ?? this.dependencies.config.unmatchedChoice ?? "reask") === "default";
|
|
2811
2935
|
}
|
|
2812
|
-
async handleInvalid(turn, graph, node, context,
|
|
2936
|
+
async handleInvalid(turn, graph, node, context, invalid) {
|
|
2813
2937
|
const runtime = runtimeOf(context);
|
|
2814
2938
|
const attempts = (runtime.invalidAnswers ?? 0) + 1;
|
|
2815
2939
|
const limit = node.maxInvalidAnswers ?? this.dependencies.config.maxInvalidAnswers ?? DEFAULT_MAX_INVALID_ANSWERS;
|
|
@@ -2818,12 +2942,30 @@ var FlowRunner = class {
|
|
|
2818
2942
|
...runtime,
|
|
2819
2943
|
invalidAnswers: attempts
|
|
2820
2944
|
});
|
|
2821
|
-
await this.say(turn, this.fallbackText(node,
|
|
2945
|
+
await this.say(turn, await this.fallbackText(turn, node, invalid), updated);
|
|
2822
2946
|
await this.awaitAnswer(turn, graph, node, updated, runtime.dynamic?.nodeId === node.id ? runtime.dynamic.page : 0);
|
|
2823
2947
|
}
|
|
2824
|
-
|
|
2948
|
+
/** Precedência: texto do validador do host, `fallbackMessage` do nó, texto do motivo, padrão do host, do pacote. */
|
|
2949
|
+
async fallbackText(turn, node, invalid) {
|
|
2825
2950
|
const { config } = this.dependencies;
|
|
2826
|
-
|
|
2951
|
+
const fixed = invalid.message ?? node.fallbackMessage;
|
|
2952
|
+
if (fixed !== void 0) return fixed;
|
|
2953
|
+
const { rejection } = invalid;
|
|
2954
|
+
const byRejection = rejection ? await this.configText(turn, node, {
|
|
2955
|
+
chain: [
|
|
2956
|
+
config.rejectionMessages?.[rejection]
|
|
2957
|
+
],
|
|
2958
|
+
kind: "rejection",
|
|
2959
|
+
rejection
|
|
2960
|
+
}) : void 0;
|
|
2961
|
+
if (byRejection !== void 0) return byRejection;
|
|
2962
|
+
const fallback = await this.configText(turn, node, {
|
|
2963
|
+
chain: [
|
|
2964
|
+
config.defaultFallbackMessage
|
|
2965
|
+
],
|
|
2966
|
+
kind: "fallback"
|
|
2967
|
+
});
|
|
2968
|
+
return fallback ?? DEFAULT_FLOW_TEXT.FALLBACK;
|
|
2827
2969
|
}
|
|
2828
2970
|
async handOff(turn, context) {
|
|
2829
2971
|
const isWithinHours = await this.dependencies.handoff.request({
|
|
@@ -2844,8 +2986,8 @@ var FlowRunner = class {
|
|
|
2844
2986
|
});
|
|
2845
2987
|
}
|
|
2846
2988
|
async jumpTo(turn, graph, target, context) {
|
|
2847
|
-
if ((0,
|
|
2848
|
-
const targetGraph = await this.loadGraph(turn.companyId, (0,
|
|
2989
|
+
if ((0, import_meta_whatsapp_contracts13.isCrossFlowTarget)(target)) {
|
|
2990
|
+
const targetGraph = await this.loadGraph(turn.companyId, (0, import_meta_whatsapp_contracts13.crossFlowKey)(target));
|
|
2849
2991
|
if (!targetGraph) return this.reportMissingFlow(turn, graph.key, target, context);
|
|
2850
2992
|
return this.runFrom(turn, {
|
|
2851
2993
|
graph: targetGraph,
|
|
@@ -2903,7 +3045,7 @@ var FlowRunner = class {
|
|
|
2903
3045
|
nodeId: null,
|
|
2904
3046
|
context: result.context
|
|
2905
3047
|
});
|
|
2906
|
-
return this.report(turn, params.graph.key, null, "max-steps", new
|
|
3048
|
+
return this.report(turn, params.graph.key, null, "max-steps", new import_meta_whatsapp_contracts13.FlowRunnerError("cycle", result.visited.join(" -> ")));
|
|
2907
3049
|
}
|
|
2908
3050
|
const target = await this.loadGraph(turn.companyId, result.flowKey);
|
|
2909
3051
|
if (!target) return this.reportMissingFlow(turn, params.graph.key, result.flowKey, result.context);
|
|
@@ -2919,7 +3061,7 @@ var FlowRunner = class {
|
|
|
2919
3061
|
nodeId: null,
|
|
2920
3062
|
context: params.context
|
|
2921
3063
|
});
|
|
2922
|
-
return this.report(turn, params.graph.key, null, "cross-flow", new
|
|
3064
|
+
return this.report(turn, params.graph.key, null, "cross-flow", new import_meta_whatsapp_contracts13.FlowRunnerError("too-many-jumps", params.graph.key));
|
|
2923
3065
|
}
|
|
2924
3066
|
/** Grava a posição no nó e pergunta. Para `dynamic_choice`, busca a página antes de gravar. */
|
|
2925
3067
|
async awaitAnswer(turn, graph, node, context, page) {
|
|
@@ -2985,7 +3127,7 @@ var FlowRunner = class {
|
|
|
2985
3127
|
nodeId: null,
|
|
2986
3128
|
context
|
|
2987
3129
|
});
|
|
2988
|
-
await this.report(turn, fromFlowKey, null, "cross-flow", new
|
|
3130
|
+
await this.report(turn, fromFlowKey, null, "cross-flow", new import_meta_whatsapp_contracts13.FlowRunnerError("flow-not-found", target));
|
|
2989
3131
|
}
|
|
2990
3132
|
/**
|
|
2991
3133
|
* Nunca relança: só é chamado depois de o turno ter sido gravado, e relançar faria a fila repetir
|
|
@@ -3008,7 +3150,7 @@ var FlowRunner = class {
|
|
|
3008
3150
|
};
|
|
3009
3151
|
|
|
3010
3152
|
// src/flows/FlowHandoff.ts
|
|
3011
|
-
var
|
|
3153
|
+
var import_meta_whatsapp_contracts14 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3012
3154
|
function readParam(node, key) {
|
|
3013
3155
|
const value = node?.actionParams?.[key];
|
|
3014
3156
|
return typeof value === "string" && value.trim().length > 0 ? value : void 0;
|
|
@@ -3031,14 +3173,14 @@ var FlowHandoff = class {
|
|
|
3031
3173
|
whatsappNumber: params.whatsappNumber
|
|
3032
3174
|
});
|
|
3033
3175
|
} catch (error) {
|
|
3034
|
-
await this.reportFailure(error, params);
|
|
3176
|
+
await this.reportFailure(error, params, "handoff");
|
|
3035
3177
|
}
|
|
3036
3178
|
const isWithinHours = await this.isWithinHours(params.companyId);
|
|
3037
|
-
const template = this.messageFor(isWithinHours, params
|
|
3179
|
+
const template = await this.messageFor(isWithinHours, params);
|
|
3038
3180
|
await sendMessage.sendText({
|
|
3039
3181
|
companyId: params.companyId,
|
|
3040
3182
|
whatsappNumber: params.whatsappNumber,
|
|
3041
|
-
body: (0,
|
|
3183
|
+
body: (0, import_meta_whatsapp_contracts14.interpolateFlowText)(template, params.variables, interpolation),
|
|
3042
3184
|
sender: "bot",
|
|
3043
3185
|
startState
|
|
3044
3186
|
});
|
|
@@ -3066,14 +3208,14 @@ var FlowHandoff = class {
|
|
|
3066
3208
|
};
|
|
3067
3209
|
};
|
|
3068
3210
|
}
|
|
3069
|
-
async reportFailure(error, params) {
|
|
3211
|
+
async reportFailure(error, params, stage) {
|
|
3070
3212
|
try {
|
|
3071
3213
|
await this.dependencies.hooks?.onFlowRunnerError?.(error, {
|
|
3072
3214
|
companyId: params.companyId,
|
|
3073
3215
|
whatsappNumber: params.whatsappNumber,
|
|
3074
3216
|
flowKey: null,
|
|
3075
3217
|
nodeId: params.node?.id ?? null,
|
|
3076
|
-
stage
|
|
3218
|
+
stage
|
|
3077
3219
|
});
|
|
3078
3220
|
} catch {
|
|
3079
3221
|
}
|
|
@@ -3081,13 +3223,35 @@ var FlowHandoff = class {
|
|
|
3081
3223
|
async isWithinHours(companyId) {
|
|
3082
3224
|
const source = this.dependencies.config.businessHours;
|
|
3083
3225
|
const hours = typeof source === "function" ? await source(companyId) : source;
|
|
3084
|
-
return hours ? (0,
|
|
3226
|
+
return hours ? (0, import_meta_whatsapp_contracts14.isWithinBusinessHours)(hours, this.dependencies.now()) : true;
|
|
3085
3227
|
}
|
|
3086
|
-
messageFor(isWithinHours,
|
|
3228
|
+
async messageFor(isWithinHours, params) {
|
|
3087
3229
|
const { config } = this.dependencies;
|
|
3088
|
-
const
|
|
3089
|
-
|
|
3090
|
-
|
|
3230
|
+
const { node } = params;
|
|
3231
|
+
const chain = isWithinHours ? [
|
|
3232
|
+
readParam(node, "message"),
|
|
3233
|
+
config.message,
|
|
3234
|
+
DEFAULT_FLOW_TEXT.HANDOFF
|
|
3235
|
+
] : [
|
|
3236
|
+
readParam(node, "outOfHoursMessage"),
|
|
3237
|
+
config.outOfHoursMessage,
|
|
3238
|
+
readParam(node, "message"),
|
|
3239
|
+
config.message,
|
|
3240
|
+
DEFAULT_FLOW_TEXT.HANDOFF_OUT_OF_HOURS
|
|
3241
|
+
];
|
|
3242
|
+
const text2 = await resolveFlowConfigText({
|
|
3243
|
+
chain,
|
|
3244
|
+
context: {
|
|
3245
|
+
companyId: params.companyId,
|
|
3246
|
+
whatsappNumber: params.whatsappNumber,
|
|
3247
|
+
kind: isWithinHours ? "handoff" : "handoff-out-of-hours",
|
|
3248
|
+
...node ? {
|
|
3249
|
+
nodeId: node.id
|
|
3250
|
+
} : {}
|
|
3251
|
+
},
|
|
3252
|
+
onError: /* @__PURE__ */ __name((error) => this.reportFailure(error, params, "text"), "onError")
|
|
3253
|
+
});
|
|
3254
|
+
return text2 ?? DEFAULT_FLOW_TEXT.HANDOFF;
|
|
3091
3255
|
}
|
|
3092
3256
|
};
|
|
3093
3257
|
|
|
@@ -3420,10 +3584,10 @@ var FlowMediaIdRepository = class {
|
|
|
3420
3584
|
|
|
3421
3585
|
// src/channel/WhatsAppChannelAdapter.ts
|
|
3422
3586
|
var import_meta_graph_core2 = require("@adatechnology/meta-graph-core");
|
|
3423
|
-
var
|
|
3587
|
+
var import_meta_whatsapp_contracts16 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3424
3588
|
|
|
3425
3589
|
// src/channel/previewMedia.ts
|
|
3426
|
-
var
|
|
3590
|
+
var import_meta_whatsapp_contracts15 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3427
3591
|
|
|
3428
3592
|
// src/channel/WhatsAppChannelAdapter.ts
|
|
3429
3593
|
var WhatsAppChannelAdapter = class {
|
|
@@ -3440,14 +3604,14 @@ var WhatsAppChannelAdapter = class {
|
|
|
3440
3604
|
}
|
|
3441
3605
|
/** `preview.<uuid>` quando o destino é contato do simulador e o recurso está ligado. */
|
|
3442
3606
|
previewMessageId(to) {
|
|
3443
|
-
if (!this.previewContacts?.isEnabled || !(0,
|
|
3607
|
+
if (!this.previewContacts?.isEnabled || !(0, import_meta_whatsapp_contracts16.isPreviewContact)(to)) return void 0;
|
|
3444
3608
|
return `preview.${this.previewContacts.generateId?.() ?? globalThis.crypto.randomUUID()}`;
|
|
3445
3609
|
}
|
|
3446
3610
|
async translateErrors(operation) {
|
|
3447
3611
|
try {
|
|
3448
3612
|
return await operation();
|
|
3449
3613
|
} catch (error) {
|
|
3450
|
-
if (error instanceof import_meta_graph_core2.WhatsAppWindowExpiredError) throw new
|
|
3614
|
+
if (error instanceof import_meta_graph_core2.WhatsAppWindowExpiredError) throw new import_meta_whatsapp_contracts16.WindowExpiredError();
|
|
3451
3615
|
throw error;
|
|
3452
3616
|
}
|
|
3453
3617
|
}
|
|
@@ -3550,7 +3714,7 @@ var WhatsAppChannelAdapter = class {
|
|
|
3550
3714
|
* tentar buscá-lo lá renderia um 404 confuso em vez do áudio que o operador acabou de gravar.
|
|
3551
3715
|
*/
|
|
3552
3716
|
async fetchMediaAsBase64(mediaId) {
|
|
3553
|
-
const uploadId = this.previewMedia?.isEnabled ? (0,
|
|
3717
|
+
const uploadId = this.previewMedia?.isEnabled ? (0, import_meta_whatsapp_contracts15.resolvePreviewUploadId)(mediaId) : void 0;
|
|
3554
3718
|
if (uploadId) {
|
|
3555
3719
|
const buffer = await this.previewMedia.objectStorage.getObject(uploadId);
|
|
3556
3720
|
return {
|
|
@@ -3563,19 +3727,19 @@ var WhatsAppChannelAdapter = class {
|
|
|
3563
3727
|
};
|
|
3564
3728
|
|
|
3565
3729
|
// src/channel/ReceiveWebhook.use-case.ts
|
|
3566
|
-
var
|
|
3730
|
+
var import_meta_whatsapp_contracts19 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3567
3731
|
|
|
3568
3732
|
// src/channel/webhookSecurity.ts
|
|
3569
3733
|
var import_meta_graph_core3 = require("@adatechnology/meta-graph-core");
|
|
3570
|
-
var
|
|
3734
|
+
var import_meta_whatsapp_contracts17 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3571
3735
|
var WEBHOOK_NONCE_NAMESPACE = "meta-whatsapp";
|
|
3572
3736
|
function verifyWebhookChallenge(params) {
|
|
3573
|
-
if (!(0, import_meta_graph_core3.isValidWebhookChallenge)(params)) throw new
|
|
3737
|
+
if (!(0, import_meta_graph_core3.isValidWebhookChallenge)(params)) throw new import_meta_whatsapp_contracts17.InvalidWebhookSignatureError();
|
|
3574
3738
|
return params.challenge;
|
|
3575
3739
|
}
|
|
3576
3740
|
__name(verifyWebhookChallenge, "verifyWebhookChallenge");
|
|
3577
3741
|
function verifyWebhookSignature(params) {
|
|
3578
|
-
if (!(0, import_meta_graph_core3.isValidWebhookSignature)(params)) throw new
|
|
3742
|
+
if (!(0, import_meta_graph_core3.isValidWebhookSignature)(params)) throw new import_meta_whatsapp_contracts17.InvalidWebhookSignatureError();
|
|
3579
3743
|
}
|
|
3580
3744
|
__name(verifyWebhookSignature, "verifyWebhookSignature");
|
|
3581
3745
|
function deliveryKey(signatureHeader) {
|
|
@@ -3598,7 +3762,7 @@ __name(confirmWebhookDelivery, "confirmWebhookDelivery");
|
|
|
3598
3762
|
var import_drizzle_orm10 = require("drizzle-orm");
|
|
3599
3763
|
|
|
3600
3764
|
// src/use-cases/TranscribeAudio.use-case.ts
|
|
3601
|
-
var
|
|
3765
|
+
var import_meta_whatsapp_contracts18 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3602
3766
|
|
|
3603
3767
|
// src/transcription.types.ts
|
|
3604
3768
|
var TRANSCRIPTION_STATUS = {
|
|
@@ -3659,7 +3823,7 @@ var TranscribeAudioUseCase = class {
|
|
|
3659
3823
|
}
|
|
3660
3824
|
if (this.dependencies.resolvePolicy) {
|
|
3661
3825
|
const policy = await this.dependencies.resolvePolicy(params.companyId);
|
|
3662
|
-
if (!policy.isEnabled) throw new
|
|
3826
|
+
if (!policy.isEnabled) throw new import_meta_whatsapp_contracts18.TranscriptionDisabledError();
|
|
3663
3827
|
}
|
|
3664
3828
|
const audio = extractAudioReference(message);
|
|
3665
3829
|
const buffer = await this.dependencies.objectStorage.getObject(audio.uploadId);
|
|
@@ -3736,11 +3900,11 @@ function extractAudioReference(message) {
|
|
|
3736
3900
|
const audio = payload["audio"];
|
|
3737
3901
|
const mimeType = typeof payload["mimeType"] === "string" ? payload["mimeType"] : audio?.mime_type;
|
|
3738
3902
|
if (!isAudioMimeType(mimeType) && !audio) {
|
|
3739
|
-
throw new
|
|
3903
|
+
throw new import_meta_whatsapp_contracts18.MessageNotAudioError(message.id, message.type);
|
|
3740
3904
|
}
|
|
3741
3905
|
const uploadId = payload["uploadId"];
|
|
3742
3906
|
if (typeof uploadId !== "string" || uploadId.length === 0) {
|
|
3743
|
-
throw new
|
|
3907
|
+
throw new import_meta_whatsapp_contracts18.AudioNotIngestedError(message.id);
|
|
3744
3908
|
}
|
|
3745
3909
|
return {
|
|
3746
3910
|
uploadId,
|
|
@@ -3956,8 +4120,8 @@ function extractPayload(message, { isLocationRedacted } = DEFAULT_EXTRACTION_OPT
|
|
|
3956
4120
|
}
|
|
3957
4121
|
__name(extractPayload, "extractPayload");
|
|
3958
4122
|
var ACCOUNT_EVENT_FIELDS = [
|
|
3959
|
-
|
|
3960
|
-
|
|
4123
|
+
import_meta_whatsapp_contracts19.WHATSAPP_WEBHOOK_FIELDS.TEMPLATE_STATUS_UPDATE,
|
|
4124
|
+
import_meta_whatsapp_contracts19.WHATSAPP_WEBHOOK_FIELDS.PHONE_NUMBER_QUALITY_UPDATE
|
|
3961
4125
|
];
|
|
3962
4126
|
function isAccountEventField(field) {
|
|
3963
4127
|
return field !== void 0 && ACCOUNT_EVENT_FIELDS.includes(field);
|
|
@@ -3999,7 +4163,7 @@ var ReceiveWebhookUseCase = class {
|
|
|
3999
4163
|
...EMPTY_RESULT
|
|
4000
4164
|
};
|
|
4001
4165
|
const rawText = typeof input.rawBody === "string" ? input.rawBody : input.rawBody.toString("utf8");
|
|
4002
|
-
const parsed =
|
|
4166
|
+
const parsed = import_meta_whatsapp_contracts19.whatsAppWebhookPayloadSchema.safeParse(JSON.parse(rawText));
|
|
4003
4167
|
if (!parsed.success) {
|
|
4004
4168
|
await this.params.hooks?.onUnhandledWebhookEvent?.({
|
|
4005
4169
|
field: void 0,
|
|
@@ -4032,7 +4196,7 @@ var ReceiveWebhookUseCase = class {
|
|
|
4032
4196
|
continue;
|
|
4033
4197
|
}
|
|
4034
4198
|
for (const message of change.value.messages ?? []) {
|
|
4035
|
-
const profileName = (0,
|
|
4199
|
+
const profileName = (0, import_meta_whatsapp_contracts19.resolveContactProfileName)({
|
|
4036
4200
|
contacts: change.value.contacts,
|
|
4037
4201
|
from: message.from
|
|
4038
4202
|
});
|
|
@@ -4070,8 +4234,8 @@ var ReceiveWebhookUseCase = class {
|
|
|
4070
4234
|
// Devolve `false` quando o corpo não bate com o schema do field — o chamador conta como não
|
|
4071
4235
|
// tratado. O host é avisado nos dois casos, mas com `reason` diferente.
|
|
4072
4236
|
async handleAccountEvent(change) {
|
|
4073
|
-
if (change.field ===
|
|
4074
|
-
const update =
|
|
4237
|
+
if (change.field === import_meta_whatsapp_contracts19.WHATSAPP_WEBHOOK_FIELDS.TEMPLATE_STATUS_UPDATE) {
|
|
4238
|
+
const update = import_meta_whatsapp_contracts19.whatsAppTemplateStatusUpdateSchema.safeParse(change.value);
|
|
4075
4239
|
if (!update.success) {
|
|
4076
4240
|
await this.params.hooks?.onUnhandledWebhookEvent?.({
|
|
4077
4241
|
field: change.field,
|
|
@@ -4083,7 +4247,7 @@ var ReceiveWebhookUseCase = class {
|
|
|
4083
4247
|
await this.params.hooks?.onTemplateStatusUpdate?.(update.data);
|
|
4084
4248
|
return true;
|
|
4085
4249
|
}
|
|
4086
|
-
const quality =
|
|
4250
|
+
const quality = import_meta_whatsapp_contracts19.whatsAppPhoneNumberQualityUpdateSchema.safeParse(change.value);
|
|
4087
4251
|
if (!quality.success) {
|
|
4088
4252
|
await this.params.hooks?.onUnhandledWebhookEvent?.({
|
|
4089
4253
|
field: change.field,
|
|
@@ -4145,6 +4309,7 @@ var ReceiveWebhookUseCase = class {
|
|
|
4145
4309
|
});
|
|
4146
4310
|
if (!updated) return;
|
|
4147
4311
|
this.params.realtime?.emit(`conv:${updated.whatsappNumber}`, "message-status", {
|
|
4312
|
+
companyId,
|
|
4148
4313
|
waMessageId: status.id,
|
|
4149
4314
|
status: status.status
|
|
4150
4315
|
});
|
|
@@ -4214,7 +4379,7 @@ var StorePreviewMediaUseCase = class {
|
|
|
4214
4379
|
key
|
|
4215
4380
|
});
|
|
4216
4381
|
return {
|
|
4217
|
-
mediaId: (0,
|
|
4382
|
+
mediaId: (0, import_meta_whatsapp_contracts15.toPreviewMediaId)(uploadId),
|
|
4218
4383
|
uploadId
|
|
4219
4384
|
};
|
|
4220
4385
|
}
|
|
@@ -4281,7 +4446,7 @@ function createMetaWhatsAppModule(params) {
|
|
|
4281
4446
|
} : {}
|
|
4282
4447
|
}) : void 0;
|
|
4283
4448
|
if (flowInterpreter && flowRunner && flowHandoff) {
|
|
4284
|
-
flowInterpreter.registerFlowAction(
|
|
4449
|
+
flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts20.FLOW_ACTION_KIND.HANDOFF, flowHandoff.createActionHandler((turn) => flowRunner.variablesFor(turn)));
|
|
4285
4450
|
}
|
|
4286
4451
|
const receiveWebhook = new ReceiveWebhookUseCase({
|
|
4287
4452
|
appSecret: config.appSecret,
|
|
@@ -4302,7 +4467,7 @@ function createMetaWhatsAppModule(params) {
|
|
|
4302
4467
|
} : {}
|
|
4303
4468
|
});
|
|
4304
4469
|
if (flowInterpreter && providers.objectStorage?.getObject) {
|
|
4305
|
-
flowInterpreter.registerFlowAction(
|
|
4470
|
+
flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts20.FLOW_ACTION_KIND.SEND_MEDIA, createSendMediaAction({
|
|
4306
4471
|
flowMediaRepository,
|
|
4307
4472
|
objectStorage: providers.objectStorage,
|
|
4308
4473
|
logMessage,
|
|
@@ -4319,7 +4484,7 @@ function createMetaWhatsAppModule(params) {
|
|
|
4319
4484
|
}));
|
|
4320
4485
|
}
|
|
4321
4486
|
if (flowInterpreter && providers.catalog && config.catalogId) {
|
|
4322
|
-
flowInterpreter.registerFlowAction(
|
|
4487
|
+
flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts20.FLOW_ACTION_KIND.SEND_PRODUCT_LIST, createSendProductListAction({
|
|
4323
4488
|
catalog: providers.catalog,
|
|
4324
4489
|
catalogId: config.catalogId,
|
|
4325
4490
|
logMessage,
|
|
@@ -4448,7 +4613,7 @@ function createMetaWhatsAppModule(params) {
|
|
|
4448
4613
|
// undefined quando `features.flowRunner` está desligado — o host dirige a conversa.
|
|
4449
4614
|
runner: flowRunner,
|
|
4450
4615
|
registerDynamicChoiceProvider: /* @__PURE__ */ __name((key, provider) => {
|
|
4451
|
-
if (!flowRunner) throw new
|
|
4616
|
+
if (!flowRunner) throw new import_meta_whatsapp_contracts20.ConfigMissingError("features.flowRunner");
|
|
4452
4617
|
flowRunner.registerDynamicChoiceProvider(key, provider);
|
|
4453
4618
|
}, "registerDynamicChoiceProvider"),
|
|
4454
4619
|
get: new GetFlowGraphUseCase(flowGraphRepository),
|
|
@@ -4656,6 +4821,7 @@ __name(redeemSseTicket, "redeemSseTicket");
|
|
|
4656
4821
|
redeemSseTicket,
|
|
4657
4822
|
resolveFailureStatus,
|
|
4658
4823
|
resolveFlowAnswer,
|
|
4824
|
+
resolveFlowConfigText,
|
|
4659
4825
|
resolveFlowTimeZone,
|
|
4660
4826
|
resolvePreviewUploadId,
|
|
4661
4827
|
runMetaWhatsAppMigrations,
|