@adatechnology/conversations-ui 0.1.0-rc.2 → 0.1.0-rc.21

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.
Files changed (106) hide show
  1. package/dist/{chunk-ZDURDZTM.js → chunk-2AYDBWNE.js} +14 -0
  2. package/dist/chunk-TV4OQRGH.js +2187 -0
  3. package/dist/flows/index.d.ts +14 -2
  4. package/dist/flows/index.js +117 -39
  5. package/dist/index.d.ts +862 -136
  6. package/dist/index.js +1746 -1124
  7. package/dist/preview/index.d.ts +470 -0
  8. package/dist/preview/index.js +1329 -0
  9. package/dist/styles.css +228 -0
  10. package/dist/types-C6A_9edv.d.ts +456 -0
  11. package/package.json +10 -3
  12. package/src/AudioRecorderButton.test.tsx +30 -0
  13. package/src/AudioRecorderButton.tsx +248 -0
  14. package/src/AudioTranscription.test.tsx +115 -0
  15. package/src/AudioTranscription.tsx +249 -0
  16. package/src/Avatar.tsx +30 -4
  17. package/src/ChannelIcon.tsx +87 -0
  18. package/src/ConversationContextPanel.tsx +280 -0
  19. package/src/ConversationDocumentsPanel.tsx +425 -0
  20. package/src/ConversationHeader.tsx +257 -0
  21. package/src/ConversationListItem.tsx +54 -7
  22. package/src/ConversationLocalesProvider.tsx +44 -0
  23. package/src/ConversationRow.tsx +137 -0
  24. package/src/DateDivider.tsx +16 -3
  25. package/src/DocumentsLibrary.tsx +322 -0
  26. package/src/EmojiPicker.tsx +69 -55
  27. package/src/FileIcon.test.ts +83 -0
  28. package/src/FileIcon.tsx +88 -11
  29. package/src/InteractiveMessage.test.tsx +41 -0
  30. package/src/InteractiveMessage.tsx +143 -0
  31. package/src/Lightbox.tsx +18 -3
  32. package/src/MediaRenderer.tsx +96 -22
  33. package/src/MessageBubble.tsx +77 -5
  34. package/src/MessageComposer.test.tsx +35 -0
  35. package/src/MessageComposer.tsx +165 -19
  36. package/src/RichMessageComposer.test.tsx +83 -0
  37. package/src/RichMessageComposer.tsx +380 -0
  38. package/src/Wallpaper.test.tsx +21 -0
  39. package/src/Wallpaper.tsx +69 -7
  40. package/src/WhatsAppMessageEditor.tsx +28 -4
  41. package/src/WindowExpiredNotice.tsx +57 -0
  42. package/src/audioRecorderFormat.test.ts +67 -0
  43. package/src/conversationChannel.test.ts +53 -0
  44. package/src/conversationChannel.ts +146 -0
  45. package/src/conversationTranscript.test.ts +122 -0
  46. package/src/conversationTranscript.ts +89 -0
  47. package/src/conversationWindow.test.ts +90 -0
  48. package/src/conversationWindow.ts +78 -0
  49. package/src/documentTypeLabel.test.ts +57 -0
  50. package/src/emojiCatalog.test.ts +35 -0
  51. package/src/emojiCatalog.ts +189 -0
  52. package/src/flows/FlowGroupHeader.tsx +12 -2
  53. package/src/flows/FlowMapCanvas.tsx +17 -14
  54. package/src/flows/FlowMapNode.tsx +3 -1
  55. package/src/flows/FlowNodeCard.tsx +22 -4
  56. package/src/flows/FlowNodePanel.tsx +132 -35
  57. package/src/flows/FlowPalette.tsx +6 -2
  58. package/src/flows/FlowWhatsAppPreview.tsx +14 -3
  59. package/src/flows/flowGraph.ts +5 -5
  60. package/src/flows/labels.ts +5 -0
  61. package/src/hooks/useConversationActions.ts +56 -0
  62. package/src/hooks/useConversationDocuments.ts +15 -9
  63. package/src/hooks/useConversationList.ts +15 -9
  64. package/src/hooks/useConversationMessages.ts +2 -2
  65. package/src/hooks/useScrollToLatestMessage.ts +127 -0
  66. package/src/index.ts +140 -16
  67. package/src/lib/cn.test.ts +29 -0
  68. package/src/lib/cn.ts +15 -0
  69. package/src/lib/createMediaUrlResolver.ts +33 -0
  70. package/src/lib/paginated.test.ts +33 -0
  71. package/src/lib/paginated.ts +26 -0
  72. package/src/lib/phone.ts +34 -0
  73. package/src/preview/ConversationPreview.tsx +334 -0
  74. package/src/preview/MediaTypesPreview.tsx +87 -0
  75. package/src/preview/conversationPreviewFailures.test.ts +64 -0
  76. package/src/preview/createMockConversationsApi.ts +271 -0
  77. package/src/preview/createMockSSEProvider.ts +40 -0
  78. package/src/preview/createPreviewBridgeClient.test.ts +92 -0
  79. package/src/preview/createPreviewBridgeClient.ts +124 -0
  80. package/src/preview/createPreviewMediaUploader.ts +82 -0
  81. package/src/preview/createPreviewWebhookClient.test.ts +194 -0
  82. package/src/preview/createPreviewWebhookClient.ts +222 -0
  83. package/src/preview/index.ts +67 -0
  84. package/src/preview/mediaTypeOf.test.ts +15 -0
  85. package/src/preview/mockDocumentsSearch.test.ts +57 -0
  86. package/src/preview/mockEventSource.ts +53 -0
  87. package/src/preview/preview.test.ts +177 -0
  88. package/src/preview/previewFileSamples.test.ts +151 -0
  89. package/src/preview/previewFileSamples.ts +74 -0
  90. package/src/preview/previewFixtures.ts +440 -0
  91. package/src/preview/previewMediaSource.test.ts +62 -0
  92. package/src/preview/previewMediaSource.ts +91 -0
  93. package/src/preview/previewMediaUploader.test.ts +61 -0
  94. package/src/preview/previewStore.ts +193 -0
  95. package/src/preview/startPreviewScript.ts +60 -0
  96. package/src/providers/types.ts +175 -12
  97. package/src/quickReply.test.ts +58 -0
  98. package/src/settings/TranscriptionSettingsForm.test.tsx +81 -0
  99. package/src/settings/TranscriptionSettingsForm.tsx +189 -0
  100. package/src/settings/WhatsAppCreateTemplateForm.tsx +3 -1
  101. package/src/settings/WhatsAppTemplatesSettings.tsx +106 -0
  102. package/src/styles.css +173 -0
  103. package/src/types.ts +72 -1
  104. package/src/useDarkMode.ts +26 -0
  105. package/src/useIsNarrow.ts +29 -0
  106. package/src/useWaitingNotifications.ts +74 -29
