@adatechnology/conversations-ui 0.17.0 → 0.18.1
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/flows/index.d.ts +33 -3
- package/dist/flows/index.js +44 -7
- package/dist/index.d.ts +44 -1
- package/dist/index.js +60 -0
- package/package.json +2 -2
- package/src/flows/FlowsWorkspace.tsx +8 -2
- package/src/flows/flowGraph.ts +71 -4
- package/src/flows/flowLabelValidation.test.ts +92 -0
- package/src/flows/index.ts +3 -0
- package/src/flows/labels.ts +11 -0
- package/src/index.ts +9 -0
- package/src/quickReplies/createMetaWhatsAppQuickRepliesClient.test.ts +113 -0
- package/src/quickReplies/createMetaWhatsAppQuickRepliesClient.ts +111 -0
package/dist/flows/index.d.ts
CHANGED
|
@@ -35,11 +35,28 @@ declare const WHATSAPP_LIMITS: {
|
|
|
35
35
|
readonly MAX_BUTTONS: 3;
|
|
36
36
|
readonly MAX_LIST_ROWS: 10;
|
|
37
37
|
readonly BUTTON_TITLE_MAX: 20;
|
|
38
|
+
readonly LIST_BUTTON_LABEL_MAX: 20;
|
|
38
39
|
readonly LIST_ROW_TITLE_MAX: 24;
|
|
39
40
|
readonly LIST_ROW_DESCRIPTION_MAX: 72;
|
|
40
41
|
readonly LIST_SECTION_TITLE_MAX: 24;
|
|
41
42
|
readonly BODY_MAX: 1024;
|
|
42
43
|
};
|
|
44
|
+
type MeasuredLabel = {
|
|
45
|
+
/** Caracteres do texto como o cliente o leria; sem exemplo para uma variável, ela vale 0 (mínimo certo). */
|
|
46
|
+
readonly length: number;
|
|
47
|
+
/** `true` quando alguma `{{variável}}` ficou sem exemplo: o tamanho real só se sabe em tempo de execução. */
|
|
48
|
+
readonly isApproximate: boolean;
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Mede um rótulo com `{{variável}}` sobre o texto interpolado com o exemplo da variável. Sem exemplo,
|
|
52
|
+
* mede o texto sem ela — contar a marcação escrita daria erro falso (`{{nome}}` vale 8 e a variável
|
|
53
|
+
* real pode ter 4).
|
|
54
|
+
*/
|
|
55
|
+
declare function measureLabel(label: string, variableExamples?: Readonly<Record<string, string>>): MeasuredLabel;
|
|
56
|
+
type ValidateGraphOptions = {
|
|
57
|
+
/** Valor de exemplo por variável (`{ buttonName: 'Pernoite' }`), usado para medir rótulos de botão e linha de lista. */
|
|
58
|
+
readonly variableExamples?: Readonly<Record<string, string>>;
|
|
59
|
+
};
|
|
43
60
|
/**
|
|
44
61
|
* Botão com até 3 opções simples; opção com descrição ou seção força lista — é a mesma regra do
|
|
45
62
|
* runner do módulo, para a prévia mostrar o que o cliente vai ver.
|
|
@@ -77,7 +94,11 @@ declare function validateGraph(graph: FlowGraphData, issueText: {
|
|
|
77
94
|
dynamicChoiceWithoutProvider?: (id: string) => string;
|
|
78
95
|
choiceDefaultIgnored?: (id: string) => string;
|
|
79
96
|
possibleNextIgnored?: (id: string) => string;
|
|
80
|
-
|
|
97
|
+
buttonTitleMayBeTooLong?: (id: string, label: string) => string;
|
|
98
|
+
listTitleMayBeTooLong?: (id: string, label: string) => string;
|
|
99
|
+
listButtonLabelTooLong?: (id: string, label: string) => string;
|
|
100
|
+
listButtonLabelMayBeTooLong?: (id: string, label: string) => string;
|
|
101
|
+
}, settings?: ValidateGraphOptions): GraphIssue[];
|
|
81
102
|
/**
|
|
82
103
|
* Auto-layout em cascata: avança para a direita a cada passo do fluxo e desce a cada card.
|
|
83
104
|
*
|
|
@@ -316,6 +337,10 @@ interface FlowValidationLabels {
|
|
|
316
337
|
descriptionTooLong?: (id: string, label: string) => string;
|
|
317
338
|
dynamicChoiceWithoutProvider?: (id: string) => string;
|
|
318
339
|
choiceDefaultIgnored?: (id: string) => string;
|
|
340
|
+
buttonTitleMayBeTooLong?: (id: string, label: string) => string;
|
|
341
|
+
listTitleMayBeTooLong?: (id: string, label: string) => string;
|
|
342
|
+
listButtonLabelTooLong?: (id: string, label: string) => string;
|
|
343
|
+
listButtonLabelMayBeTooLong?: (id: string, label: string) => string;
|
|
319
344
|
}
|
|
320
345
|
declare const DEFAULT_FLOW_EDITOR_LABELS: FlowEditorLabels;
|
|
321
346
|
declare function mergeFlowEditorLabels(override?: Partial<FlowEditorLabels>): FlowEditorLabels;
|
|
@@ -660,6 +685,11 @@ interface FlowsWorkspaceProps {
|
|
|
660
685
|
* pacote a adivinhar a escala tipográfica de cada produto.
|
|
661
686
|
*/
|
|
662
687
|
readonly showHeader?: boolean;
|
|
688
|
+
/**
|
|
689
|
+
* Valor de exemplo por variável usada em rótulo de botão e linha de lista (`{ buttonName: 'Pernoite' }`).
|
|
690
|
+
* Com exemplo, o validador mede o texto interpolado; sem, só avisa quando a marcação escrita passa do limite.
|
|
691
|
+
*/
|
|
692
|
+
readonly variableExamples?: Readonly<Record<string, string>>;
|
|
663
693
|
readonly className?: string;
|
|
664
694
|
}
|
|
665
695
|
/**
|
|
@@ -670,7 +700,7 @@ interface FlowsWorkspaceProps {
|
|
|
670
700
|
* versão diferente do mesmo editor. Customização entra por `labels`, `actionOptions` e
|
|
671
701
|
* `renderMediaPicker` — nunca por cópia do arquivo.
|
|
672
702
|
*/
|
|
673
|
-
declare function FlowsWorkspace({ api, rootFlowKey, labels: labelsOverride, actionOptions, renderMediaPicker, livePollIntervalMs, showHeader, className, }: FlowsWorkspaceProps): react.JSX.Element;
|
|
703
|
+
declare function FlowsWorkspace({ api, rootFlowKey, labels: labelsOverride, actionOptions, renderMediaPicker, livePollIntervalMs, showHeader, variableExamples, className, }: FlowsWorkspaceProps): react.JSX.Element;
|
|
674
704
|
|
|
675
705
|
/**
|
|
676
706
|
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
@@ -743,4 +773,4 @@ declare function applyConnection(node: FlowNodeData, resolved: ResolvedConnectio
|
|
|
743
773
|
*/
|
|
744
774
|
declare function isGraphDirty(working: FlowGraphData | undefined, published: FlowGraphData | undefined): boolean;
|
|
745
775
|
|
|
746
|
-
export { BUILT_IN_ACTION_KINDS, CONDITION_OPERATORS, CROSS_FLOW_PREFIX, type CollectionChain, type ConnectionRequest, type CreateFlowInput, DEFAULT_FLOW_EDITOR_LABELS, FlowConnectionEdge, type FlowEdgeKind, type FlowEdgeSpec, type FlowEditorLabels, FlowGroupFrame, type FlowGroupFrameData, FlowGroupHeader, type FlowGroupHeaderData, FlowLegend, type FlowLiveNodeCount, type FlowLivePosition, type FlowLivePositionInput, FlowMapCanvas, type FlowMapCanvasProps, FlowMapNode, type FlowMapNodeData, FlowNodeCard, type FlowNodeCardData, FlowNodePanel, type FlowNodePanelProps, type FlowNodePosition, FlowPalette, type FlowPaletteActionOption, FlowPaletteMenu, type FlowPaletteProps, FlowPortalNode, type FlowPortalNodeData, type FlowValidationLabels, FlowWhatsAppPreview, type FlowWhatsAppPreviewProps, FlowsWorkspace, type FlowsWorkspaceApi, type FlowsWorkspaceProps, GROUP_HEADER_NODE_ID, type GraphIssue, NODE_CARD_WIDTH, type NewNodeSpec, PASS_THROUGH_ACTION_KINDS, type ResolvedConnection, WHATSAPP_LIMITS, applyConnection, buildFlowEdges, chainFrameBounds, chainFrameNodeId, computeAutoLayout, computeFlowMapLayout, computeMergedLayout, countLiveByNode, crossFlowKey, crossFlowTargetsOf, detachedNodeIds, estimateNodeHeight, findCollectionChains, flowEdgeTypes, flowGroupFrameNodeTypes, flowGroupHeaderNodeTypes, flowMapNodeTypes, flowNodeTypes, flowPortalNodeTypes, isCrossFlowTarget, isGraphDirty, mergeFlowEditorLabels, mergedFlowKeysFrom, namespaceNodeId, newNodeFromSpec, nodeLabel, parseNamespacedId, portalNodeId, removeNodeAndCleanRefs, rendersAsButtons, resolveConnection, slugifyNodeId, targetsOf, validateGraph };
|
|
776
|
+
export { BUILT_IN_ACTION_KINDS, CONDITION_OPERATORS, CROSS_FLOW_PREFIX, type CollectionChain, type ConnectionRequest, type CreateFlowInput, DEFAULT_FLOW_EDITOR_LABELS, FlowConnectionEdge, type FlowEdgeKind, type FlowEdgeSpec, type FlowEditorLabels, FlowGroupFrame, type FlowGroupFrameData, FlowGroupHeader, type FlowGroupHeaderData, FlowLegend, type FlowLiveNodeCount, type FlowLivePosition, type FlowLivePositionInput, FlowMapCanvas, type FlowMapCanvasProps, FlowMapNode, type FlowMapNodeData, FlowNodeCard, type FlowNodeCardData, FlowNodePanel, type FlowNodePanelProps, type FlowNodePosition, FlowPalette, type FlowPaletteActionOption, FlowPaletteMenu, type FlowPaletteProps, FlowPortalNode, type FlowPortalNodeData, type FlowValidationLabels, FlowWhatsAppPreview, type FlowWhatsAppPreviewProps, FlowsWorkspace, type FlowsWorkspaceApi, type FlowsWorkspaceProps, GROUP_HEADER_NODE_ID, type GraphIssue, type MeasuredLabel, NODE_CARD_WIDTH, type NewNodeSpec, PASS_THROUGH_ACTION_KINDS, type ResolvedConnection, type ValidateGraphOptions, WHATSAPP_LIMITS, applyConnection, buildFlowEdges, chainFrameBounds, chainFrameNodeId, computeAutoLayout, computeFlowMapLayout, computeMergedLayout, countLiveByNode, crossFlowKey, crossFlowTargetsOf, detachedNodeIds, estimateNodeHeight, findCollectionChains, flowEdgeTypes, flowGroupFrameNodeTypes, flowGroupHeaderNodeTypes, flowMapNodeTypes, flowNodeTypes, flowPortalNodeTypes, isCrossFlowTarget, isGraphDirty, measureLabel, mergeFlowEditorLabels, mergedFlowKeysFrom, namespaceNodeId, newNodeFromSpec, nodeLabel, parseNamespacedId, portalNodeId, removeNodeAndCleanRefs, rendersAsButtons, resolveConnection, slugifyNodeId, targetsOf, validateGraph };
|
package/dist/flows/index.js
CHANGED
|
@@ -218,6 +218,10 @@ var DEFAULT_FLOW_EDITOR_LABELS = {
|
|
|
218
218
|
deadEndQuestion: (id) => `N\xF3 "${id}": pergunta sem pr\xF3ximo passo definido.`,
|
|
219
219
|
conditionIncomplete: (id) => `N\xF3 "${id}": condi\xE7\xE3o incompleta \u2014 defina vari\xE1vel, operador e valor.`,
|
|
220
220
|
conditionBranchMissing: (id, branch) => `N\xF3 "${id}": ramo "${branch === "true" ? "Verdadeiro" : "Falso"}" sem destino definido.`,
|
|
221
|
+
buttonTitleMayBeTooLong: (id, label) => `N\xF3 "${id}": bot\xE3o "${label}" tem vari\xE1vel e pode passar de 20 caracteres; confira o valor real.`,
|
|
222
|
+
listTitleMayBeTooLong: (id, label) => `N\xF3 "${id}": item de lista "${label}" tem vari\xE1vel e pode passar de 24 caracteres; confira o valor real.`,
|
|
223
|
+
listButtonLabelTooLong: (id, label) => `N\xF3 "${id}": bot\xE3o da lista "${label}" passa de 20 caracteres.`,
|
|
224
|
+
listButtonLabelMayBeTooLong: (id, label) => `N\xF3 "${id}": bot\xE3o da lista "${label}" tem vari\xE1vel e pode passar de 20 caracteres; confira o valor real.`,
|
|
221
225
|
descriptionTooLong: (id, label) => `N\xF3 "${id}": a descri\xE7\xE3o de "${label}" passa de 72 caracteres.`,
|
|
222
226
|
dynamicChoiceWithoutProvider: (id) => `N\xF3 "${id}": escolha din\xE2mica sem provedor de op\xE7\xF5es.`,
|
|
223
227
|
choiceDefaultIgnored: (id) => `N\xF3 "${id}": o bot repergunta quando a resposta n\xE3o casa com uma op\xE7\xE3o, ent\xE3o "Caso contr\xE1rio" n\xE3o \xE9 seguido. Para seguir, mude "Resposta fora das op\xE7\xF5es".`
|
|
@@ -324,6 +328,7 @@ var WHATSAPP_LIMITS = {
|
|
|
324
328
|
MAX_BUTTONS: WHATSAPP_CHOICE_LIMIT.BUTTONS,
|
|
325
329
|
MAX_LIST_ROWS: WHATSAPP_CHOICE_LIMIT.LIST_ROWS,
|
|
326
330
|
BUTTON_TITLE_MAX: WHATSAPP_CHOICE_LIMIT.BUTTON_TITLE_LENGTH,
|
|
331
|
+
LIST_BUTTON_LABEL_MAX: WHATSAPP_CHOICE_LIMIT.LIST_BUTTON_LABEL_LENGTH,
|
|
327
332
|
LIST_ROW_TITLE_MAX: WHATSAPP_CHOICE_LIMIT.LIST_ROW_TITLE_LENGTH,
|
|
328
333
|
LIST_ROW_DESCRIPTION_MAX: WHATSAPP_CHOICE_LIMIT.LIST_ROW_DESCRIPTION_LENGTH,
|
|
329
334
|
LIST_SECTION_TITLE_MAX: WHATSAPP_CHOICE_LIMIT.LIST_SECTION_TITLE_LENGTH,
|
|
@@ -332,6 +337,21 @@ var WHATSAPP_LIMITS = {
|
|
|
332
337
|
function countCharacters(text) {
|
|
333
338
|
return Array.from(text).length;
|
|
334
339
|
}
|
|
340
|
+
var PLACEHOLDER_PATTERN = /\{\{\s*([\w.]+)\s*\}\}/g;
|
|
341
|
+
function measureLabel(label, variableExamples = {}) {
|
|
342
|
+
let isApproximate = false;
|
|
343
|
+
const text = label.replace(PLACEHOLDER_PATTERN, (_placeholder, key) => {
|
|
344
|
+
const example = variableExamples[key];
|
|
345
|
+
if (example === void 0) isApproximate = true;
|
|
346
|
+
return example ?? "";
|
|
347
|
+
});
|
|
348
|
+
return { length: countCharacters(text), isApproximate };
|
|
349
|
+
}
|
|
350
|
+
function judgeLabel(label, max, variableExamples) {
|
|
351
|
+
const measured = measureLabel(label, variableExamples);
|
|
352
|
+
if (measured.length > max) return "too-long";
|
|
353
|
+
return measured.isApproximate && countCharacters(label) > max ? "may-be-too-long" : "ok";
|
|
354
|
+
}
|
|
335
355
|
function rendersAsButtons(options, optionDetails) {
|
|
336
356
|
const hasDetails = (options ?? []).some(
|
|
337
357
|
([id]) => !!optionDetails?.[id]?.description || !!optionDetails?.[id]?.section
|
|
@@ -351,7 +371,8 @@ function targetsOf(node) {
|
|
|
351
371
|
const possible = (node.possibleNext ?? []).map((target) => ({ target, isPossible: true }));
|
|
352
372
|
return [...nextTargetsOf(node), ...possible];
|
|
353
373
|
}
|
|
354
|
-
function validateGraph(graph, issueText) {
|
|
374
|
+
function validateGraph(graph, issueText, settings = {}) {
|
|
375
|
+
const examples = settings.variableExamples ?? {};
|
|
355
376
|
const issues = [];
|
|
356
377
|
const nodeIds = new Set(Object.keys(graph.nodes));
|
|
357
378
|
const isValidTarget = (target) => nodeIds.has(target) || isCrossFlowTarget(target);
|
|
@@ -381,11 +402,15 @@ function validateGraph(graph, issueText) {
|
|
|
381
402
|
issues.push({ severity: "warning", nodeId: node.id, message: issueText.optionWithoutTarget(node.id, label) });
|
|
382
403
|
}
|
|
383
404
|
const usesButtons = rendersAsButtons(options, node.optionDetails);
|
|
384
|
-
|
|
385
|
-
|
|
405
|
+
const titleMax = usesButtons ? WHATSAPP_LIMITS.BUTTON_TITLE_MAX : WHATSAPP_LIMITS.LIST_ROW_TITLE_MAX;
|
|
406
|
+
const titleVerdict = judgeLabel(label, titleMax, examples);
|
|
407
|
+
if (titleVerdict === "too-long") {
|
|
408
|
+
const tooLong = usesButtons ? issueText.buttonTitleTooLong : issueText.listTitleTooLong;
|
|
409
|
+
issues.push({ severity: "error", nodeId: node.id, message: tooLong(node.id, label) });
|
|
386
410
|
}
|
|
387
|
-
if (
|
|
388
|
-
|
|
411
|
+
if (titleVerdict === "may-be-too-long") {
|
|
412
|
+
const message = (usesButtons ? issueText.buttonTitleMayBeTooLong : issueText.listTitleMayBeTooLong)?.(node.id, label) ?? `N\xF3 "${node.id}": "${label}" tem vari\xE1vel e pode passar de ${titleMax} caracteres; confira o valor real.`;
|
|
413
|
+
issues.push({ severity: "warning", nodeId: node.id, message });
|
|
389
414
|
}
|
|
390
415
|
const description = node.optionDetails?.[optionId]?.description ?? "";
|
|
391
416
|
if (countCharacters(description) > WHATSAPP_LIMITS.LIST_ROW_DESCRIPTION_MAX) {
|
|
@@ -393,6 +418,16 @@ function validateGraph(graph, issueText) {
|
|
|
393
418
|
issues.push({ severity: "error", nodeId: node.id, message });
|
|
394
419
|
}
|
|
395
420
|
}
|
|
421
|
+
const listButtonLabel = node.listButtonLabel;
|
|
422
|
+
const listButtonVerdict = listButtonLabel ? judgeLabel(listButtonLabel, WHATSAPP_LIMITS.LIST_BUTTON_LABEL_MAX, examples) : "ok";
|
|
423
|
+
if (listButtonLabel && listButtonVerdict === "too-long") {
|
|
424
|
+
const message = issueText.listButtonLabelTooLong?.(node.id, listButtonLabel) ?? `N\xF3 "${node.id}": o bot\xE3o da lista "${listButtonLabel}" passa de ${WHATSAPP_LIMITS.LIST_BUTTON_LABEL_MAX} caracteres.`;
|
|
425
|
+
issues.push({ severity: "error", nodeId: node.id, message });
|
|
426
|
+
}
|
|
427
|
+
if (listButtonLabel && listButtonVerdict === "may-be-too-long") {
|
|
428
|
+
const message = issueText.listButtonLabelMayBeTooLong?.(node.id, listButtonLabel) ?? `N\xF3 "${node.id}": o bot\xE3o da lista "${listButtonLabel}" tem vari\xE1vel e pode passar de ${WHATSAPP_LIMITS.LIST_BUTTON_LABEL_MAX} caracteres; confira o valor real.`;
|
|
429
|
+
issues.push({ severity: "warning", nodeId: node.id, message });
|
|
430
|
+
}
|
|
396
431
|
const defaultTarget = typeof node.next === "object" && node.next ? node.next.default : "";
|
|
397
432
|
if (defaultTarget && defaultTarget !== node.id && node.unmatchedChoice !== "default") {
|
|
398
433
|
const message = issueText.choiceDefaultIgnored?.(node.id) ?? `N\xF3 "${node.id}": "caso contr\xE1rio" s\xF3 \xE9 seguido com "resposta fora das op\xE7\xF5es" = seguir o caso contr\xE1rio.`;
|
|
@@ -2705,6 +2740,7 @@ function FlowsWorkspace({
|
|
|
2705
2740
|
renderMediaPicker,
|
|
2706
2741
|
livePollIntervalMs = 5e3,
|
|
2707
2742
|
showHeader = true,
|
|
2743
|
+
variableExamples,
|
|
2708
2744
|
className
|
|
2709
2745
|
}) {
|
|
2710
2746
|
const labels = useMemo2(() => mergeFlowEditorLabels(labelsOverride), [labelsOverride]);
|
|
@@ -2796,10 +2832,10 @@ function FlowsWorkspace({
|
|
|
2796
2832
|
const map = {};
|
|
2797
2833
|
for (const key of openFlowKeys) {
|
|
2798
2834
|
const graph = workingGraphs[key];
|
|
2799
|
-
if (graph) map[key] = validateGraph(graph, labels.validation);
|
|
2835
|
+
if (graph) map[key] = validateGraph(graph, labels.validation, { variableExamples });
|
|
2800
2836
|
}
|
|
2801
2837
|
return map;
|
|
2802
|
-
}, [openFlowKeys, workingGraphs, labels]);
|
|
2838
|
+
}, [openFlowKeys, workingGraphs, labels, variableExamples]);
|
|
2803
2839
|
const errorCount = Object.values(issuesByFlow).reduce(
|
|
2804
2840
|
(sum, list) => sum + list.filter((issue) => issue.severity === "error").length,
|
|
2805
2841
|
0
|
|
@@ -3622,6 +3658,7 @@ export {
|
|
|
3622
3658
|
flowPortalNodeTypes,
|
|
3623
3659
|
isCrossFlowTarget,
|
|
3624
3660
|
isGraphDirty,
|
|
3661
|
+
measureLabel,
|
|
3625
3662
|
mergeFlowEditorLabels,
|
|
3626
3663
|
mergedFlowKeysFrom,
|
|
3627
3664
|
namespaceNodeId,
|
package/dist/index.d.ts
CHANGED
|
@@ -1963,6 +1963,49 @@ type QuickRepliesPickerProps = {
|
|
|
1963
1963
|
*/
|
|
1964
1964
|
declare function QuickRepliesPicker({ id, items, search, highlightedIndex, isLoading, hasError, onHover, onSelect, labels, className, ownSearch, variables, hasAttachmentsCapability, }: QuickRepliesPickerProps): react.JSX.Element;
|
|
1965
1965
|
|
|
1966
|
+
/**
|
|
1967
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
1968
|
+
*
|
|
1969
|
+
* Porta de respostas rápidas pronta para as rotas de `createMetaWhatsAppQuickReplyRoutes`
|
|
1970
|
+
* (`@adatechnology/meta-whatsapp-module`). O resultado se espalha em `ConversationsApi` e satisfaz
|
|
1971
|
+
* `QuickRepliesWorkspaceApi`; sem ele cada host reescrevia a mesma ponte — e errava o envelope.
|
|
1972
|
+
*
|
|
1973
|
+
* Só texto: anexos de resposta rápida não existem no módulo, então não há `uploadQuickReplyAttachment`
|
|
1974
|
+
* e as telas não oferecem a seção de anexos.
|
|
1975
|
+
*/
|
|
1976
|
+
|
|
1977
|
+
type CreateMetaWhatsAppQuickRepliesClientParams = {
|
|
1978
|
+
/** Onde o host montou as rotas, ex.: `/v1/whatsapp`. Sem barra no fim; `/quick-replies` é acrescentado. */
|
|
1979
|
+
readonly baseUrl: string;
|
|
1980
|
+
/** Cabeçalhos por requisição (o `Authorization` do host). Chamado a cada request. */
|
|
1981
|
+
readonly getHeaders?: () => Record<string, string> | Promise<Record<string, string>>;
|
|
1982
|
+
readonly fetch?: typeof fetch;
|
|
1983
|
+
};
|
|
1984
|
+
type MetaWhatsAppQuickRepliesClient = {
|
|
1985
|
+
readonly listQuickReplies: (params?: {
|
|
1986
|
+
search?: string;
|
|
1987
|
+
}) => Promise<QuickReply$1[]>;
|
|
1988
|
+
readonly createQuickReply: (input: QuickReplyInput) => Promise<QuickReply$1>;
|
|
1989
|
+
readonly updateQuickReply: (id: string, input: QuickReplyInput) => Promise<QuickReply$1>;
|
|
1990
|
+
readonly deleteQuickReply: (id: string) => Promise<void>;
|
|
1991
|
+
};
|
|
1992
|
+
type QuickRepliesApiErrorDetail = {
|
|
1993
|
+
readonly field: string;
|
|
1994
|
+
readonly message: string;
|
|
1995
|
+
};
|
|
1996
|
+
/**
|
|
1997
|
+
* Erro da API com `code` estável e `details` no formato que o `QuickRepliesWorkspace` lê
|
|
1998
|
+
* (`{ field, message }`): a validação do módulo devolve `issues[{ path, message }]`, traduzido aqui
|
|
1999
|
+
* para o erro aparecer no campo certo do formulário.
|
|
2000
|
+
*/
|
|
2001
|
+
declare class QuickRepliesApiError extends Error {
|
|
2002
|
+
readonly status: number;
|
|
2003
|
+
readonly code: string;
|
|
2004
|
+
readonly details: readonly QuickRepliesApiErrorDetail[];
|
|
2005
|
+
constructor(message: string, status: number, code: string, details?: readonly QuickRepliesApiErrorDetail[]);
|
|
2006
|
+
}
|
|
2007
|
+
declare function createMetaWhatsAppQuickRepliesClient(params: CreateMetaWhatsAppQuickRepliesClientParams): MetaWhatsAppQuickRepliesClient;
|
|
2008
|
+
|
|
1966
2009
|
declare function normalizeForSearch(value: string): string;
|
|
1967
2010
|
type FilterQuickRepliesParams = {
|
|
1968
2011
|
readonly quickReplies: readonly QuickReply$1[];
|
|
@@ -2353,4 +2396,4 @@ type QueuedAttachmentsListProps = {
|
|
|
2353
2396
|
};
|
|
2354
2397
|
declare function QueuedAttachmentsList({ items, statusOf, onRemove, onRetry, retryingKeys, getThumbnailUrl, labels, busy, }: QueuedAttachmentsListProps): react.JSX.Element | null;
|
|
2355
2398
|
|
|
2356
|
-
export { type AsyncResourceState, type AttachmentFileRejection, AudioPlayer, type AudioPlayerProps, AudioTranscription, type AudioTranscriptionProps, Avatar, type AvatarLabels, type AvatarProps, type BotMessages, type BuildTranscriptTextParams, BulkActionBar, type BulkActionBarProps, CHANNEL_BRAND_COLOR, CONVERSATIONS_PER_PAGE, CONVERSATION_WINDOW, ChannelFilter, ChannelFilterOption, ChannelIcon, type ChannelIconProps, ConversationChannel, type ConversationContextEntry, ConversationContextPanel, type ConversationContextPanelClassNames, type ConversationContextPanelLabels, type ConversationContextPanelProps, type ConversationContextStatus, ConversationDocument, ConversationDocumentsPanel, type ConversationDocumentsPanelClassNames, type ConversationDocumentsPanelLabels, type ConversationDocumentsPanelProps, ConversationHeader, type ConversationHeaderClassNames, type ConversationHeaderLabels, type ConversationHeaderProps, type ConversationHeaderUtility, ConversationListItem, type ConversationListItemLabels, type ConversationListItemProps, type ConversationLocales, ConversationLocalesProvider, type ConversationLocalesProviderProps, ConversationPane, type ConversationPaneProps, type ConversationRealtimeHandler, ConversationRow, type ConversationRowClassNames, type ConversationRowProps, ConversationSimulatorClient, ConversationSummary, ConversationTemplate, ConversationVariable, ConversationWallpaper, type ConversationWallpaperProps, type ConversationWindow, ConversationsApi, ConversationsFeatures, ConversationsInboxList, type ConversationsInboxListProps, ConversationsProvider, ConversationsWorkspace, type ConversationsWorkspaceLabels, type ConversationsWorkspaceProps, type ConversationsWorkspaceSimulator, DEFAULT_ACCEPTED_FILE_TYPES, DEFAULT_AVATAR_LABELS, DEFAULT_CONVERSATIONS_WORKSPACE_LABELS, DEFAULT_CONVERSATION_CONTEXT_LABELS, DEFAULT_CONVERSATION_DOCUMENTS_LABELS, DEFAULT_CONVERSATION_HEADER_LABELS, DEFAULT_CONVERSATION_LIST_ITEM_LABELS, DEFAULT_DARK_MODE_TOGGLE_LABELS, DEFAULT_DOCUMENTS_LIBRARY_LABELS, DEFAULT_DOCUMENTS_WORKSPACE_LABELS, DEFAULT_EMOJI_PICKER_LABELS, DEFAULT_INTERACTIVE_MESSAGE_LABELS, DEFAULT_LIGHTBOX_LABELS, DEFAULT_MAX_ATTACHMENT_SIZE_BYTES, DEFAULT_MAX_RECORDING_MILLISECONDS, DEFAULT_MESSAGE_COMPOSER_LABELS, DEFAULT_QUICK_REPLIES_PICKER_LABELS, DEFAULT_QUICK_REPLIES_WORKSPACE_LABELS, DEFAULT_RICH_COMPOSER_TOOLTIPS, DEFAULT_TEMPLATES_SETTINGS_LABELS, DEFAULT_WHATSAPP_MESSAGE_EDITOR_LABELS, DEFAULT_WINDOW_EXPIRED_LABELS, DOCUMENT_SOURCE_FILTER, DarkModeToggle, type DarkModeToggleLabels, type DarkModeToggleProps, DateDivider, type DateDividerClassNames, type DateDividerProps, type DocumentSourceFilter, type DocumentsFiltersContext, DocumentsLibrary, type DocumentsLibraryClassNames, type DocumentsLibraryLabels, type DocumentsLibraryProps, DocumentsWorkspace, type DocumentsWorkspaceClassNames, type DocumentsWorkspaceLabels, type DocumentsWorkspaceProps, EMOJI_CATEGORIES, type EmojiCategory, type EmojiEntry, EmojiPicker, type EmojiPickerLabels, type EmojiPickerProps, FileIcon, type FileIconProps, type FilterOption, type FilterQuickRepliesParams, InteractiveMessage, type InteractiveMessageLabels, type InteractiveMessageProps, InteractivePayload, InteractiveSelection, Lightbox, type LightboxLabels, type LightboxProps, ListConversationsParams, ListDocumentsParams, ListingPagination, type ListingPaginationProps, type MatchSegment, type MaxAttachmentSizeBytes, MessageBubble, type MessageBubbleProps, MessageComposer, type MessageComposerClassNames, type MessageComposerLabels, type MessageComposerProps, MessagePayload, MessageTail, MessageText, type MessageTextProps, MessageTimestamp, MessageTranscription, MessagesWorkspace, type MessagesWorkspaceApi, type MessagesWorkspaceLabels, type MessagesWorkspaceProps, type MessagesWorkspaceTemplateRole, MultiSelectFilter, type MultiSelectFilterProps, NARROW_MAX_WIDTH_PX, type OutgoingItems, QueuedAttachment, QueuedAttachmentsList, QuickRepliesPicker, type QuickRepliesPickerLabels, type QuickRepliesPickerProps, QuickRepliesWorkspace, type QuickRepliesWorkspaceLabels, type QuickRepliesWorkspaceProps, type QuickReply, QuickReplyAttachment, QuickReplyInput, REPLY_LATENCY, REPLY_LATENCY_CRITICAL_HOURS, REPLY_LATENCY_LATE_HOURS, RICH_COMPOSER_ACTION, type ReplyLatency, type ReplyLatencyParams, ResolveMediaUrl, type RichComposerAction, type RichComposerQuickReply, type RichComposerTooltips, type RichComposerVariable, RichMessageComposer, type RichMessageComposerHandle, type RichMessageComposerProps, SSEProvider, QuickReply$1 as SavedQuickReply, SimpleEmojiPicker, type SimpleEmojiPickerProps, type SimulatorTestContact, type SimulatorTransportFactory, type SimulatorTransportParams, type SortDirection, SortableHead, type SortableHeadProps, StatusTicks, type StatusTicksProps, TEMPLATE_SETTINGS_TAB, TEST_CONTACT_LABEL, TOOLTIP_ATTRIBUTE, type TemplateSettings, type TemplateSettingsTab, ToastProvider, TooltipLayer, type TopicItem, TopicsForm, type TopicsFormLabels, type TopicsFormProps, TranscriptionMode, type TranscriptionSettings, TranscriptionSettingsForm, type TranscriptionSettingsFormLabels, type TranscriptionSettingsFormProps, type UrlStateOptions, type UseConversationActionsResult, type UseConversationContextResult, type UseConversationDocumentsParams, type UseConversationDocumentsResult, type UseConversationListParams, type UseConversationListResult, type UseConversationMessagesResult, type UseConversationsInboxParams, type UseConversationsInboxResult, type UseInboxActionsResult, type UseScrollToLatestMessageParams, type UseScrollToLatestMessageResult, type UseWaitingNotificationsLabels, type UseWaitingNotificationsParams, type UseWaitingNotificationsResult, type ValidateAttachmentFilesResult, WHATSAPP_MARKER_BY_ACTION, WINDOW_FILTERS, WelcomeFarewellForm, type WelcomeFarewellFormLabels, type WelcomeFarewellFormProps, WhatsAppCreateTemplateForm, type WhatsAppCreateTemplateFormLabels, type WhatsAppCreateTemplateFormProps, type WhatsAppCreateTemplateResult, type WhatsAppCreateTemplateState, WhatsAppMessageEditor, type WhatsAppMessageEditorLabels, type WhatsAppMessageEditorProps, WhatsAppMessagePreview, type WhatsAppMessagePreviewProps, type WhatsAppTemplateHeaderType, WhatsAppTemplateSettingsForm, type WhatsAppTemplateSettingsFormLabels, type WhatsAppTemplateSettingsFormProps, type WhatsAppTemplateSummary, type WhatsAppTemplateVariableSuggestion, WhatsAppTemplatesSettings, type WhatsAppTemplatesSettingsLabels, type WhatsAppTemplatesSettingsProps, WindowExpiredNotice, type WindowExpiredNoticeLabels, type WindowExpiredNoticeProps, type WindowOfParams, applyQuickReplyVariables, buildTranscriptFilename, buildTranscriptText, channelCapabilityFor, createMediaUrlResolver, downloadTextFile, filterQuickReplies, formatDateTime, formatFileSize, formatPhone, formatStalledFor, formatTimestamp, highlightMatch, htmlToWA, isReplyOverdue, isSameDay, isTestContactNumber, isWindowBlocking, normalizeForSearch, parseWhatsAppFormatting, phoneInitials, queuedAttachmentsFromQuickReply, replyLatencyOf, resolveMaxAttachmentSizeBytes, resolveQuickReply, searchEmojis, toast, useConversationActions, useConversationContext, useConversationDocuments, useConversationList, useConversationLocales, useConversationMessages, useConversationRealtime, useConversations, useConversationsInbox, useDarkMode, useDebouncedValue, useGlobalRealtime, useInboxActions, useIsDarkTheme, useIsNarrow, useScrollToLatestMessage, useToast, useUrlArrayState, useUrlNumberState, useUrlStringState, useWaitingNotifications, waToHTML, waToHTMLInline, windowOf };
|
|
2399
|
+
export { type AsyncResourceState, type AttachmentFileRejection, AudioPlayer, type AudioPlayerProps, AudioTranscription, type AudioTranscriptionProps, Avatar, type AvatarLabels, type AvatarProps, type BotMessages, type BuildTranscriptTextParams, BulkActionBar, type BulkActionBarProps, CHANNEL_BRAND_COLOR, CONVERSATIONS_PER_PAGE, CONVERSATION_WINDOW, ChannelFilter, ChannelFilterOption, ChannelIcon, type ChannelIconProps, ConversationChannel, type ConversationContextEntry, ConversationContextPanel, type ConversationContextPanelClassNames, type ConversationContextPanelLabels, type ConversationContextPanelProps, type ConversationContextStatus, ConversationDocument, ConversationDocumentsPanel, type ConversationDocumentsPanelClassNames, type ConversationDocumentsPanelLabels, type ConversationDocumentsPanelProps, ConversationHeader, type ConversationHeaderClassNames, type ConversationHeaderLabels, type ConversationHeaderProps, type ConversationHeaderUtility, ConversationListItem, type ConversationListItemLabels, type ConversationListItemProps, type ConversationLocales, ConversationLocalesProvider, type ConversationLocalesProviderProps, ConversationPane, type ConversationPaneProps, type ConversationRealtimeHandler, ConversationRow, type ConversationRowClassNames, type ConversationRowProps, ConversationSimulatorClient, ConversationSummary, ConversationTemplate, ConversationVariable, ConversationWallpaper, type ConversationWallpaperProps, type ConversationWindow, ConversationsApi, ConversationsFeatures, ConversationsInboxList, type ConversationsInboxListProps, ConversationsProvider, ConversationsWorkspace, type ConversationsWorkspaceLabels, type ConversationsWorkspaceProps, type ConversationsWorkspaceSimulator, type CreateMetaWhatsAppQuickRepliesClientParams, DEFAULT_ACCEPTED_FILE_TYPES, DEFAULT_AVATAR_LABELS, DEFAULT_CONVERSATIONS_WORKSPACE_LABELS, DEFAULT_CONVERSATION_CONTEXT_LABELS, DEFAULT_CONVERSATION_DOCUMENTS_LABELS, DEFAULT_CONVERSATION_HEADER_LABELS, DEFAULT_CONVERSATION_LIST_ITEM_LABELS, DEFAULT_DARK_MODE_TOGGLE_LABELS, DEFAULT_DOCUMENTS_LIBRARY_LABELS, DEFAULT_DOCUMENTS_WORKSPACE_LABELS, DEFAULT_EMOJI_PICKER_LABELS, DEFAULT_INTERACTIVE_MESSAGE_LABELS, DEFAULT_LIGHTBOX_LABELS, DEFAULT_MAX_ATTACHMENT_SIZE_BYTES, DEFAULT_MAX_RECORDING_MILLISECONDS, DEFAULT_MESSAGE_COMPOSER_LABELS, DEFAULT_QUICK_REPLIES_PICKER_LABELS, DEFAULT_QUICK_REPLIES_WORKSPACE_LABELS, DEFAULT_RICH_COMPOSER_TOOLTIPS, DEFAULT_TEMPLATES_SETTINGS_LABELS, DEFAULT_WHATSAPP_MESSAGE_EDITOR_LABELS, DEFAULT_WINDOW_EXPIRED_LABELS, DOCUMENT_SOURCE_FILTER, DarkModeToggle, type DarkModeToggleLabels, type DarkModeToggleProps, DateDivider, type DateDividerClassNames, type DateDividerProps, type DocumentSourceFilter, type DocumentsFiltersContext, DocumentsLibrary, type DocumentsLibraryClassNames, type DocumentsLibraryLabels, type DocumentsLibraryProps, DocumentsWorkspace, type DocumentsWorkspaceClassNames, type DocumentsWorkspaceLabels, type DocumentsWorkspaceProps, EMOJI_CATEGORIES, type EmojiCategory, type EmojiEntry, EmojiPicker, type EmojiPickerLabels, type EmojiPickerProps, FileIcon, type FileIconProps, type FilterOption, type FilterQuickRepliesParams, InteractiveMessage, type InteractiveMessageLabels, type InteractiveMessageProps, InteractivePayload, InteractiveSelection, Lightbox, type LightboxLabels, type LightboxProps, ListConversationsParams, ListDocumentsParams, ListingPagination, type ListingPaginationProps, type MatchSegment, type MaxAttachmentSizeBytes, MessageBubble, type MessageBubbleProps, MessageComposer, type MessageComposerClassNames, type MessageComposerLabels, type MessageComposerProps, MessagePayload, MessageTail, MessageText, type MessageTextProps, MessageTimestamp, MessageTranscription, MessagesWorkspace, type MessagesWorkspaceApi, type MessagesWorkspaceLabels, type MessagesWorkspaceProps, type MessagesWorkspaceTemplateRole, type MetaWhatsAppQuickRepliesClient, MultiSelectFilter, type MultiSelectFilterProps, NARROW_MAX_WIDTH_PX, type OutgoingItems, QueuedAttachment, QueuedAttachmentsList, QuickRepliesApiError, type QuickRepliesApiErrorDetail, QuickRepliesPicker, type QuickRepliesPickerLabels, type QuickRepliesPickerProps, QuickRepliesWorkspace, type QuickRepliesWorkspaceLabels, type QuickRepliesWorkspaceProps, type QuickReply, QuickReplyAttachment, QuickReplyInput, REPLY_LATENCY, REPLY_LATENCY_CRITICAL_HOURS, REPLY_LATENCY_LATE_HOURS, RICH_COMPOSER_ACTION, type ReplyLatency, type ReplyLatencyParams, ResolveMediaUrl, type RichComposerAction, type RichComposerQuickReply, type RichComposerTooltips, type RichComposerVariable, RichMessageComposer, type RichMessageComposerHandle, type RichMessageComposerProps, SSEProvider, QuickReply$1 as SavedQuickReply, SimpleEmojiPicker, type SimpleEmojiPickerProps, type SimulatorTestContact, type SimulatorTransportFactory, type SimulatorTransportParams, type SortDirection, SortableHead, type SortableHeadProps, StatusTicks, type StatusTicksProps, TEMPLATE_SETTINGS_TAB, TEST_CONTACT_LABEL, TOOLTIP_ATTRIBUTE, type TemplateSettings, type TemplateSettingsTab, ToastProvider, TooltipLayer, type TopicItem, TopicsForm, type TopicsFormLabels, type TopicsFormProps, TranscriptionMode, type TranscriptionSettings, TranscriptionSettingsForm, type TranscriptionSettingsFormLabels, type TranscriptionSettingsFormProps, type UrlStateOptions, type UseConversationActionsResult, type UseConversationContextResult, type UseConversationDocumentsParams, type UseConversationDocumentsResult, type UseConversationListParams, type UseConversationListResult, type UseConversationMessagesResult, type UseConversationsInboxParams, type UseConversationsInboxResult, type UseInboxActionsResult, type UseScrollToLatestMessageParams, type UseScrollToLatestMessageResult, type UseWaitingNotificationsLabels, type UseWaitingNotificationsParams, type UseWaitingNotificationsResult, type ValidateAttachmentFilesResult, WHATSAPP_MARKER_BY_ACTION, WINDOW_FILTERS, WelcomeFarewellForm, type WelcomeFarewellFormLabels, type WelcomeFarewellFormProps, WhatsAppCreateTemplateForm, type WhatsAppCreateTemplateFormLabels, type WhatsAppCreateTemplateFormProps, type WhatsAppCreateTemplateResult, type WhatsAppCreateTemplateState, WhatsAppMessageEditor, type WhatsAppMessageEditorLabels, type WhatsAppMessageEditorProps, WhatsAppMessagePreview, type WhatsAppMessagePreviewProps, type WhatsAppTemplateHeaderType, WhatsAppTemplateSettingsForm, type WhatsAppTemplateSettingsFormLabels, type WhatsAppTemplateSettingsFormProps, type WhatsAppTemplateSummary, type WhatsAppTemplateVariableSuggestion, WhatsAppTemplatesSettings, type WhatsAppTemplatesSettingsLabels, type WhatsAppTemplatesSettingsProps, WindowExpiredNotice, type WindowExpiredNoticeLabels, type WindowExpiredNoticeProps, type WindowOfParams, applyQuickReplyVariables, buildTranscriptFilename, buildTranscriptText, channelCapabilityFor, createMediaUrlResolver, createMetaWhatsAppQuickRepliesClient, downloadTextFile, filterQuickReplies, formatDateTime, formatFileSize, formatPhone, formatStalledFor, formatTimestamp, highlightMatch, htmlToWA, isReplyOverdue, isSameDay, isTestContactNumber, isWindowBlocking, normalizeForSearch, parseWhatsAppFormatting, phoneInitials, queuedAttachmentsFromQuickReply, replyLatencyOf, resolveMaxAttachmentSizeBytes, resolveQuickReply, searchEmojis, toast, useConversationActions, useConversationContext, useConversationDocuments, useConversationList, useConversationLocales, useConversationMessages, useConversationRealtime, useConversations, useConversationsInbox, useDarkMode, useDebouncedValue, useGlobalRealtime, useInboxActions, useIsDarkTheme, useIsNarrow, useScrollToLatestMessage, useToast, useUrlArrayState, useUrlNumberState, useUrlStringState, useWaitingNotifications, waToHTML, waToHTMLInline, windowOf };
|
package/dist/index.js
CHANGED
|
@@ -5555,6 +5555,64 @@ function QuickRepliesWorkspace({
|
|
|
5555
5555
|
] });
|
|
5556
5556
|
}
|
|
5557
5557
|
|
|
5558
|
+
// src/quickReplies/createMetaWhatsAppQuickRepliesClient.ts
|
|
5559
|
+
var QuickRepliesApiError = class extends Error {
|
|
5560
|
+
constructor(message, status, code, details = []) {
|
|
5561
|
+
super(message);
|
|
5562
|
+
this.status = status;
|
|
5563
|
+
this.code = code;
|
|
5564
|
+
this.details = details;
|
|
5565
|
+
this.name = "QuickRepliesApiError";
|
|
5566
|
+
}
|
|
5567
|
+
};
|
|
5568
|
+
async function toApiError(response) {
|
|
5569
|
+
const body = await response.json().catch(() => void 0);
|
|
5570
|
+
const details = (body?.error?.issues ?? []).flatMap(
|
|
5571
|
+
(issue) => issue.path && issue.message ? [{ field: issue.path, message: issue.message }] : []
|
|
5572
|
+
);
|
|
5573
|
+
return new QuickRepliesApiError(
|
|
5574
|
+
body?.error?.message ?? `Falha na API de respostas r\xE1pidas (${response.status})`,
|
|
5575
|
+
response.status,
|
|
5576
|
+
body?.error?.code ?? "HTTP_ERROR",
|
|
5577
|
+
details
|
|
5578
|
+
);
|
|
5579
|
+
}
|
|
5580
|
+
function toBody(input) {
|
|
5581
|
+
return { title: input.title, shortcut: input.shortcut, body: input.body };
|
|
5582
|
+
}
|
|
5583
|
+
function createMetaWhatsAppQuickRepliesClient(params) {
|
|
5584
|
+
const fetchImpl = params.fetch ?? globalThis.fetch.bind(globalThis);
|
|
5585
|
+
const collectionUrl = `${params.baseUrl}/quick-replies`;
|
|
5586
|
+
async function request(url, method, json) {
|
|
5587
|
+
const headers = { ...await params.getHeaders?.() };
|
|
5588
|
+
if (json !== void 0) headers["content-type"] = "application/json";
|
|
5589
|
+
const response = await fetchImpl(url, {
|
|
5590
|
+
method,
|
|
5591
|
+
headers,
|
|
5592
|
+
...json === void 0 ? {} : { body: JSON.stringify(json) }
|
|
5593
|
+
});
|
|
5594
|
+
if (!response.ok) throw await toApiError(response);
|
|
5595
|
+
return response;
|
|
5596
|
+
}
|
|
5597
|
+
async function requestData(url, method, json) {
|
|
5598
|
+
const response = await request(url, method, json);
|
|
5599
|
+
return (await response.json()).data;
|
|
5600
|
+
}
|
|
5601
|
+
const itemUrl = (id) => `${collectionUrl}/${encodeURIComponent(id)}`;
|
|
5602
|
+
return {
|
|
5603
|
+
listQuickReplies: (listParams) => {
|
|
5604
|
+
const search = listParams?.search?.trim();
|
|
5605
|
+
const query = search ? `?${new URLSearchParams({ search }).toString()}` : "";
|
|
5606
|
+
return requestData(`${collectionUrl}${query}`, "GET");
|
|
5607
|
+
},
|
|
5608
|
+
createQuickReply: (input) => requestData(collectionUrl, "POST", toBody(input)),
|
|
5609
|
+
updateQuickReply: (id, input) => requestData(itemUrl(id), "PUT", toBody(input)),
|
|
5610
|
+
deleteQuickReply: async (id) => {
|
|
5611
|
+
await request(itemUrl(id), "DELETE");
|
|
5612
|
+
}
|
|
5613
|
+
};
|
|
5614
|
+
}
|
|
5615
|
+
|
|
5558
5616
|
// src/workspace/ConversationsWorkspace.tsx
|
|
5559
5617
|
import { useEffect as useEffect20, useMemo as useMemo7, useState as useState26 } from "react";
|
|
5560
5618
|
import { Check as Check2, CheckCheck, FlaskConical, Hourglass as Hourglass2, Mail as Mail2, MessagesSquare, UserPlus } from "lucide-react";
|
|
@@ -7221,6 +7279,7 @@ export {
|
|
|
7221
7279
|
NARROW_MAX_WIDTH_PX,
|
|
7222
7280
|
QUICK_REPLY_ATTACHMENT_LIMIT,
|
|
7223
7281
|
QueuedAttachmentsList,
|
|
7282
|
+
QuickRepliesApiError,
|
|
7224
7283
|
QuickRepliesPicker,
|
|
7225
7284
|
QuickRepliesWorkspace,
|
|
7226
7285
|
REOPEN_MECHANISM,
|
|
@@ -7256,6 +7315,7 @@ export {
|
|
|
7256
7315
|
channelFiltersFor,
|
|
7257
7316
|
contactFlag,
|
|
7258
7317
|
createMediaUrlResolver,
|
|
7318
|
+
createMetaWhatsAppQuickRepliesClient,
|
|
7259
7319
|
downloadTextFile,
|
|
7260
7320
|
filterQuickReplies,
|
|
7261
7321
|
formatContactHandle,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adatechnology/conversations-ui",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.1",
|
|
4
4
|
"description": "WhatsApp conversation UI components — parametrizável por endpoint, tema e feature flags",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
"lucide-react": "^1.21.0",
|
|
37
37
|
"tailwind-merge": "^3.6.0",
|
|
38
38
|
"@adatechnology/conversation-contracts": "0.7.0",
|
|
39
|
-
"@adatechnology/meta-whatsapp-contracts": "0.
|
|
39
|
+
"@adatechnology/meta-whatsapp-contracts": "0.11.0"
|
|
40
40
|
},
|
|
41
41
|
"peerDependencies": {
|
|
42
42
|
"@xyflow/react": "^12",
|
|
@@ -171,6 +171,11 @@ export interface FlowsWorkspaceProps {
|
|
|
171
171
|
* pacote a adivinhar a escala tipográfica de cada produto.
|
|
172
172
|
*/
|
|
173
173
|
readonly showHeader?: boolean
|
|
174
|
+
/**
|
|
175
|
+
* Valor de exemplo por variável usada em rótulo de botão e linha de lista (`{ buttonName: 'Pernoite' }`).
|
|
176
|
+
* Com exemplo, o validador mede o texto interpolado; sem, só avisa quando a marcação escrita passa do limite.
|
|
177
|
+
*/
|
|
178
|
+
readonly variableExamples?: Readonly<Record<string, string>>
|
|
174
179
|
readonly className?: string
|
|
175
180
|
}
|
|
176
181
|
|
|
@@ -245,6 +250,7 @@ export function FlowsWorkspace({
|
|
|
245
250
|
renderMediaPicker,
|
|
246
251
|
livePollIntervalMs = 5000,
|
|
247
252
|
showHeader = true,
|
|
253
|
+
variableExamples,
|
|
248
254
|
className,
|
|
249
255
|
}: FlowsWorkspaceProps) {
|
|
250
256
|
const labels = useMemo(() => mergeFlowEditorLabels(labelsOverride), [labelsOverride])
|
|
@@ -358,10 +364,10 @@ export function FlowsWorkspace({
|
|
|
358
364
|
const map: Record<string, GraphIssue[]> = {}
|
|
359
365
|
for (const key of openFlowKeys) {
|
|
360
366
|
const graph = workingGraphs[key]
|
|
361
|
-
if (graph) map[key] = validateGraph(graph, labels.validation)
|
|
367
|
+
if (graph) map[key] = validateGraph(graph, labels.validation, { variableExamples })
|
|
362
368
|
}
|
|
363
369
|
return map
|
|
364
|
-
}, [openFlowKeys, workingGraphs, labels])
|
|
370
|
+
}, [openFlowKeys, workingGraphs, labels, variableExamples])
|
|
365
371
|
|
|
366
372
|
const errorCount = Object.values(issuesByFlow).reduce(
|
|
367
373
|
(sum, list) => sum + list.filter((issue) => issue.severity === 'error').length,
|
package/src/flows/flowGraph.ts
CHANGED
|
@@ -118,6 +118,7 @@ export const WHATSAPP_LIMITS = {
|
|
|
118
118
|
MAX_BUTTONS: WHATSAPP_CHOICE_LIMIT.BUTTONS,
|
|
119
119
|
MAX_LIST_ROWS: WHATSAPP_CHOICE_LIMIT.LIST_ROWS,
|
|
120
120
|
BUTTON_TITLE_MAX: WHATSAPP_CHOICE_LIMIT.BUTTON_TITLE_LENGTH,
|
|
121
|
+
LIST_BUTTON_LABEL_MAX: WHATSAPP_CHOICE_LIMIT.LIST_BUTTON_LABEL_LENGTH,
|
|
121
122
|
LIST_ROW_TITLE_MAX: WHATSAPP_CHOICE_LIMIT.LIST_ROW_TITLE_LENGTH,
|
|
122
123
|
LIST_ROW_DESCRIPTION_MAX: WHATSAPP_CHOICE_LIMIT.LIST_ROW_DESCRIPTION_LENGTH,
|
|
123
124
|
LIST_SECTION_TITLE_MAX: WHATSAPP_CHOICE_LIMIT.LIST_SECTION_TITLE_LENGTH,
|
|
@@ -129,6 +130,44 @@ export function countCharacters(text: string): number {
|
|
|
129
130
|
return Array.from(text).length
|
|
130
131
|
}
|
|
131
132
|
|
|
133
|
+
const PLACEHOLDER_PATTERN = /\{\{\s*([\w.]+)\s*\}\}/g
|
|
134
|
+
|
|
135
|
+
export type MeasuredLabel = {
|
|
136
|
+
/** Caracteres do texto como o cliente o leria; sem exemplo para uma variável, ela vale 0 (mínimo certo). */
|
|
137
|
+
readonly length: number
|
|
138
|
+
/** `true` quando alguma `{{variável}}` ficou sem exemplo: o tamanho real só se sabe em tempo de execução. */
|
|
139
|
+
readonly isApproximate: boolean
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Mede um rótulo com `{{variável}}` sobre o texto interpolado com o exemplo da variável. Sem exemplo,
|
|
144
|
+
* mede o texto sem ela — contar a marcação escrita daria erro falso (`{{nome}}` vale 8 e a variável
|
|
145
|
+
* real pode ter 4).
|
|
146
|
+
*/
|
|
147
|
+
export function measureLabel(label: string, variableExamples: Readonly<Record<string, string>> = {}): MeasuredLabel {
|
|
148
|
+
let isApproximate = false
|
|
149
|
+
const text = label.replace(PLACEHOLDER_PATTERN, (_placeholder, key: string) => {
|
|
150
|
+
const example = variableExamples[key]
|
|
151
|
+
if (example === undefined) isApproximate = true
|
|
152
|
+
return example ?? ''
|
|
153
|
+
})
|
|
154
|
+
return { length: countCharacters(text), isApproximate }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
type LabelVerdict = 'ok' | 'too-long' | 'may-be-too-long'
|
|
158
|
+
|
|
159
|
+
/** Erro só quando o mínimo certo já passa do teto; aviso quando só a marcação escrita passa e a variável não tem exemplo. */
|
|
160
|
+
function judgeLabel(label: string, max: number, variableExamples: Readonly<Record<string, string>>): LabelVerdict {
|
|
161
|
+
const measured = measureLabel(label, variableExamples)
|
|
162
|
+
if (measured.length > max) return 'too-long'
|
|
163
|
+
return measured.isApproximate && countCharacters(label) > max ? 'may-be-too-long' : 'ok'
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export type ValidateGraphOptions = {
|
|
167
|
+
/** Valor de exemplo por variável (`{ buttonName: 'Pernoite' }`), usado para medir rótulos de botão e linha de lista. */
|
|
168
|
+
readonly variableExamples?: Readonly<Record<string, string>>
|
|
169
|
+
}
|
|
170
|
+
|
|
132
171
|
/**
|
|
133
172
|
* Botão com até 3 opções simples; opção com descrição ou seção força lista — é a mesma regra do
|
|
134
173
|
* runner do módulo, para a prévia mostrar o que o cliente vai ver.
|
|
@@ -196,8 +235,14 @@ export function validateGraph(
|
|
|
196
235
|
dynamicChoiceWithoutProvider?: (id: string) => string
|
|
197
236
|
choiceDefaultIgnored?: (id: string) => string
|
|
198
237
|
possibleNextIgnored?: (id: string) => string
|
|
238
|
+
buttonTitleMayBeTooLong?: (id: string, label: string) => string
|
|
239
|
+
listTitleMayBeTooLong?: (id: string, label: string) => string
|
|
240
|
+
listButtonLabelTooLong?: (id: string, label: string) => string
|
|
241
|
+
listButtonLabelMayBeTooLong?: (id: string, label: string) => string
|
|
199
242
|
},
|
|
243
|
+
settings: ValidateGraphOptions = {},
|
|
200
244
|
): GraphIssue[] {
|
|
245
|
+
const examples = settings.variableExamples ?? {}
|
|
201
246
|
const issues: GraphIssue[] = []
|
|
202
247
|
const nodeIds = new Set(Object.keys(graph.nodes))
|
|
203
248
|
const isValidTarget = (target: string) => nodeIds.has(target) || isCrossFlowTarget(target)
|
|
@@ -230,11 +275,17 @@ export function validateGraph(
|
|
|
230
275
|
issues.push({ severity: 'warning', nodeId: node.id, message: issueText.optionWithoutTarget(node.id, label) })
|
|
231
276
|
}
|
|
232
277
|
const usesButtons = rendersAsButtons(options, node.optionDetails)
|
|
233
|
-
|
|
234
|
-
|
|
278
|
+
const titleMax = usesButtons ? WHATSAPP_LIMITS.BUTTON_TITLE_MAX : WHATSAPP_LIMITS.LIST_ROW_TITLE_MAX
|
|
279
|
+
const titleVerdict = judgeLabel(label, titleMax, examples)
|
|
280
|
+
if (titleVerdict === 'too-long') {
|
|
281
|
+
const tooLong = usesButtons ? issueText.buttonTitleTooLong : issueText.listTitleTooLong
|
|
282
|
+
issues.push({ severity: 'error', nodeId: node.id, message: tooLong(node.id, label) })
|
|
235
283
|
}
|
|
236
|
-
if (
|
|
237
|
-
|
|
284
|
+
if (titleVerdict === 'may-be-too-long') {
|
|
285
|
+
const message =
|
|
286
|
+
(usesButtons ? issueText.buttonTitleMayBeTooLong : issueText.listTitleMayBeTooLong)?.(node.id, label) ??
|
|
287
|
+
`Nó "${node.id}": "${label}" tem variável e pode passar de ${titleMax} caracteres; confira o valor real.`
|
|
288
|
+
issues.push({ severity: 'warning', nodeId: node.id, message })
|
|
238
289
|
}
|
|
239
290
|
const description = node.optionDetails?.[optionId]?.description ?? ''
|
|
240
291
|
if (countCharacters(description) > WHATSAPP_LIMITS.LIST_ROW_DESCRIPTION_MAX) {
|
|
@@ -244,6 +295,22 @@ export function validateGraph(
|
|
|
244
295
|
issues.push({ severity: 'error', nodeId: node.id, message })
|
|
245
296
|
}
|
|
246
297
|
}
|
|
298
|
+
const listButtonLabel = node.listButtonLabel
|
|
299
|
+
const listButtonVerdict = listButtonLabel
|
|
300
|
+
? judgeLabel(listButtonLabel, WHATSAPP_LIMITS.LIST_BUTTON_LABEL_MAX, examples)
|
|
301
|
+
: 'ok'
|
|
302
|
+
if (listButtonLabel && listButtonVerdict === 'too-long') {
|
|
303
|
+
const message =
|
|
304
|
+
issueText.listButtonLabelTooLong?.(node.id, listButtonLabel) ??
|
|
305
|
+
`Nó "${node.id}": o botão da lista "${listButtonLabel}" passa de ${WHATSAPP_LIMITS.LIST_BUTTON_LABEL_MAX} caracteres.`
|
|
306
|
+
issues.push({ severity: 'error', nodeId: node.id, message })
|
|
307
|
+
}
|
|
308
|
+
if (listButtonLabel && listButtonVerdict === 'may-be-too-long') {
|
|
309
|
+
const message =
|
|
310
|
+
issueText.listButtonLabelMayBeTooLong?.(node.id, listButtonLabel) ??
|
|
311
|
+
`Nó "${node.id}": o botão da lista "${listButtonLabel}" tem variável e pode passar de ${WHATSAPP_LIMITS.LIST_BUTTON_LABEL_MAX} caracteres; confira o valor real.`
|
|
312
|
+
issues.push({ severity: 'warning', nodeId: node.id, message })
|
|
313
|
+
}
|
|
247
314
|
// Com o runner em `reask` (padrão), resposta fora das opções repergunta: um "caso contrário"
|
|
248
315
|
// apontando para outro nó nunca seria seguido. Aviso, não erro — o host pode ligar `default`.
|
|
249
316
|
const defaultTarget = typeof node.next === 'object' && node.next ? node.next.default : ''
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
3
|
+
*
|
|
4
|
+
* Rótulo de botão/linha com `{{variável}}`: o validador mede o texto interpolado, não a marcação.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { describe, expect, it } from 'bun:test'
|
|
8
|
+
import { validateGraph, measureLabel, type FlowGraphData } from './flowGraph'
|
|
9
|
+
import { DEFAULT_FLOW_EDITOR_LABELS } from './labels'
|
|
10
|
+
|
|
11
|
+
function menuGraph(label: string, extra: Record<string, unknown> = {}): FlowGraphData {
|
|
12
|
+
return {
|
|
13
|
+
key: 'main',
|
|
14
|
+
label: 'Main',
|
|
15
|
+
version: 1,
|
|
16
|
+
startNodeId: 'menu',
|
|
17
|
+
nodes: {
|
|
18
|
+
menu: {
|
|
19
|
+
id: 'menu',
|
|
20
|
+
type: 'menu',
|
|
21
|
+
question: 'Escolha',
|
|
22
|
+
options: [['a', label]],
|
|
23
|
+
next: { byAnswer: { a: 'menu' }, default: 'menu' },
|
|
24
|
+
...extra,
|
|
25
|
+
},
|
|
26
|
+
},
|
|
27
|
+
} as FlowGraphData
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const validate = (graph: FlowGraphData, variableExamples?: Record<string, string>) =>
|
|
31
|
+
validateGraph(graph, DEFAULT_FLOW_EDITOR_LABELS.validation, variableExamples ? { variableExamples } : {})
|
|
32
|
+
|
|
33
|
+
describe('measureLabel', () => {
|
|
34
|
+
it('measures the interpolated example, not the marker', () => {
|
|
35
|
+
expect(measureLabel('✅ {{buttonName}}', { buttonName: 'Pernoite' })).toEqual({ length: 10, isApproximate: false })
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it('counts a variable without example as zero and flags the measure as approximate', () => {
|
|
39
|
+
expect(measureLabel('✅ {{buttonName}}')).toEqual({ length: 2, isApproximate: true })
|
|
40
|
+
})
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
describe('validateGraph — labels with variables', () => {
|
|
44
|
+
const LONG_MARKER = '✅ {{nameButtonTitle}}'
|
|
45
|
+
|
|
46
|
+
it('does not error on a long marker without example; it warns', () => {
|
|
47
|
+
const issues = validate(menuGraph(LONG_MARKER))
|
|
48
|
+
expect(issues.filter((issue) => issue.severity === 'error')).toEqual([])
|
|
49
|
+
expect(issues.some((issue) => issue.severity === 'warning' && issue.message.includes('pode passar de 20'))).toBe(
|
|
50
|
+
true,
|
|
51
|
+
)
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
it('passes silently when the example fits', () => {
|
|
55
|
+
expect(validate(menuGraph(LONG_MARKER), { nameButtonTitle: 'Pernoite' })).toEqual([])
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('errors when the example does not fit the button limit', () => {
|
|
59
|
+
const issues = validate(menuGraph(LONG_MARKER), { nameButtonTitle: 'Pacote de fim de semana inteiro' })
|
|
60
|
+
expect(issues.map((issue) => issue.severity)).toEqual(['error'])
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
it('errors when the fixed part alone passes the limit', () => {
|
|
64
|
+
const issues = validate(menuGraph('Texto fixo bem comprido demais {{x}}'))
|
|
65
|
+
expect(issues.map((issue) => issue.severity)).toEqual(['error'])
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
it('keeps the strict check for labels without variables', () => {
|
|
69
|
+
const issues = validate(menuGraph('Um rótulo comprido demais para botão'))
|
|
70
|
+
expect(issues.map((issue) => issue.severity)).toEqual(['error'])
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('uses the list row limit (24) when the node renders a list', () => {
|
|
74
|
+
const graph = menuGraph('{{unitName}} 12345678901234', { optionDetails: { a: { description: 'x' } } })
|
|
75
|
+
expect(validate(graph, { unitName: 'Centro' }).filter((issue) => issue.severity === 'error')).toEqual([])
|
|
76
|
+
expect(validate(graph, { unitName: 'Unidade Centro' }).map((issue) => issue.severity)).toEqual(['error'])
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
it('validates the list button label the same way', () => {
|
|
80
|
+
expect(validate(menuGraph('A', { listButtonLabel: 'Horários {{unit}}' })).map((issue) => issue.severity)).toEqual(
|
|
81
|
+
[],
|
|
82
|
+
)
|
|
83
|
+
expect(
|
|
84
|
+
validate(menuGraph('A', { listButtonLabel: 'Horários {{unit}}' }), { unit: 'Unidade Centro' }).map(
|
|
85
|
+
(issue) => issue.severity,
|
|
86
|
+
),
|
|
87
|
+
).toEqual(['error'])
|
|
88
|
+
expect(
|
|
89
|
+
validate(menuGraph('A', { listButtonLabel: 'Ver todos os horários disponíveis' })).map((i) => i.severity),
|
|
90
|
+
).toEqual(['error'])
|
|
91
|
+
})
|
|
92
|
+
})
|
package/src/flows/index.ts
CHANGED
|
@@ -28,6 +28,7 @@ export {
|
|
|
28
28
|
rendersAsButtons,
|
|
29
29
|
targetsOf,
|
|
30
30
|
validateGraph,
|
|
31
|
+
measureLabel,
|
|
31
32
|
computeAutoLayout,
|
|
32
33
|
crossFlowTargetsOf,
|
|
33
34
|
computeFlowMapLayout,
|
|
@@ -44,6 +45,8 @@ export type {
|
|
|
44
45
|
FlowNodeData,
|
|
45
46
|
FlowGraphData,
|
|
46
47
|
GraphIssue,
|
|
48
|
+
MeasuredLabel,
|
|
49
|
+
ValidateGraphOptions,
|
|
47
50
|
CollectionChain,
|
|
48
51
|
} from './flowGraph'
|
|
49
52
|
|
package/src/flows/labels.ts
CHANGED
|
@@ -214,6 +214,10 @@ export interface FlowValidationLabels {
|
|
|
214
214
|
descriptionTooLong?: (id: string, label: string) => string
|
|
215
215
|
dynamicChoiceWithoutProvider?: (id: string) => string
|
|
216
216
|
choiceDefaultIgnored?: (id: string) => string
|
|
217
|
+
buttonTitleMayBeTooLong?: (id: string, label: string) => string
|
|
218
|
+
listTitleMayBeTooLong?: (id: string, label: string) => string
|
|
219
|
+
listButtonLabelTooLong?: (id: string, label: string) => string
|
|
220
|
+
listButtonLabelMayBeTooLong?: (id: string, label: string) => string
|
|
217
221
|
}
|
|
218
222
|
|
|
219
223
|
/** Padrões dos rótulos opcionais de `FlowRunnerFieldLabels` — o componente cai neles quando o host não passa. */
|
|
@@ -413,6 +417,13 @@ export const DEFAULT_FLOW_EDITOR_LABELS: FlowEditorLabels = {
|
|
|
413
417
|
conditionIncomplete: (id) => `Nó "${id}": condição incompleta — defina variável, operador e valor.`,
|
|
414
418
|
conditionBranchMissing: (id, branch) =>
|
|
415
419
|
`Nó "${id}": ramo "${branch === 'true' ? 'Verdadeiro' : 'Falso'}" sem destino definido.`,
|
|
420
|
+
buttonTitleMayBeTooLong: (id, label) =>
|
|
421
|
+
`Nó "${id}": botão "${label}" tem variável e pode passar de 20 caracteres; confira o valor real.`,
|
|
422
|
+
listTitleMayBeTooLong: (id, label) =>
|
|
423
|
+
`Nó "${id}": item de lista "${label}" tem variável e pode passar de 24 caracteres; confira o valor real.`,
|
|
424
|
+
listButtonLabelTooLong: (id, label) => `Nó "${id}": botão da lista "${label}" passa de 20 caracteres.`,
|
|
425
|
+
listButtonLabelMayBeTooLong: (id, label) =>
|
|
426
|
+
`Nó "${id}": botão da lista "${label}" tem variável e pode passar de 20 caracteres; confira o valor real.`,
|
|
416
427
|
descriptionTooLong: (id, label) => `Nó "${id}": a descrição de "${label}" passa de 72 caracteres.`,
|
|
417
428
|
dynamicChoiceWithoutProvider: (id) => `Nó "${id}": escolha dinâmica sem provedor de opções.`,
|
|
418
429
|
choiceDefaultIgnored: (id) =>
|
package/src/index.ts
CHANGED
|
@@ -286,6 +286,15 @@ export { QuickRepliesWorkspace, QuickRepliesPicker } from './quickReplies'
|
|
|
286
286
|
export type { QuickRepliesWorkspaceProps, QuickRepliesPickerProps } from './quickReplies'
|
|
287
287
|
export { DEFAULT_QUICK_REPLIES_PICKER_LABELS, DEFAULT_QUICK_REPLIES_WORKSPACE_LABELS } from './quickReplies/labels'
|
|
288
288
|
export type { QuickRepliesPickerLabels, QuickRepliesWorkspaceLabels } from './quickReplies/labels'
|
|
289
|
+
export {
|
|
290
|
+
createMetaWhatsAppQuickRepliesClient,
|
|
291
|
+
QuickRepliesApiError,
|
|
292
|
+
} from './quickReplies/createMetaWhatsAppQuickRepliesClient'
|
|
293
|
+
export type {
|
|
294
|
+
CreateMetaWhatsAppQuickRepliesClientParams,
|
|
295
|
+
MetaWhatsAppQuickRepliesClient,
|
|
296
|
+
QuickRepliesApiErrorDetail,
|
|
297
|
+
} from './quickReplies/createMetaWhatsAppQuickRepliesClient'
|
|
289
298
|
export { normalizeForSearch, filterQuickReplies, highlightMatch } from './quickReplies/quickReplySearch'
|
|
290
299
|
export type { FilterQuickRepliesParams, MatchSegment } from './quickReplies/quickReplySearch'
|
|
291
300
|
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test'
|
|
2
|
+
|
|
3
|
+
import type { QuickRepliesWorkspaceApi } from './useQuickRepliesWorkspace'
|
|
4
|
+
import { QuickRepliesApiError, createMetaWhatsAppQuickRepliesClient } from './createMetaWhatsAppQuickRepliesClient'
|
|
5
|
+
|
|
6
|
+
type Call = { url: string; init: RequestInit }
|
|
7
|
+
|
|
8
|
+
function fakeFetch(respond: (call: Call) => Response) {
|
|
9
|
+
const calls: Call[] = []
|
|
10
|
+
const fetchImpl = (async (url: string, init: RequestInit) => {
|
|
11
|
+
const call = { url, init }
|
|
12
|
+
calls.push(call)
|
|
13
|
+
return respond(call)
|
|
14
|
+
}) as unknown as typeof fetch
|
|
15
|
+
return { calls, fetchImpl }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const json = (body: unknown, status = 200) =>
|
|
19
|
+
new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
|
|
20
|
+
|
|
21
|
+
const stored = { id: 'q1', title: 'Olá', shortcut: 'ola', body: 'Olá!', sortOrder: 0, createdAt: '', updatedAt: '' }
|
|
22
|
+
|
|
23
|
+
describe('createMetaWhatsAppQuickRepliesClient', () => {
|
|
24
|
+
it('lista desembrulhando { data } e manda o cabeçalho do host e a busca', async () => {
|
|
25
|
+
const { calls, fetchImpl } = fakeFetch(() => json({ data: [stored] }))
|
|
26
|
+
const client = createMetaWhatsAppQuickRepliesClient({
|
|
27
|
+
baseUrl: '/v1/whatsapp',
|
|
28
|
+
fetch: fetchImpl,
|
|
29
|
+
getHeaders: async () => ({ authorization: 'Bearer t' }),
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
expect(await client.listQuickReplies({ search: ' olá & x ' })).toEqual([stored])
|
|
33
|
+
expect(calls[0]?.url).toBe('/v1/whatsapp/quick-replies?search=ol%C3%A1+%26+x')
|
|
34
|
+
expect(calls[0]?.init.method).toBe('GET')
|
|
35
|
+
expect((calls[0]?.init.headers as Record<string, string>).authorization).toBe('Bearer t')
|
|
36
|
+
|
|
37
|
+
await client.listQuickReplies()
|
|
38
|
+
expect(calls[1]?.url).toBe('/v1/whatsapp/quick-replies')
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
it('cria e edita mandando só título, atalho e texto', async () => {
|
|
42
|
+
const { calls, fetchImpl } = fakeFetch(() => json({ data: stored }, 200))
|
|
43
|
+
const client = createMetaWhatsAppQuickRepliesClient({ baseUrl: '/v1/whatsapp', fetch: fetchImpl })
|
|
44
|
+
const input = { title: 'Olá', shortcut: 'ola', body: 'Olá!', attachmentUploadIds: ['u1'] }
|
|
45
|
+
|
|
46
|
+
await client.createQuickReply(input)
|
|
47
|
+
await client.updateQuickReply('a/b', input)
|
|
48
|
+
|
|
49
|
+
expect(calls[0]?.init.method).toBe('POST')
|
|
50
|
+
expect(JSON.parse(String(calls[0]?.init.body))).toEqual({ title: 'Olá', shortcut: 'ola', body: 'Olá!' })
|
|
51
|
+
expect(calls[1]?.url).toBe('/v1/whatsapp/quick-replies/a%2Fb')
|
|
52
|
+
expect(calls[1]?.init.method).toBe('PUT')
|
|
53
|
+
expect((calls[1]?.init.headers as Record<string, string>)['content-type']).toBe('application/json')
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it('apaga e aceita o 204 sem corpo', async () => {
|
|
57
|
+
const { calls, fetchImpl } = fakeFetch(() => new Response(null, { status: 204 }))
|
|
58
|
+
const client = createMetaWhatsAppQuickRepliesClient({ baseUrl: '/v1/whatsapp', fetch: fetchImpl })
|
|
59
|
+
|
|
60
|
+
await expect(client.deleteQuickReply('q1')).resolves.toBeUndefined()
|
|
61
|
+
expect(calls[0]?.init.method).toBe('DELETE')
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
it('erro de validação vira details { field, message } e o código estável chega à tela', async () => {
|
|
65
|
+
const { fetchImpl } = fakeFetch(() =>
|
|
66
|
+
json(
|
|
67
|
+
{
|
|
68
|
+
error: {
|
|
69
|
+
code: 'VALIDATION_ERROR',
|
|
70
|
+
message: 'Requisição inválida.',
|
|
71
|
+
issues: [{ path: 'shortcut', message: 'ruim' }],
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
400,
|
|
75
|
+
),
|
|
76
|
+
)
|
|
77
|
+
const client = createMetaWhatsAppQuickRepliesClient({ baseUrl: '/v1/whatsapp', fetch: fetchImpl })
|
|
78
|
+
|
|
79
|
+
const error = await client
|
|
80
|
+
.createQuickReply({ title: 'a', shortcut: 'A', body: 'b' })
|
|
81
|
+
.catch((caught: unknown) => caught)
|
|
82
|
+
expect(error).toBeInstanceOf(QuickRepliesApiError)
|
|
83
|
+
expect((error as QuickRepliesApiError).status).toBe(400)
|
|
84
|
+
expect((error as QuickRepliesApiError).details).toEqual([{ field: 'shortcut', message: 'ruim' }])
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
it('atalho em uso chega com o código que o QuickRepliesWorkspace reconhece', async () => {
|
|
88
|
+
const { fetchImpl } = fakeFetch(() =>
|
|
89
|
+
json({ error: { code: 'QUICK_REPLY_SHORTCUT_TAKEN', message: 'Esse atalho já está em uso.' } }, 409),
|
|
90
|
+
)
|
|
91
|
+
const client = createMetaWhatsAppQuickRepliesClient({ baseUrl: '/v1/whatsapp', fetch: fetchImpl })
|
|
92
|
+
|
|
93
|
+
const error = await client
|
|
94
|
+
.createQuickReply({ title: 'a', shortcut: 'a', body: 'b' })
|
|
95
|
+
.catch((caught: unknown) => caught)
|
|
96
|
+
expect((error as QuickRepliesApiError).code).toBe('QUICK_REPLY_SHORTCUT_TAKEN')
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
it('corpo de erro ilegível ainda vira QuickRepliesApiError com o status', async () => {
|
|
100
|
+
const { fetchImpl } = fakeFetch(() => new Response('<html>', { status: 502 }))
|
|
101
|
+
const client = createMetaWhatsAppQuickRepliesClient({ baseUrl: '/v1/whatsapp', fetch: fetchImpl })
|
|
102
|
+
|
|
103
|
+
const error = await client.listQuickReplies().catch((caught: unknown) => caught)
|
|
104
|
+
expect((error as QuickRepliesApiError).status).toBe(502)
|
|
105
|
+
expect((error as QuickRepliesApiError).code).toBe('HTTP_ERROR')
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
it('satisfaz a porta do QuickRepliesWorkspace', () => {
|
|
109
|
+
const client = createMetaWhatsAppQuickRepliesClient({ baseUrl: '/v1/whatsapp' })
|
|
110
|
+
const api: QuickRepliesWorkspaceApi = client
|
|
111
|
+
expect(typeof api.listQuickReplies).toBe('function')
|
|
112
|
+
})
|
|
113
|
+
})
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
3
|
+
*
|
|
4
|
+
* Porta de respostas rápidas pronta para as rotas de `createMetaWhatsAppQuickReplyRoutes`
|
|
5
|
+
* (`@adatechnology/meta-whatsapp-module`). O resultado se espalha em `ConversationsApi` e satisfaz
|
|
6
|
+
* `QuickRepliesWorkspaceApi`; sem ele cada host reescrevia a mesma ponte — e errava o envelope.
|
|
7
|
+
*
|
|
8
|
+
* Só texto: anexos de resposta rápida não existem no módulo, então não há `uploadQuickReplyAttachment`
|
|
9
|
+
* e as telas não oferecem a seção de anexos.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { QuickReply, QuickReplyInput } from './quickReply.types'
|
|
13
|
+
|
|
14
|
+
export type CreateMetaWhatsAppQuickRepliesClientParams = {
|
|
15
|
+
/** Onde o host montou as rotas, ex.: `/v1/whatsapp`. Sem barra no fim; `/quick-replies` é acrescentado. */
|
|
16
|
+
readonly baseUrl: string
|
|
17
|
+
/** Cabeçalhos por requisição (o `Authorization` do host). Chamado a cada request. */
|
|
18
|
+
readonly getHeaders?: () => Record<string, string> | Promise<Record<string, string>>
|
|
19
|
+
readonly fetch?: typeof fetch
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type MetaWhatsAppQuickRepliesClient = {
|
|
23
|
+
readonly listQuickReplies: (params?: { search?: string }) => Promise<QuickReply[]>
|
|
24
|
+
readonly createQuickReply: (input: QuickReplyInput) => Promise<QuickReply>
|
|
25
|
+
readonly updateQuickReply: (id: string, input: QuickReplyInput) => Promise<QuickReply>
|
|
26
|
+
readonly deleteQuickReply: (id: string) => Promise<void>
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export type QuickRepliesApiErrorDetail = { readonly field: string; readonly message: string }
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Erro da API com `code` estável e `details` no formato que o `QuickRepliesWorkspace` lê
|
|
33
|
+
* (`{ field, message }`): a validação do módulo devolve `issues[{ path, message }]`, traduzido aqui
|
|
34
|
+
* para o erro aparecer no campo certo do formulário.
|
|
35
|
+
*/
|
|
36
|
+
export class QuickRepliesApiError extends Error {
|
|
37
|
+
constructor(
|
|
38
|
+
message: string,
|
|
39
|
+
readonly status: number,
|
|
40
|
+
readonly code: string,
|
|
41
|
+
readonly details: readonly QuickRepliesApiErrorDetail[] = [],
|
|
42
|
+
) {
|
|
43
|
+
super(message)
|
|
44
|
+
this.name = 'QuickRepliesApiError'
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
type ErrorBody = {
|
|
49
|
+
readonly error?: {
|
|
50
|
+
readonly code?: string
|
|
51
|
+
readonly message?: string
|
|
52
|
+
readonly issues?: readonly { readonly path?: string; readonly message?: string }[]
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function toApiError(response: Response): Promise<QuickRepliesApiError> {
|
|
57
|
+
const body = (await response.json().catch(() => undefined)) as ErrorBody | undefined
|
|
58
|
+
const details = (body?.error?.issues ?? []).flatMap((issue) =>
|
|
59
|
+
issue.path && issue.message ? [{ field: issue.path, message: issue.message }] : [],
|
|
60
|
+
)
|
|
61
|
+
return new QuickRepliesApiError(
|
|
62
|
+
body?.error?.message ?? `Falha na API de respostas rápidas (${response.status})`,
|
|
63
|
+
response.status,
|
|
64
|
+
body?.error?.code ?? 'HTTP_ERROR',
|
|
65
|
+
details,
|
|
66
|
+
)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Só o que o módulo aceita — `attachmentUploadIds` e afins ficam de fora do corpo.
|
|
70
|
+
function toBody(input: QuickReplyInput): Pick<QuickReplyInput, 'title' | 'shortcut' | 'body'> {
|
|
71
|
+
return { title: input.title, shortcut: input.shortcut, body: input.body }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function createMetaWhatsAppQuickRepliesClient(
|
|
75
|
+
params: CreateMetaWhatsAppQuickRepliesClientParams,
|
|
76
|
+
): MetaWhatsAppQuickRepliesClient {
|
|
77
|
+
const fetchImpl = params.fetch ?? globalThis.fetch.bind(globalThis)
|
|
78
|
+
const collectionUrl = `${params.baseUrl}/quick-replies`
|
|
79
|
+
|
|
80
|
+
async function request(url: string, method: string, json?: unknown): Promise<Response> {
|
|
81
|
+
const headers: Record<string, string> = { ...(await params.getHeaders?.()) }
|
|
82
|
+
if (json !== undefined) headers['content-type'] = 'application/json'
|
|
83
|
+
const response = await fetchImpl(url, {
|
|
84
|
+
method,
|
|
85
|
+
headers,
|
|
86
|
+
...(json === undefined ? {} : { body: JSON.stringify(json) }),
|
|
87
|
+
})
|
|
88
|
+
if (!response.ok) throw await toApiError(response)
|
|
89
|
+
return response
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function requestData<TResult>(url: string, method: string, json?: unknown): Promise<TResult> {
|
|
93
|
+
const response = await request(url, method, json)
|
|
94
|
+
return ((await response.json()) as { data: TResult }).data
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const itemUrl = (id: string): string => `${collectionUrl}/${encodeURIComponent(id)}`
|
|
98
|
+
|
|
99
|
+
return {
|
|
100
|
+
listQuickReplies: (listParams) => {
|
|
101
|
+
const search = listParams?.search?.trim()
|
|
102
|
+
const query = search ? `?${new URLSearchParams({ search }).toString()}` : ''
|
|
103
|
+
return requestData<QuickReply[]>(`${collectionUrl}${query}`, 'GET')
|
|
104
|
+
},
|
|
105
|
+
createQuickReply: (input) => requestData<QuickReply>(collectionUrl, 'POST', toBody(input)),
|
|
106
|
+
updateQuickReply: (id, input) => requestData<QuickReply>(itemUrl(id), 'PUT', toBody(input)),
|
|
107
|
+
deleteQuickReply: async (id) => {
|
|
108
|
+
await request(itemUrl(id), 'DELETE')
|
|
109
|
+
},
|
|
110
|
+
}
|
|
111
|
+
}
|