@@ -0,0 +1,271 @@
1
+ /**
2
+ * `ConversationsApi` servido pelo store em memória. Como o pacote é headless e recebe a API por
3
+ * injeção, o preview de atendimento humano não precisa de servidor, banco nem Meta: é só outra
4
+ * implementação deste mesmo contrato.
5
+ *
6
+ * Toda resposta é assíncrona e passa por um atraso configurável — API instantânea esconde estados
7
+ * de carregamento, e é neles que a inbox costuma mostrar defeito.
8
+ */
9
+
10
+ import type { MessagePayload } from '../types'
11
+ import type {
12
+ CompanyDocumentPage,
13
+ ConversationDocumentPage,
14
+ ConversationPage,
15
+ ConversationTemplate,
16
+ ConversationsApi,
17
+ ListConversationsParams,
18
+ } from '../providers/types'
19
+ import { PREVIEW_DOCUMENTS } from './previewFixtures'
20
+ import { previewFileBase64, previewFileUrl } from './previewMediaSource'
21
+ import type { PreviewStore } from './previewStore'
22
+
23
+ export type CreateMockConversationsApiParams = {
24
+ readonly store: PreviewStore
25
+ readonly latencyMs?: number
26
+ readonly agentName?: string
27
+ }
28
+
29
+ const DEFAULT_LATENCY_MS = 120
30
+
31
+ const PREVIEW_AGENT_ID = 'preview-agent'
32
+
33
+ const PREVIEW_TEMPLATES: readonly ConversationTemplate[] = [
34
+ { name: 'retomada_atendimento', language: 'pt_BR', status: 'APPROVED', category: 'UTILITY' },
35
+ { name: 'lembrete_documentos', language: 'pt_BR', status: 'APPROVED', category: 'UTILITY' },
36
+ { name: 'promocao_taxa', language: 'pt_BR', status: 'PENDING', category: 'MARKETING' },
37
+ ]
38
+
39
+ /**
40
+ * O mock satisfaz `ConversationsApi`, mas com o retorno de `fetchConversations` ESTREITADO para a
41
+ * forma paginada. Sem isto o contrato — que aceita array ou página — obrigaria todo consumidor do
42
+ * preview a desempacotar uma união que aqui nunca varia.
43
+ */
44
+ export type MockConversationsApi = Omit<ConversationsApi, 'fetchConversations'> & {
45
+ fetchConversations(params?: ListConversationsParams): Promise<ConversationPage>
46
+ }
47
+
48
+ export function createMockConversationsApi(params: CreateMockConversationsApiParams): MockConversationsApi {
49
+ const latencyMs = params.latencyMs ?? DEFAULT_LATENCY_MS
50
+
51
+ async function withLatency<TResult>(produce: () => TResult): Promise<TResult> {
52
+ await new Promise((resolve) => setTimeout(resolve, latencyMs))
53
+ return produce()
54
+ }
55
+
56
+ return {
57
+ // Devolve a forma paginada, não o array puro: é a que o contrato passou a oferecer e a que
58
+ // permite o preview desenhar controles de página. O total é contado ANTES do corte — depois
59
+ // dele seria sempre o tamanho da página, e a paginação nunca sairia da primeira.
60
+ fetchConversations(fetchParams): Promise<ConversationPage> {
61
+ return withLatency(() => {
62
+ const conversations = params.store.listConversations({
63
+ waitingHuman: fetchParams?.waitingHuman,
64
+ search: fetchParams?.search,
65
+ })
66
+
67
+ const limit = fetchParams?.limit ?? conversations.length
68
+ const page = fetchParams?.page ?? 1
69
+ return {
70
+ conversations: conversations.slice((page - 1) * limit, page * limit),
71
+ total: conversations.length,
72
+ }
73
+ })
74
+ },
75
+
76
+ fetchMessages(conversationId, fetchParams): Promise<MessagePayload[]> {
77
+ return withLatency(() => {
78
+ const messages = params.store.listMessages(conversationId)
79
+ const limit = fetchParams?.limit
80
+ return limit ? messages.slice(-limit) : messages
81
+ })
82
+ },
83
+
84
+ sendMessage(conversationId, text): Promise<MessagePayload> {
85
+ return withLatency(() =>
86
+ params.store.appendMessage({ conversationId, content: text, direction: 'outbound', sender: 'agent' }),
87
+ )
88
+ },
89
+
90
+ sendMedia(conversationId, data): Promise<MessagePayload> {
91
+ return withLatency(() =>
92
+ params.store.appendMessage({
93
+ conversationId,
94
+ content: data.caption ?? data.filename,
95
+ direction: 'outbound',
96
+ sender: 'agent',
97
+ }),
98
+ )
99
+ },
100
+
101
+ sendTemplate(conversationId, data): Promise<void> {
102
+ return withLatency(() => {
103
+ params.store.appendMessage({
104
+ conversationId,
105
+ // Sem nome, o host está pedindo o template padrão do backend — o mock representa isso
106
+ // pelo que o atendente veria, não por um nome inventado.
107
+ content: `[template] ${data.templateName ?? PREVIEW_TEMPLATES[0]?.name ?? 'padrao'}`,
108
+ direction: 'outbound',
109
+ sender: 'agent',
110
+ })
111
+ })
112
+ },
113
+
114
+ markRead(conversationId): Promise<void> {
115
+ return withLatency(() => params.store.markRead(conversationId))
116
+ },
117
+
118
+ getContext(conversationId): Promise<Record<string, unknown>> {
119
+ return withLatency(() => {
120
+ const conversation = params.store.listConversations().find((item) => item.id === conversationId)
121
+ return {
122
+ currentState: conversation?.currentState ?? 'unknown',
123
+ mode: conversation?.mode ?? 'bot',
124
+ preview: true,
125
+ }
126
+ })
127
+ },
128
+
129
+ /**
130
+ * Espelha o backend em busca, filtro de origem, ordenação E paginação. Mock que ignora params
131
+ * faz o painel parecer quebrado aqui e, pior, esconde o caso em que o backend também os ignora
132
+ * — foi exatamente assim que o filtro de origem passou a existir só no contrato.
133
+ */
134
+ getDocuments(conversationId, documentParams): Promise<ConversationDocumentPage> {
135
+ return withLatency(() => {
136
+ let documents = [...(PREVIEW_DOCUMENTS[conversationId] ?? [])]
137
+
138
+ const search = documentParams?.search?.trim().toLowerCase()
139
+ if (search) {
140
+ documents = documents.filter((document) => document.filename.toLowerCase().includes(search))
141
+ }
142
+
143
+ // 'team' agrupa agent + bot, como o painel apresenta.
144
+ const source = documentParams?.source
145
+ if (source === 'team') {
146
+ documents = documents.filter((document) => document.source === 'agent' || document.source === 'bot')
147
+ } else if (source) {
148
+ documents = documents.filter((document) => document.source === source)
149
+ }
150
+
151
+ documents.sort((left, right) =>
152
+ documentParams?.sortDirection === 'asc'
153
+ ? left.linkedAt.localeCompare(right.linkedAt)
154
+ : right.linkedAt.localeCompare(left.linkedAt),
155
+ )
156
+
157
+ // Total contado ANTES do corte — depois seria sempre o tamanho da página, e a paginação
158
+ // nunca sairia da primeira.
159
+ const total = documents.length
160
+ const limit = documentParams?.limit ?? total
161
+ const page = documentParams?.page ?? 1
162
+
163
+ return { documents: documents.slice((page - 1) * limit, page * limit), total }
164
+ })
165
+ },
166
+
167
+ /**
168
+ * Zip de mentira: um texto listando o que entraria. Basta para exercitar seleção, botão e o
169
+ * caminho de download no preview, sem arrastar uma lib de compactação para o pacote.
170
+ */
171
+ downloadDocumentsArchive(conversationId, uploadIds): Promise<Blob> {
172
+ return withLatency(() => {
173
+ const known = PREVIEW_DOCUMENTS[conversationId] ?? []
174
+ const names = uploadIds.map((id) => known.find((document) => document.id === id)?.filename ?? id)
175
+ return new Blob([`preview: ${names.length} arquivo(s)\n${names.join('\n')}`], { type: 'application/zip' })
176
+ })
177
+ },
178
+
179
+ /** Junta as bibliotecas de todas as conversas do fixture, com a origem de cada arquivo. */
180
+ getAllDocuments(documentParams): Promise<CompanyDocumentPage> {
181
+ return withLatency(() => {
182
+ let all = Object.entries(PREVIEW_DOCUMENTS).flatMap(([conversationId, docs]) =>
183
+ docs.map((document) => ({ ...document, conversationId })),
184
+ )
185
+
186
+ // Mesma regra do backend (`companyDocumentSearch`): o termo casa nome do arquivo OU
187
+ // telefone da conversa, e o telefone só pelos dígitos — o preview mostra o número
188
+ // formatado, então é assim que o atendente vai colá-lo na busca.
189
+ const search = documentParams?.search?.trim().toLowerCase()
190
+ if (search) {
191
+ const digits = search.replace(/\D/g, '')
192
+ all = all.filter(
193
+ (document) =>
194
+ document.filename.toLowerCase().includes(search) ||
195
+ (digits !== '' && document.conversationId.includes(digits)),
196
+ )
197
+ }
198
+
199
+ const source = documentParams?.source
200
+ if (source === 'team') {
201
+ all = all.filter((document) => document.source === 'agent' || document.source === 'bot')
202
+ } else if (source) {
203
+ all = all.filter((document) => document.source === source)
204
+ }
205
+
206
+ all.sort((left, right) =>
207
+ documentParams?.sortDirection === 'asc'
208
+ ? left.linkedAt.localeCompare(right.linkedAt)
209
+ : right.linkedAt.localeCompare(left.linkedAt),
210
+ )
211
+
212
+ const total = all.length
213
+ const limit = documentParams?.limit ?? total
214
+ const page = documentParams?.page ?? 1
215
+ return { documents: all.slice((page - 1) * limit, page * limit), total }
216
+ })
217
+ },
218
+
219
+ // Devolve os bytes DO TIPO do documento, não uma imagem para tudo: antes, abrir um PDF entregava
220
+ // um PNG rotulado `application/pdf` e o leitor recusava o arquivo. O `uploadId` é a única pista
221
+ // que o contrato dá, então o tipo vem da própria biblioteca.
222
+ getDocumentUrl(uploadId): Promise<string> {
223
+ return withLatency(() => {
224
+ const found = Object.values(PREVIEW_DOCUMENTS)
225
+ .flat()
226
+ .find((document) => document.id === uploadId)
227
+ return previewFileUrl(found?.mimeType, found?.filename)
228
+ })
229
+ },
230
+
231
+ // Caminho da mídia ainda não ingerida: o backend busca na Meta e devolve base64. Resolve pelo
232
+ // id para a bolha receber os bytes DO TIPO dela — devolvendo um PNG para todo id, vídeo e áudio
233
+ // apareciam quebrados na thread mesmo havendo amostra válida do formato.
234
+ getMediaProxyUrl(mediaId): Promise<{ mimeType: string; data: string }> {
235
+ return withLatency(() => {
236
+ const found = Object.values(PREVIEW_DOCUMENTS)
237
+ .flat()
238
+ .find((document) => document.id === `preview/inbound/${mediaId}`)
239
+ return previewFileBase64(found?.mimeType, found?.filename)
240
+ })
241
+ },
242
+
243
+ takeover(conversationId): Promise<void> {
244
+ return withLatency(() =>
245
+ params.store.setMode({ conversationId, mode: 'human', assignedUserId: PREVIEW_AGENT_ID }),
246
+ )
247
+ },
248
+
249
+ release(conversationId): Promise<void> {
250
+ return withLatency(() => params.store.setMode({ conversationId, mode: 'bot' }))
251
+ },
252
+
253
+ // Encerrar devolve ao bot como o release, e é de propósito: a diferença entre os dois é a
254
+ // despedida, que o host manda antes de chamar aqui. O mock não a inventa.
255
+ finalize(conversationId): Promise<void> {
256
+ return withLatency(() => params.store.setMode({ conversationId, mode: 'bot' }))
257
+ },
258
+
259
+ markAllRead(): Promise<void> {
260
+ return withLatency(() => {
261
+ for (const conversation of params.store.listConversations()) {
262
+ params.store.markRead(conversation.id)
263
+ }
264
+ })
265
+ },
266
+
267
+ listTemplates(): Promise<ConversationTemplate[]> {
268
+ return withLatency(() => [...PREVIEW_TEMPLATES])
269
+ },
270
+ }
271
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * `SSEProvider` servido pelo store em memória. Mesmo mapeamento de canal do servidor
3
+ * (`conv:<conversationId>` e `global`), para que a UI não perceba a troca.
4
+ */
5
+
6
+ import type { SSEProvider } from '../providers/types'
7
+ import { createMockEventSource } from './mockEventSource'
8
+ import { conversationChannel, GLOBAL_CHANNEL, type PreviewStore } from './previewStore'
9
+
10
+ export type CreateMockSSEProviderParams = {
11
+ readonly store: PreviewStore
12
+ }
13
+
14
+ export function createMockSSEProvider(params: CreateMockSSEProviderParams): SSEProvider {
15
+ function connect(channel: string): ReturnType<typeof createMockEventSource> {
16
+ const source = createMockEventSource()
17
+ const unsubscribe = params.store.subscribe(channel, (emission) => {
18
+ source.emit(emission.event, emission.payload)
19
+ })
20
+
21
+ const close = source.close.bind(source)
22
+ // O unsubscribe tem de acontecer no close, senão cada remontagem de componente deixa um
23
+ // listener preso no store e a mesma mensagem chega duplicada na UI.
24
+ source.close = (): void => {
25
+ unsubscribe()
26
+ close()
27
+ }
28
+
29
+ return source
30
+ }
31
+
32
+ return {
33
+ connectConversationStream(conversationId: string) {
34
+ return connect(conversationChannel(conversationId))
35
+ },
36
+ connectGlobalStream() {
37
+ return connect(GLOBAL_CHANNEL)
38
+ },
39
+ }
40
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * O que estes testes protegem é a propriedade de segurança da ponte: nenhum caminho pode voltar a
3
+ * exigir segredo no navegador, e o corpo enviado tem que ser a INTENÇÃO — se um refactor passar a
4
+ * mandar payload da Meta montado no cliente, a rota do host vira injetor de webhook arbitrário.
5
+ */
6
+
7
+ import { describe, expect, it } from 'bun:test'
8
+
9
+ import { createPreviewBridgeClient, PreviewBridgeRejectedError } from './createPreviewBridgeClient'
10
+ import type { PreviewInboundCommand } from './createPreviewBridgeClient'
11
+
12
+ const FROM = '5511999999999'
13
+
14
+ function createRecordingClient() {
15
+ const commands: PreviewInboundCommand[] = []
16
+ const client = createPreviewBridgeClient({
17
+ from: FROM,
18
+ sendCommand: async (command) => {
19
+ commands.push(command)
20
+ },
21
+ })
22
+ return { client, commands }
23
+ }
24
+
25
+ describe('createPreviewBridgeClient', () => {
26
+ it('entrega a intenção do cliente, carimbando o remetente em cada comando', async () => {
27
+ const { client, commands } = createRecordingClient()
28
+
29
+ await client.sendText('quero simular')
30
+ await client.sendButtonReply({ id: 'hab_pronto', title: 'Imóvel pronto' })
31
+ await client.sendListReply({ id: 'faixa_2', title: 'Faixa 2' })
32
+ await client.sendAudio('media-1')
33
+ await client.sendMedia({ mediaType: 'document', mediaId: 'media-2', filename: 'rg.pdf' })
34
+
35
+ expect(commands).toEqual([
36
+ { kind: 'text', from: FROM, text: 'quero simular' },
37
+ { kind: 'buttonReply', from: FROM, reply: { id: 'hab_pronto', title: 'Imóvel pronto' } },
38
+ { kind: 'listReply', from: FROM, reply: { id: 'faixa_2', title: 'Faixa 2' } },
39
+ { kind: 'audio', from: FROM, mediaId: 'media-1' },
40
+ { kind: 'media', from: FROM, mediaType: 'document', mediaId: 'media-2', filename: 'rg.pdf' },
41
+ ])
42
+ })
43
+
44
+ it('nunca embute assinatura nem segredo no que sai do navegador', async () => {
45
+ const { client, commands } = createRecordingClient()
46
+
47
+ await client.sendText('oi')
48
+
49
+ const serialized = JSON.stringify(commands[0])
50
+ expect(serialized).not.toMatch(/sha256=/)
51
+ expect(serialized).not.toMatch(/secret/i)
52
+ expect(commands[0]).not.toHaveProperty('entry')
53
+ })
54
+
55
+ it('posta no endpoint do host com os headers de sessão que o host injeta', async () => {
56
+ const calls: Array<{ url: string; init: RequestInit }> = []
57
+ const client = createPreviewBridgeClient({
58
+ from: FROM,
59
+ endpointUrl: 'https://host.test/api/conversations/preview/inbound',
60
+ headers: { authorization: 'Bearer token-do-painel' },
61
+ fetchImplementation: (async (url: string, init: RequestInit) => {
62
+ calls.push({ url, init })
63
+ return { ok: true } as Response
64
+ }) as unknown as typeof fetch,
65
+ })
66
+
67
+ await client.sendText('oi')
68
+
69
+ expect(calls[0]?.url).toBe('https://host.test/api/conversations/preview/inbound')
70
+ expect(calls[0]?.init.method).toBe('POST')
71
+ expect(calls[0]?.init.headers).toMatchObject({
72
+ 'content-type': 'application/json',
73
+ authorization: 'Bearer token-do-painel',
74
+ })
75
+ expect(JSON.parse(String(calls[0]?.init.body))).toEqual({ kind: 'text', from: FROM, text: 'oi' })
76
+ })
77
+
78
+ it('converte recusa do host em erro tipado, para o painel poder mostrar o motivo', async () => {
79
+ const client = createPreviewBridgeClient({
80
+ from: FROM,
81
+ endpointUrl: 'https://host.test/preview',
82
+ fetchImplementation: (async () => ({ ok: false, status: 403 }) as Response) as unknown as typeof fetch,
83
+ })
84
+
85
+ await expect(client.sendText('oi')).rejects.toBeInstanceOf(PreviewBridgeRejectedError)
86
+ await expect(client.sendText('oi')).rejects.toThrow(/403/)
87
+ })
88
+
89
+ it('recusa configuração sem forma de entregar, em vez de falhar só no primeiro envio', () => {
90
+ expect(() => createPreviewBridgeClient({ from: FROM })).toThrow(/sendCommand.*endpointUrl/)
91
+ })
92
+ })
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Cliente do preview que NÃO carrega segredo: em vez de montar e assinar o payload da Meta no
3
+ * navegador, manda um comando semântico (`{ kind: 'text', text }`) para uma rota do próprio host,
4
+ * autenticada pela sessão que o painel já tem. Quem monta o payload e assina é o servidor, com o
5
+ * app secret que nunca sai de lá.
6
+ *
7
+ * Por que esta fábrica existe ao lado de `createPreviewWebhookClient`: assinar no navegador exige o
8
+ * app secret dentro do bundle, e bundle é público por definição — em qualquer ambiente com URL
9
+ * acessível isso é o mesmo que publicar o segredo. Com o segredo vazado, qualquer um forja webhooks
10
+ * válidos daquele app: injeta mensagens de qualquer número e dispara os fluxos. `createPreviewWebhook
11
+ * Client` continua servindo para execução puramente local (docker de dev, onde o bundle não é
12
+ * servido para ninguém); para qualquer ambiente publicado, a ponte é o caminho.
13
+ *
14
+ * O pacote não decide autenticação: o host injeta `sendCommand` (ou `headers` + `fetchImplementation`),
15
+ * porque token, cookie e cabeçalho de sessão são do produto, não da biblioteca.
16
+ */
17
+
18
+ import type { InboundMediaType, InteractiveReplyOption } from '@adatechnology/meta-whatsapp-contracts/testing'
19
+ import {
20
+ createPreviewMediaPoster,
21
+ defaultMediaUploadUrl,
22
+ type PreviewWebhookClient,
23
+ type SendPreviewMediaParams,
24
+ } from './createPreviewWebhookClient'
25
+ import type { PreviewUploadedMedia } from './createPreviewMediaUploader'
26
+
27
+ /**
28
+ * Comando semântico entregue ao host. É deliberadamente o QUE o cliente fez, não o payload da Meta:
29
+ * se o navegador mandasse o payload pronto, a rota viraria um injetor de webhook arbitrário para
30
+ * quem tivesse sessão. Mandando a intenção, o servidor é quem escolhe a forma.
31
+ */
32
+ export type PreviewInboundCommand =
33
+ | { readonly kind: 'text'; readonly from: string; readonly text: string }
34
+ | { readonly kind: 'buttonReply'; readonly from: string; readonly reply: InteractiveReplyOption }
35
+ | { readonly kind: 'listReply'; readonly from: string; readonly reply: InteractiveReplyOption }
36
+ | { readonly kind: 'audio'; readonly from: string; readonly mediaId: string }
37
+ | ({ readonly kind: 'media'; readonly from: string } & SendPreviewMediaParams)
38
+
39
+ export type SendPreviewInboundCommand = (command: PreviewInboundCommand) => Promise<void>
40
+
41
+ export class PreviewBridgeRejectedError extends Error {
42
+ constructor(readonly status: number) {
43
+ super(`A rota de preview do host recusou a entrega (HTTP ${status}).`)
44
+ this.name = 'PreviewBridgeRejectedError'
45
+ }
46
+ }
47
+
48
+ export type CreatePreviewBridgeClientParams = {
49
+ readonly from: string
50
+ /**
51
+ * Entrega o comando. Use quando o host já tem um cliente HTTP com sessão, interceptors e refresh
52
+ * de token — reimplementar isso aqui só duplicaria a autenticação do produto.
53
+ */
54
+ readonly sendCommand?: SendPreviewInboundCommand
55
+ /** Alternativa a `sendCommand` para hosts sem cliente HTTP próprio. */
56
+ readonly endpointUrl?: string
57
+ readonly headers?: Readonly<Record<string, string>>
58
+ readonly fetchImplementation?: typeof fetch
59
+ /**
60
+ * Rota que guarda o áudio gravado. Por padrão, `/v1/preview/media` na origem do `endpointUrl`.
61
+ *
62
+ * Aqui não há assinatura a calcular: a ponte existe justamente para não ter segredo no navegador,
63
+ * e a rota é protegida pela sessão do painel — os mesmos `headers` do comando valem para o upload.
64
+ */
65
+ readonly mediaUploadUrl?: string
66
+ /**
67
+ * Substitui o upload embutido. Necessário para host que só passa `sendCommand`: sem `endpointUrl`
68
+ * não há origem a derivar, e sem destino o gravador não é desenhado.
69
+ */
70
+ readonly uploadMedia?: (file: File) => Promise<PreviewUploadedMedia>
71
+ }
72
+
73
+ function buildFetchSender(params: CreatePreviewBridgeClientParams): SendPreviewInboundCommand {
74
+ const endpointUrl = params.endpointUrl
75
+ if (!endpointUrl) {
76
+ throw new Error('createPreviewBridgeClient exige `sendCommand` ou `endpointUrl`.')
77
+ }
78
+
79
+ return async (command) => {
80
+ const performRequest = params.fetchImplementation ?? fetch
81
+ const response = await performRequest(endpointUrl, {
82
+ method: 'POST',
83
+ // `credentials` fica com o host via `headers`/`fetchImplementation`: sessão por cookie e por
84
+ // bearer não convivem numa escolha default sem quebrar um dos dois.
85
+ headers: { 'content-type': 'application/json', ...params.headers },
86
+ body: JSON.stringify(command),
87
+ })
88
+
89
+ if (!response.ok) throw new PreviewBridgeRejectedError(response.status)
90
+ }
91
+ }
92
+
93
+ /** Só existe quando há para onde mandar: rota explícita, ou origem herdada do `endpointUrl`. */
94
+ function resolveBridgeUpload(
95
+ params: CreatePreviewBridgeClientParams,
96
+ ): ((file: File) => Promise<PreviewUploadedMedia>) | undefined {
97
+ if (params.uploadMedia) return params.uploadMedia
98
+
99
+ const url = params.mediaUploadUrl ?? (params.endpointUrl ? defaultMediaUploadUrl(params.endpointUrl) : undefined)
100
+ if (!url) return undefined
101
+
102
+ return createPreviewMediaPoster({
103
+ url,
104
+ ...(params.headers ? { headers: async () => params.headers ?? {} } : {}),
105
+ ...(params.fetchImplementation ? { fetchImplementation: params.fetchImplementation } : {}),
106
+ })
107
+ }
108
+
109
+ export function createPreviewBridgeClient(params: CreatePreviewBridgeClientParams): PreviewWebhookClient {
110
+ const send = params.sendCommand ?? buildFetchSender(params)
111
+ const from = params.from
112
+ const uploadMedia = resolveBridgeUpload(params)
113
+
114
+ return {
115
+ sendText: (text) => send({ kind: 'text', from, text }),
116
+ sendButtonReply: (reply) => send({ kind: 'buttonReply', from, reply }),
117
+ sendListReply: (reply) => send({ kind: 'listReply', from, reply }),
118
+ sendAudio: (mediaId) => send({ kind: 'audio', from, mediaId }),
119
+ sendMedia: (media) => send({ kind: 'media', from, ...media }),
120
+ ...(uploadMedia ? { uploadMedia } : {}),
121
+ }
122
+ }
123
+
124
+ export type { InboundMediaType }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Entrega ao simulador o `uploadMedia` que ele precisa para desenhar o microfone.
3
+ *
4
+ * O `ConversationPreview` esconde o gravador sem esta função, e com razão: microfone que grava sem
5
+ * ter onde guardar o arquivo faz o operador falar para o vazio. O que faltava era montar isto —
6
+ * lê o `File`, manda para a rota do host, devolve o `mediaId` prefixado que o webhook referencia.
7
+ *
8
+ * Fica no pacote porque a parte que erra é sempre a mesma em todo produto: converter o binário sem
9
+ * estourar a pilha e marcar o id com o prefixo que o backend reconhece. O que muda por produto é só
10
+ * a rota e o cliente HTTP — e é exatamente isso que entra por parâmetro.
11
+ */
12
+
13
+ /**
14
+ * Do `contracts`, que este pacote já consome — não uma cópia.
15
+ *
16
+ * A convenção tem duas pontas (o front gera o id, o backend resolve) e a versão anterior disso vivia
17
+ * duplicada em dois pacotes de um produto, cada cópia com um comentário pedindo para não divergir.
18
+ * Contrato compartilhado é o que o `contracts` existe para guardar.
19
+ */
20
+ export { PREVIEW_MEDIA_ID_PREFIX } from '@adatechnology/meta-whatsapp-contracts'
21
+ import { toPreviewMediaId } from '@adatechnology/meta-whatsapp-contracts'
22
+
23
+ export type PreviewUploadedMedia = {
24
+ readonly mediaId: string
25
+ readonly mimeType?: string
26
+ readonly filename?: string
27
+ }
28
+
29
+ export type PreviewMediaUploadRequest = {
30
+ readonly base64: string
31
+ readonly mimeType: string
32
+ readonly filename: string
33
+ }
34
+
35
+ export type CreatePreviewMediaUploaderParams = {
36
+ /**
37
+ * Envia o arquivo à rota do host e devolve o `uploadId` (sem prefixo) que o backend gerou.
38
+ *
39
+ * Recebe a função inteira, e não uma URL, porque autenticação varia: uma instalação assina com
40
+ * HMAC, outra manda token de admin, outra usa cookie de sessão. Pedir a URL obrigaria o pacote a
41
+ * escolher por elas.
42
+ */
43
+ readonly upload: (request: PreviewMediaUploadRequest) => Promise<{ uploadId: string }>
44
+ /** Nome usado quando o gravador entrega o áudio sem nome próprio. */
45
+ readonly fallbackFilename?: string
46
+ readonly fallbackMimeType?: string
47
+ }
48
+
49
+ /**
50
+ * Converte em blocos, não com `String.fromCharCode(...bytes)` de uma vez.
51
+ *
52
+ * Espalhar centenas de milhares de bytes como argumentos estoura o limite da engine — poucos segundos
53
+ * de áudio já chegam perto. O sintoma seria `RangeError` só nos arquivos grandes: passa no teste com
54
+ * um clipe curto e falha na primeira gravação de verdade.
55
+ */
56
+ const CHUNK_SIZE = 8192
57
+
58
+ async function fileToBase64(file: File): Promise<string> {
59
+ const bytes = new Uint8Array(await file.arrayBuffer())
60
+ let binary = ''
61
+ for (let offset = 0; offset < bytes.length; offset += CHUNK_SIZE) {
62
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + CHUNK_SIZE))
63
+ }
64
+ return btoa(binary)
65
+ }
66
+
67
+ export function createPreviewMediaUploader(
68
+ params: CreatePreviewMediaUploaderParams,
69
+ ): (file: File) => Promise<PreviewUploadedMedia> {
70
+ const fallbackMimeType = params.fallbackMimeType ?? 'audio/ogg'
71
+ const fallbackFilename = params.fallbackFilename ?? 'audio.ogg'
72
+
73
+ return async function uploadPreviewMedia(file: File): Promise<PreviewUploadedMedia> {
74
+ // Gravação de voz chega sem nome, e sem mime em navegador antigo.
75
+ const mimeType = file.type || fallbackMimeType
76
+ const filename = file.name || fallbackFilename
77
+
78
+ const { uploadId } = await params.upload({ base64: await fileToBase64(file), mimeType, filename })
79
+
80
+ return { mediaId: toPreviewMediaId(uploadId), mimeType, filename }
81
+ }
82
+ }