@menuia/core 1.5.2 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +148 -0
- package/dist/index.d.mts +159 -1
- package/dist/index.d.ts +159 -1
- package/dist/index.js +218 -3
- package/dist/index.mjs +218 -3
- package/package.json +1 -1
package/README.md
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
# @menuia/core
|
|
2
|
+
|
|
3
|
+
SDK do chat da MenuIA para colocar o atendimento (IA + equipe) dentro do seu site ou app.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install @menuia/core
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { MenuIAClient } from '@menuia/core';
|
|
11
|
+
|
|
12
|
+
const chat = new MenuIAClient({
|
|
13
|
+
widgetId: 'SEU_WIDGET_ID', // painel › Canais › Widget
|
|
14
|
+
onMessage: (msg) => console.log(msg.role, msg.content),
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
await chat.sendMessage({ content: 'Olá!' });
|
|
18
|
+
chat.startPolling(); // respostas da equipe chegam por aqui
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Widget privado (cliente logado)
|
|
22
|
+
|
|
23
|
+
No widget **privado**, quem diz quem é o cliente é o **seu servidor**:
|
|
24
|
+
|
|
25
|
+
1. Seu backend chama `POST https://api-ia.menuia.com/api/v1/widget/<widgetId>/auth` com
|
|
26
|
+
`Authorization: Bearer wsec_...` (segredo do painel; nunca vai para o navegador) e o corpo
|
|
27
|
+
`{ externalUserId, name, email, phone }` de quem está logado.
|
|
28
|
+
2. A resposta traz `sessionToken` (vale ~10 min). Só ele vai para o front:
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
const chat = new MenuIAClient({ widgetId, sessionToken, metadata: { widgetSession: sessionToken } });
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Notificação quando a equipe ou a IA responde
|
|
35
|
+
|
|
36
|
+
Há dois jeitos, e eles se completam:
|
|
37
|
+
|
|
38
|
+
| | Quando funciona | O que você precisa |
|
|
39
|
+
|---|---|---|
|
|
40
|
+
| **Push de aplicativo** (`registrarPush`) | com o app **fechado** ou em segundo plano | app com FCM ou Expo + credencial cadastrada no painel |
|
|
41
|
+
| **Aviso do navegador** (`ativarNotificacaoNoNavegador`) | com a página aberta em **outra aba** ou minimizada | só o navegador (nenhuma credencial) |
|
|
42
|
+
|
|
43
|
+
### 1. Push de aplicativo
|
|
44
|
+
|
|
45
|
+
**a) Cadastre a credencial de envio (uma vez, dono ou admin da conta).**
|
|
46
|
+
Ela fica no servidor da MenuIA. Nunca vai no app e nunca é devolvida em leitura.
|
|
47
|
+
|
|
48
|
+
- **FCM** (Android, iOS ou web com o SDK do Firebase): no console do Firebase, abra Configurações
|
|
49
|
+
do projeto › Contas de serviço › **Gerar nova chave privada** e envie o JSON:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
curl -X PUT https://api-ia.menuia.com/api/v1/push-credentials/fcm \
|
|
53
|
+
-H "Authorization: Bearer <token do painel>" -H "Content-Type: application/json" \
|
|
54
|
+
-d '{"serviceAccount": <conteúdo do JSON>, "titulo": "Minha Loja"}'
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
A chave é conferida com o Google na hora: chave revogada ou incompleta é recusada.
|
|
58
|
+
|
|
59
|
+
- **Expo** (React Native / expo-notifications): não precisa de credencial. O token de acesso só é
|
|
60
|
+
necessário com "push security" ligado no Expo.
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
curl -X PUT https://api-ia.menuia.com/api/v1/push-credentials/expo \
|
|
64
|
+
-H "Authorization: Bearer <token do painel>" -H "Content-Type: application/json" \
|
|
65
|
+
-d '{"titulo": "Minha Loja"}'
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
**Opções** (as duas valem por credencial):
|
|
69
|
+
|
|
70
|
+
- `titulo`: título da notificação. Padrão: o nome da conta.
|
|
71
|
+
- `previa: false`: manda "Você tem uma mensagem nova no chat" em vez do começo da mensagem.
|
|
72
|
+
|
|
73
|
+
**Ver e remover:**
|
|
74
|
+
|
|
75
|
+
- `GET /push-credentials` mostra só o que está configurado, uma dica e quantos aparelhos.
|
|
76
|
+
- `DELETE /push-credentials/<fcm|expo>` remove.
|
|
77
|
+
|
|
78
|
+
**b) No app, registre o aparelho:**
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
// Android/iOS com Firebase
|
|
82
|
+
const token = await messaging().getToken();
|
|
83
|
+
await chat.registrarPush({ tipo: 'fcm', token, plataforma: 'android' });
|
|
84
|
+
|
|
85
|
+
// Expo
|
|
86
|
+
const { data: token } = await Notifications.getExpoPushTokenAsync();
|
|
87
|
+
await chat.registrarPush({ tipo: 'expo', token });
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
**Quem recebe:**
|
|
91
|
+
|
|
92
|
+
- **Widget privado:** o aparelho fica ligado à PESSOA (`externalUserId` do token de sessão) e recebe
|
|
93
|
+
as respostas de todas as conversas dela.
|
|
94
|
+
- **Widget público:** o aparelho fica ligado à conversa deste aparelho.
|
|
95
|
+
- Antes da primeira mensagem ainda não existe conversa. Nesse caso `registrarPush` devolve
|
|
96
|
+
`{ ok: true, pendente: true }` e o registro sai sozinho logo depois da primeira mensagem.
|
|
97
|
+
- **O mesmo token registrado de novo muda de dono:** num aparelho compartilhado, só quem entrou por
|
|
98
|
+
último recebe.
|
|
99
|
+
- **Ao sair da conta,** desligue: `await chat.removerPush(token)`.
|
|
100
|
+
|
|
101
|
+
**O que chega no aparelho:**
|
|
102
|
+
|
|
103
|
+
- **Título:** o configurado (ou o nome da conta). Com várias respostas antes de a pessoa voltar,
|
|
104
|
+
vira `Minha Loja — 3 mensagens novas`, numa notificação só: a nova substitui a anterior.
|
|
105
|
+
- **Texto:** o começo da mensagem (até 90 caracteres), sem marcação. Link vira "link" e mídia vira
|
|
106
|
+
"Imagem", "Áudio", "Vídeo" ou "Arquivo".
|
|
107
|
+
- **Não notifica:** mensagem do próprio visitante, nota interna da equipe e avisos do sistema.
|
|
108
|
+
- **`data`:** `{ menuia: 'chat', conversationId, widgetId }`. Use para abrir a tela do chat no
|
|
109
|
+
toque.
|
|
110
|
+
- **App aberto na tela:** o FCM entrega em `onMessageReceived`/`onMessage` e o sistema não mostra
|
|
111
|
+
nada. Decida no app se quer mostrar.
|
|
112
|
+
|
|
113
|
+
**A contagem é do que a pessoa ainda não viu.** Zera quando ela escreve e quando está com o chat
|
|
114
|
+
na tela. Com `startPolling()` e a página visível, o SDK avisa a presença sozinho. Em app nativo,
|
|
115
|
+
chame `chat.marcarPresenca()` a cada ~20 s enquanto a tela do chat estiver aberta.
|
|
116
|
+
|
|
117
|
+
### 2. Aviso do navegador
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
botao.onclick = async () => {
|
|
121
|
+
// ⚠️ dentro de um clique: o navegador só pede permissão em resposta a um gesto da pessoa
|
|
122
|
+
const permissao = await chat.ativarNotificacaoNoNavegador({ titulo: 'Minha Loja', icone: '/logo.png' });
|
|
123
|
+
// 'granted' | 'denied' | 'default' | 'indisponivel'
|
|
124
|
+
};
|
|
125
|
+
chat.startPolling();
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
- Com a aba **escondida**, cada resposta vira um aviso. O aviso seguinte substitui o anterior e
|
|
129
|
+
mostra a contagem.
|
|
130
|
+
- Ao voltar para a aba, o aviso fecha e a contagem zera.
|
|
131
|
+
- **Com a aba visível, nada aparece:** a pessoa já está vendo.
|
|
132
|
+
- **Com a página fechada, não há aviso.** Use o push de aplicativo.
|
|
133
|
+
- Para desligar: `chat.desativarNotificacaoNoNavegador()`.
|
|
134
|
+
|
|
135
|
+
> **Web Push (service worker, aviso com o site fechado) ainda não está disponível.** Por isso
|
|
136
|
+
> `registrarPush({ tipo: 'webpush' })` responde 400 explicando. Se o seu site já usa o Firebase
|
|
137
|
+
> Messaging no navegador, o token dele é do tipo `fcm` e funciona normalmente.
|
|
138
|
+
|
|
139
|
+
### Sem o SDK (chamadas diretas)
|
|
140
|
+
|
|
141
|
+
`POST /api/v1/widget/<widgetId>/push` com
|
|
142
|
+
`{ tipo: 'fcm' | 'expo', token, plataforma? }` e uma das provas abaixo:
|
|
143
|
+
|
|
144
|
+
- **widget privado:** header `x-widget-session: <sessionToken>`;
|
|
145
|
+
- **widget público:** `sessionId` da conversa no corpo, ou o `widgetToken` que `/widget/<id>/session`
|
|
146
|
+
devolveu.
|
|
147
|
+
|
|
148
|
+
Para desligar: `POST /api/v1/widget/<widgetId>/push/remove` com `{ token }` e a mesma prova.
|
package/dist/index.d.mts
CHANGED
|
@@ -44,7 +44,71 @@ interface ChatMessage {
|
|
|
44
44
|
toolCalls?: string;
|
|
45
45
|
toolResults?: string;
|
|
46
46
|
authorName?: string;
|
|
47
|
+
/**
|
|
48
|
+
* Botoes / lista / carrossel desta mensagem (ver `InteractivePayload`).
|
|
49
|
+
* Quando vem preenchido, `content` traz o MESMO conteudo em texto: mostre um OU outro.
|
|
50
|
+
*/
|
|
51
|
+
interactive?: InteractivePayload;
|
|
52
|
+
/**
|
|
53
|
+
* O envio desta mensagem FALHOU e ela nao chegou ao servidor.
|
|
54
|
+
*
|
|
55
|
+
* ⚠️ Sem este campo a bolha do usuario ficava na tela identica a uma enviada com sucesso
|
|
56
|
+
* quando o envio falhava — o hook so chamava `setError`, e quem olhava o chat nao tinha como
|
|
57
|
+
* saber que aquela mensagem nunca saiu. O widget proprio desta casa sempre teve `failed` +
|
|
58
|
+
* botao de reenviar; o SDK nao tinha recebido a paridade.
|
|
59
|
+
*
|
|
60
|
+
* Desenhe a bolha com um aviso e um botao que chame `retryMessage(msg)`.
|
|
61
|
+
*/
|
|
62
|
+
failed?: boolean;
|
|
63
|
+
}
|
|
64
|
+
/** Botao de mensagem interativa: com `url` abre um link; sem, e resposta rapida. */
|
|
65
|
+
interface InteractiveButton {
|
|
66
|
+
text: string;
|
|
67
|
+
url?: string;
|
|
68
|
+
id?: string;
|
|
47
69
|
}
|
|
70
|
+
/**
|
|
71
|
+
* Mensagem interativa enviada pela IA: botoes, lista/menu ou carrossel.
|
|
72
|
+
*
|
|
73
|
+
* Como desenhar: botao com `url` abre o link em outra aba; botao sem `url` e item de lista sao
|
|
74
|
+
* RESPOSTA — ao tocar, envie o rotulo (`text` / `title`) como a proxima mensagem do usuario.
|
|
75
|
+
* Quem nao desenha pode mostrar so o `content` da mensagem, que traz as mesmas opcoes em texto.
|
|
76
|
+
*
|
|
77
|
+
* ⚠️ O conteudo vem da IA: so abra `url` e `imageUrl` que comecem com http:// ou https://.
|
|
78
|
+
*/
|
|
79
|
+
type InteractivePayload = {
|
|
80
|
+
kind: 'buttons';
|
|
81
|
+
text?: string;
|
|
82
|
+
header?: string;
|
|
83
|
+
footer?: string;
|
|
84
|
+
buttons: InteractiveButton[];
|
|
85
|
+
} | {
|
|
86
|
+
kind: 'list';
|
|
87
|
+
text?: string;
|
|
88
|
+
header?: string;
|
|
89
|
+
list: {
|
|
90
|
+
title?: string;
|
|
91
|
+
footer?: string;
|
|
92
|
+
sections: Array<{
|
|
93
|
+
title?: string;
|
|
94
|
+
rows: Array<{
|
|
95
|
+
title: string;
|
|
96
|
+
description?: string;
|
|
97
|
+
id?: string;
|
|
98
|
+
}>;
|
|
99
|
+
}>;
|
|
100
|
+
};
|
|
101
|
+
} | {
|
|
102
|
+
kind: 'carousel';
|
|
103
|
+
text?: string;
|
|
104
|
+
footer?: string;
|
|
105
|
+
cards: Array<{
|
|
106
|
+
imageUrl?: string;
|
|
107
|
+
body?: string;
|
|
108
|
+
footer?: string;
|
|
109
|
+
buttons?: InteractiveButton[];
|
|
110
|
+
}>;
|
|
111
|
+
};
|
|
48
112
|
interface SendMessageOptions {
|
|
49
113
|
content: string;
|
|
50
114
|
attachments?: MessageAttachment[];
|
|
@@ -72,13 +136,51 @@ interface ChatResponse {
|
|
|
72
136
|
aiPaused?: boolean;
|
|
73
137
|
/** Enquanto a IA consulta a equipe: ate quando esperar por uma resposta. */
|
|
74
138
|
aiCheckingUntil?: string;
|
|
139
|
+
/**
|
|
140
|
+
* Mensagens interativas (botoes / lista / carrossel) que a IA mostrou NESTE turno, em ordem e
|
|
141
|
+
* com o id real. Na tela vem ANTES de `message`. As mesmas voltam no historico (`loadHistory`).
|
|
142
|
+
*/
|
|
143
|
+
interactiveMessages?: ChatMessage[];
|
|
75
144
|
};
|
|
76
145
|
}
|
|
77
146
|
interface StreamEvent {
|
|
78
147
|
type: 'token' | 'thinking' | 'tool_start' | 'tool_done' | 'tool_end' | 'done' | 'error' | 'response';
|
|
79
148
|
data: unknown;
|
|
80
149
|
}
|
|
150
|
+
/**
|
|
151
|
+
* Aparelho que recebe notificacao quando a equipe ou a IA responde (`client.registrarPush`).
|
|
152
|
+
*
|
|
153
|
+
* - `fcm`: token do Firebase Cloud Messaging (Android/iOS nativo, ou web com o SDK do Firebase).
|
|
154
|
+
* - `expo`: `ExponentPushToken[...]` do expo-notifications (React Native/Expo).
|
|
155
|
+
*
|
|
156
|
+
* A credencial de envio (conta de servico do Firebase / token do Expo) e do DONO do widget,
|
|
157
|
+
* cadastrada no painel — nunca vai no app.
|
|
158
|
+
*/
|
|
159
|
+
interface RegistrarPushOptions {
|
|
160
|
+
tipo: 'fcm' | 'expo';
|
|
161
|
+
token: string;
|
|
162
|
+
/** Opcional, so para o painel saber de onde veio (ex.: 'android', 'ios', 'web'). */
|
|
163
|
+
plataforma?: string;
|
|
164
|
+
}
|
|
165
|
+
interface RegistrarPushResult {
|
|
166
|
+
ok: boolean;
|
|
167
|
+
/**
|
|
168
|
+
* Widget publico sem conversa ainda: o registro fica guardado e sai sozinho logo depois da
|
|
169
|
+
* primeira mensagem (antes disso nao ha resposta para avisar).
|
|
170
|
+
*/
|
|
171
|
+
pendente?: boolean;
|
|
172
|
+
erro?: string;
|
|
173
|
+
}
|
|
174
|
+
/** Aviso do NAVEGADOR (Notification API) quando chega resposta com a aba escondida. */
|
|
175
|
+
interface NotificacaoNavegadorOptions {
|
|
176
|
+
/** Titulo do aviso. Padrao: 'Nova mensagem'. */
|
|
177
|
+
titulo?: string;
|
|
178
|
+
/** URL do icone. */
|
|
179
|
+
icone?: string;
|
|
180
|
+
}
|
|
81
181
|
interface WidgetSession {
|
|
182
|
+
/** Registro de push guardado ate existir conversa (widget publico). */
|
|
183
|
+
pushPendente?: RegistrarPushOptions;
|
|
82
184
|
sessionId: string;
|
|
83
185
|
conversationId?: string;
|
|
84
186
|
ticketId?: string;
|
|
@@ -100,6 +202,12 @@ declare class MenuIAClient {
|
|
|
100
202
|
private pollInterval;
|
|
101
203
|
private lastMessageCount;
|
|
102
204
|
private resolvedAgentId;
|
|
205
|
+
/** Aviso do navegador ligado (ativarNotificacaoNoNavegador) e quantas chegaram com a aba escondida. */
|
|
206
|
+
private notifNavegador;
|
|
207
|
+
private naoVistasNavegador;
|
|
208
|
+
private avisoNavegador;
|
|
209
|
+
private ultimaPresenca;
|
|
210
|
+
private ouvindoVisibilidade;
|
|
103
211
|
constructor(config: MenuIAConfig);
|
|
104
212
|
/** Get the effective ID (widgetId preferred, falls back to agentId) */
|
|
105
213
|
private getWidgetId;
|
|
@@ -113,12 +221,52 @@ declare class MenuIAClient {
|
|
|
113
221
|
private ensureSession;
|
|
114
222
|
/** Send a message to the AI agent */
|
|
115
223
|
sendMessage(options: SendMessageOptions): Promise<ChatResponse>;
|
|
224
|
+
/**
|
|
225
|
+
* Troca o token de sessão do widget privado (o servidor do site emite um novo antes de o anterior
|
|
226
|
+
* vencer). Vale para as próximas chamadas; a conversa continua a mesma.
|
|
227
|
+
*/
|
|
228
|
+
setSessionToken(token: string): void;
|
|
116
229
|
/** Send a message and receive streaming response */
|
|
117
230
|
sendMessageStream(options: SendMessageOptions, onToken: (token: string, fullText: string) => void): Promise<ChatResponse | null>;
|
|
118
231
|
/** Load conversation history from server */
|
|
119
232
|
loadHistory(): Promise<ChatMessage[]>;
|
|
120
233
|
/** Start polling for new messages (human agent replies) */
|
|
121
234
|
startPolling(intervalMs?: number): void;
|
|
235
|
+
/**
|
|
236
|
+
* Registra este aparelho para receber notificacao quando a equipe ou a IA responder no chat,
|
|
237
|
+
* mesmo com o app fechado. O envio usa a credencial do DONO do widget (painel > Notificacoes do
|
|
238
|
+
* chat); o app so entrega o token do aparelho.
|
|
239
|
+
*
|
|
240
|
+
* - Widget PRIVADO: vale para a PESSOA (identidade do token de sessao) em todas as conversas dela.
|
|
241
|
+
* - Widget publico: vale para a conversa deste aparelho. Sem conversa ainda, fica guardado e sai
|
|
242
|
+
* sozinho depois da primeira mensagem (`pendente: true`).
|
|
243
|
+
*
|
|
244
|
+
* O mesmo token registrado de novo muda de dono: num aparelho compartilhado, so quem entrou por
|
|
245
|
+
* ultimo recebe. Ao sair da conta, chame `removerPush(token)`.
|
|
246
|
+
*/
|
|
247
|
+
registrarPush(opcoes: RegistrarPushOptions): Promise<RegistrarPushResult>;
|
|
248
|
+
/** Desliga a notificacao neste aparelho (ex.: ao sair da conta no app). */
|
|
249
|
+
removerPush(token: string): Promise<RegistrarPushResult>;
|
|
250
|
+
/**
|
|
251
|
+
* Aviso do NAVEGADOR quando chega resposta com a aba escondida (Notification API).
|
|
252
|
+
*
|
|
253
|
+
* Chame dentro de um clique (ex.: botao "Avisar quando responderem"): o navegador so mostra o
|
|
254
|
+
* pedido de permissao em resposta a um gesto da pessoa. Funciona enquanto a pagina estiver aberta
|
|
255
|
+
* (em outra aba ou minimizada) e com `startPolling()` ligado; com a pagina FECHADA so o push de
|
|
256
|
+
* aplicativo (`registrarPush`) alcanca a pessoa.
|
|
257
|
+
*
|
|
258
|
+
* Devolve a permissao: 'granted' liga o aviso; 'denied'/'default' nao; 'indisponivel' quando o
|
|
259
|
+
* ambiente nao tem a API (app nativo, navegador antigo, iframe sem permissao).
|
|
260
|
+
*/
|
|
261
|
+
ativarNotificacaoNoNavegador(opcoes?: NotificacaoNavegadorOptions): Promise<NotificationPermission | 'indisponivel'>;
|
|
262
|
+
/** Desliga o aviso do navegador. */
|
|
263
|
+
desativarNotificacaoNoNavegador(): void;
|
|
264
|
+
/**
|
|
265
|
+
* Avisa que a pessoa esta com o chat na tela (o inbox mostra "online", e a notificacao no celular
|
|
266
|
+
* nao conta como nova o que ela ja viu). O `startPolling()` ja chama sozinho com a pagina
|
|
267
|
+
* visivel; em app nativo, chame enquanto a tela do chat estiver aberta (a cada ~20 s).
|
|
268
|
+
*/
|
|
269
|
+
marcarPresenca(): Promise<void>;
|
|
122
270
|
/** Stop polling */
|
|
123
271
|
stopPolling(): void;
|
|
124
272
|
/** Get current messages */
|
|
@@ -150,6 +298,16 @@ declare class MenuIAClient {
|
|
|
150
298
|
clearSession(): void;
|
|
151
299
|
/** Cleanup - call when component unmounts */
|
|
152
300
|
destroy(): void;
|
|
301
|
+
/** Registro guardado ate a 1a mensagem (widget publico). Falhou: fica para a proxima. */
|
|
302
|
+
private registrarPushPendente;
|
|
303
|
+
private enviarRegistroPush;
|
|
304
|
+
private paginaVisivel;
|
|
305
|
+
/** Resposta chegou pelo poll: com a aba escondida e o aviso ligado, mostra uma notificacao. */
|
|
306
|
+
private avisarNoNavegador;
|
|
307
|
+
private fecharAvisoNavegador;
|
|
308
|
+
private ouvirVisibilidade;
|
|
309
|
+
/** Voltou para a aba: o que estava avisado foi visto. */
|
|
310
|
+
private aoMudarVisibilidade;
|
|
153
311
|
private setStatus;
|
|
154
312
|
private getSessionKey;
|
|
155
313
|
private loadSession;
|
|
@@ -157,4 +315,4 @@ declare class MenuIAClient {
|
|
|
157
315
|
private saveSession;
|
|
158
316
|
}
|
|
159
317
|
|
|
160
|
-
export { type ChatMessage, type ChatResponse, type ConnectionStatus, MenuIAClient, type MenuIAConfig, type MessageAttachment, type SendMessageOptions, type StreamEvent, type WidgetSession };
|
|
318
|
+
export { type ChatMessage, type ChatResponse, type ConnectionStatus, type InteractiveButton, type InteractivePayload, MenuIAClient, type MenuIAConfig, type MessageAttachment, type NotificacaoNavegadorOptions, type RegistrarPushOptions, type RegistrarPushResult, type SendMessageOptions, type StreamEvent, type WidgetSession };
|
package/dist/index.d.ts
CHANGED
|
@@ -44,7 +44,71 @@ interface ChatMessage {
|
|
|
44
44
|
toolCalls?: string;
|
|
45
45
|
toolResults?: string;
|
|
46
46
|
authorName?: string;
|
|
47
|
+
/**
|
|
48
|
+
* Botoes / lista / carrossel desta mensagem (ver `InteractivePayload`).
|
|
49
|
+
* Quando vem preenchido, `content` traz o MESMO conteudo em texto: mostre um OU outro.
|
|
50
|
+
*/
|
|
51
|
+
interactive?: InteractivePayload;
|
|
52
|
+
/**
|
|
53
|
+
* O envio desta mensagem FALHOU e ela nao chegou ao servidor.
|
|
54
|
+
*
|
|
55
|
+
* ⚠️ Sem este campo a bolha do usuario ficava na tela identica a uma enviada com sucesso
|
|
56
|
+
* quando o envio falhava — o hook so chamava `setError`, e quem olhava o chat nao tinha como
|
|
57
|
+
* saber que aquela mensagem nunca saiu. O widget proprio desta casa sempre teve `failed` +
|
|
58
|
+
* botao de reenviar; o SDK nao tinha recebido a paridade.
|
|
59
|
+
*
|
|
60
|
+
* Desenhe a bolha com um aviso e um botao que chame `retryMessage(msg)`.
|
|
61
|
+
*/
|
|
62
|
+
failed?: boolean;
|
|
63
|
+
}
|
|
64
|
+
/** Botao de mensagem interativa: com `url` abre um link; sem, e resposta rapida. */
|
|
65
|
+
interface InteractiveButton {
|
|
66
|
+
text: string;
|
|
67
|
+
url?: string;
|
|
68
|
+
id?: string;
|
|
47
69
|
}
|
|
70
|
+
/**
|
|
71
|
+
* Mensagem interativa enviada pela IA: botoes, lista/menu ou carrossel.
|
|
72
|
+
*
|
|
73
|
+
* Como desenhar: botao com `url` abre o link em outra aba; botao sem `url` e item de lista sao
|
|
74
|
+
* RESPOSTA — ao tocar, envie o rotulo (`text` / `title`) como a proxima mensagem do usuario.
|
|
75
|
+
* Quem nao desenha pode mostrar so o `content` da mensagem, que traz as mesmas opcoes em texto.
|
|
76
|
+
*
|
|
77
|
+
* ⚠️ O conteudo vem da IA: so abra `url` e `imageUrl` que comecem com http:// ou https://.
|
|
78
|
+
*/
|
|
79
|
+
type InteractivePayload = {
|
|
80
|
+
kind: 'buttons';
|
|
81
|
+
text?: string;
|
|
82
|
+
header?: string;
|
|
83
|
+
footer?: string;
|
|
84
|
+
buttons: InteractiveButton[];
|
|
85
|
+
} | {
|
|
86
|
+
kind: 'list';
|
|
87
|
+
text?: string;
|
|
88
|
+
header?: string;
|
|
89
|
+
list: {
|
|
90
|
+
title?: string;
|
|
91
|
+
footer?: string;
|
|
92
|
+
sections: Array<{
|
|
93
|
+
title?: string;
|
|
94
|
+
rows: Array<{
|
|
95
|
+
title: string;
|
|
96
|
+
description?: string;
|
|
97
|
+
id?: string;
|
|
98
|
+
}>;
|
|
99
|
+
}>;
|
|
100
|
+
};
|
|
101
|
+
} | {
|
|
102
|
+
kind: 'carousel';
|
|
103
|
+
text?: string;
|
|
104
|
+
footer?: string;
|
|
105
|
+
cards: Array<{
|
|
106
|
+
imageUrl?: string;
|
|
107
|
+
body?: string;
|
|
108
|
+
footer?: string;
|
|
109
|
+
buttons?: InteractiveButton[];
|
|
110
|
+
}>;
|
|
111
|
+
};
|
|
48
112
|
interface SendMessageOptions {
|
|
49
113
|
content: string;
|
|
50
114
|
attachments?: MessageAttachment[];
|
|
@@ -72,13 +136,51 @@ interface ChatResponse {
|
|
|
72
136
|
aiPaused?: boolean;
|
|
73
137
|
/** Enquanto a IA consulta a equipe: ate quando esperar por uma resposta. */
|
|
74
138
|
aiCheckingUntil?: string;
|
|
139
|
+
/**
|
|
140
|
+
* Mensagens interativas (botoes / lista / carrossel) que a IA mostrou NESTE turno, em ordem e
|
|
141
|
+
* com o id real. Na tela vem ANTES de `message`. As mesmas voltam no historico (`loadHistory`).
|
|
142
|
+
*/
|
|
143
|
+
interactiveMessages?: ChatMessage[];
|
|
75
144
|
};
|
|
76
145
|
}
|
|
77
146
|
interface StreamEvent {
|
|
78
147
|
type: 'token' | 'thinking' | 'tool_start' | 'tool_done' | 'tool_end' | 'done' | 'error' | 'response';
|
|
79
148
|
data: unknown;
|
|
80
149
|
}
|
|
150
|
+
/**
|
|
151
|
+
* Aparelho que recebe notificacao quando a equipe ou a IA responde (`client.registrarPush`).
|
|
152
|
+
*
|
|
153
|
+
* - `fcm`: token do Firebase Cloud Messaging (Android/iOS nativo, ou web com o SDK do Firebase).
|
|
154
|
+
* - `expo`: `ExponentPushToken[...]` do expo-notifications (React Native/Expo).
|
|
155
|
+
*
|
|
156
|
+
* A credencial de envio (conta de servico do Firebase / token do Expo) e do DONO do widget,
|
|
157
|
+
* cadastrada no painel — nunca vai no app.
|
|
158
|
+
*/
|
|
159
|
+
interface RegistrarPushOptions {
|
|
160
|
+
tipo: 'fcm' | 'expo';
|
|
161
|
+
token: string;
|
|
162
|
+
/** Opcional, so para o painel saber de onde veio (ex.: 'android', 'ios', 'web'). */
|
|
163
|
+
plataforma?: string;
|
|
164
|
+
}
|
|
165
|
+
interface RegistrarPushResult {
|
|
166
|
+
ok: boolean;
|
|
167
|
+
/**
|
|
168
|
+
* Widget publico sem conversa ainda: o registro fica guardado e sai sozinho logo depois da
|
|
169
|
+
* primeira mensagem (antes disso nao ha resposta para avisar).
|
|
170
|
+
*/
|
|
171
|
+
pendente?: boolean;
|
|
172
|
+
erro?: string;
|
|
173
|
+
}
|
|
174
|
+
/** Aviso do NAVEGADOR (Notification API) quando chega resposta com a aba escondida. */
|
|
175
|
+
interface NotificacaoNavegadorOptions {
|
|
176
|
+
/** Titulo do aviso. Padrao: 'Nova mensagem'. */
|
|
177
|
+
titulo?: string;
|
|
178
|
+
/** URL do icone. */
|
|
179
|
+
icone?: string;
|
|
180
|
+
}
|
|
81
181
|
interface WidgetSession {
|
|
182
|
+
/** Registro de push guardado ate existir conversa (widget publico). */
|
|
183
|
+
pushPendente?: RegistrarPushOptions;
|
|
82
184
|
sessionId: string;
|
|
83
185
|
conversationId?: string;
|
|
84
186
|
ticketId?: string;
|
|
@@ -100,6 +202,12 @@ declare class MenuIAClient {
|
|
|
100
202
|
private pollInterval;
|
|
101
203
|
private lastMessageCount;
|
|
102
204
|
private resolvedAgentId;
|
|
205
|
+
/** Aviso do navegador ligado (ativarNotificacaoNoNavegador) e quantas chegaram com a aba escondida. */
|
|
206
|
+
private notifNavegador;
|
|
207
|
+
private naoVistasNavegador;
|
|
208
|
+
private avisoNavegador;
|
|
209
|
+
private ultimaPresenca;
|
|
210
|
+
private ouvindoVisibilidade;
|
|
103
211
|
constructor(config: MenuIAConfig);
|
|
104
212
|
/** Get the effective ID (widgetId preferred, falls back to agentId) */
|
|
105
213
|
private getWidgetId;
|
|
@@ -113,12 +221,52 @@ declare class MenuIAClient {
|
|
|
113
221
|
private ensureSession;
|
|
114
222
|
/** Send a message to the AI agent */
|
|
115
223
|
sendMessage(options: SendMessageOptions): Promise<ChatResponse>;
|
|
224
|
+
/**
|
|
225
|
+
* Troca o token de sessão do widget privado (o servidor do site emite um novo antes de o anterior
|
|
226
|
+
* vencer). Vale para as próximas chamadas; a conversa continua a mesma.
|
|
227
|
+
*/
|
|
228
|
+
setSessionToken(token: string): void;
|
|
116
229
|
/** Send a message and receive streaming response */
|
|
117
230
|
sendMessageStream(options: SendMessageOptions, onToken: (token: string, fullText: string) => void): Promise<ChatResponse | null>;
|
|
118
231
|
/** Load conversation history from server */
|
|
119
232
|
loadHistory(): Promise<ChatMessage[]>;
|
|
120
233
|
/** Start polling for new messages (human agent replies) */
|
|
121
234
|
startPolling(intervalMs?: number): void;
|
|
235
|
+
/**
|
|
236
|
+
* Registra este aparelho para receber notificacao quando a equipe ou a IA responder no chat,
|
|
237
|
+
* mesmo com o app fechado. O envio usa a credencial do DONO do widget (painel > Notificacoes do
|
|
238
|
+
* chat); o app so entrega o token do aparelho.
|
|
239
|
+
*
|
|
240
|
+
* - Widget PRIVADO: vale para a PESSOA (identidade do token de sessao) em todas as conversas dela.
|
|
241
|
+
* - Widget publico: vale para a conversa deste aparelho. Sem conversa ainda, fica guardado e sai
|
|
242
|
+
* sozinho depois da primeira mensagem (`pendente: true`).
|
|
243
|
+
*
|
|
244
|
+
* O mesmo token registrado de novo muda de dono: num aparelho compartilhado, so quem entrou por
|
|
245
|
+
* ultimo recebe. Ao sair da conta, chame `removerPush(token)`.
|
|
246
|
+
*/
|
|
247
|
+
registrarPush(opcoes: RegistrarPushOptions): Promise<RegistrarPushResult>;
|
|
248
|
+
/** Desliga a notificacao neste aparelho (ex.: ao sair da conta no app). */
|
|
249
|
+
removerPush(token: string): Promise<RegistrarPushResult>;
|
|
250
|
+
/**
|
|
251
|
+
* Aviso do NAVEGADOR quando chega resposta com a aba escondida (Notification API).
|
|
252
|
+
*
|
|
253
|
+
* Chame dentro de um clique (ex.: botao "Avisar quando responderem"): o navegador so mostra o
|
|
254
|
+
* pedido de permissao em resposta a um gesto da pessoa. Funciona enquanto a pagina estiver aberta
|
|
255
|
+
* (em outra aba ou minimizada) e com `startPolling()` ligado; com a pagina FECHADA so o push de
|
|
256
|
+
* aplicativo (`registrarPush`) alcanca a pessoa.
|
|
257
|
+
*
|
|
258
|
+
* Devolve a permissao: 'granted' liga o aviso; 'denied'/'default' nao; 'indisponivel' quando o
|
|
259
|
+
* ambiente nao tem a API (app nativo, navegador antigo, iframe sem permissao).
|
|
260
|
+
*/
|
|
261
|
+
ativarNotificacaoNoNavegador(opcoes?: NotificacaoNavegadorOptions): Promise<NotificationPermission | 'indisponivel'>;
|
|
262
|
+
/** Desliga o aviso do navegador. */
|
|
263
|
+
desativarNotificacaoNoNavegador(): void;
|
|
264
|
+
/**
|
|
265
|
+
* Avisa que a pessoa esta com o chat na tela (o inbox mostra "online", e a notificacao no celular
|
|
266
|
+
* nao conta como nova o que ela ja viu). O `startPolling()` ja chama sozinho com a pagina
|
|
267
|
+
* visivel; em app nativo, chame enquanto a tela do chat estiver aberta (a cada ~20 s).
|
|
268
|
+
*/
|
|
269
|
+
marcarPresenca(): Promise<void>;
|
|
122
270
|
/** Stop polling */
|
|
123
271
|
stopPolling(): void;
|
|
124
272
|
/** Get current messages */
|
|
@@ -150,6 +298,16 @@ declare class MenuIAClient {
|
|
|
150
298
|
clearSession(): void;
|
|
151
299
|
/** Cleanup - call when component unmounts */
|
|
152
300
|
destroy(): void;
|
|
301
|
+
/** Registro guardado ate a 1a mensagem (widget publico). Falhou: fica para a proxima. */
|
|
302
|
+
private registrarPushPendente;
|
|
303
|
+
private enviarRegistroPush;
|
|
304
|
+
private paginaVisivel;
|
|
305
|
+
/** Resposta chegou pelo poll: com a aba escondida e o aviso ligado, mostra uma notificacao. */
|
|
306
|
+
private avisarNoNavegador;
|
|
307
|
+
private fecharAvisoNavegador;
|
|
308
|
+
private ouvirVisibilidade;
|
|
309
|
+
/** Voltou para a aba: o que estava avisado foi visto. */
|
|
310
|
+
private aoMudarVisibilidade;
|
|
153
311
|
private setStatus;
|
|
154
312
|
private getSessionKey;
|
|
155
313
|
private loadSession;
|
|
@@ -157,4 +315,4 @@ declare class MenuIAClient {
|
|
|
157
315
|
private saveSession;
|
|
158
316
|
}
|
|
159
317
|
|
|
160
|
-
export { type ChatMessage, type ChatResponse, type ConnectionStatus, MenuIAClient, type MenuIAConfig, type MessageAttachment, type SendMessageOptions, type StreamEvent, type WidgetSession };
|
|
318
|
+
export { type ChatMessage, type ChatResponse, type ConnectionStatus, type InteractiveButton, type InteractivePayload, MenuIAClient, type MenuIAConfig, type MessageAttachment, type NotificacaoNavegadorOptions, type RegistrarPushOptions, type RegistrarPushResult, type SendMessageOptions, type StreamEvent, type WidgetSession };
|
package/dist/index.js
CHANGED
|
@@ -33,7 +33,20 @@ var MenuIAClient = class {
|
|
|
33
33
|
this.pollInterval = null;
|
|
34
34
|
this.lastMessageCount = 0;
|
|
35
35
|
this.resolvedAgentId = null;
|
|
36
|
+
/** Aviso do navegador ligado (ativarNotificacaoNoNavegador) e quantas chegaram com a aba escondida. */
|
|
37
|
+
this.notifNavegador = null;
|
|
38
|
+
this.naoVistasNavegador = 0;
|
|
39
|
+
this.avisoNavegador = null;
|
|
40
|
+
this.ultimaPresenca = 0;
|
|
41
|
+
this.ouvindoVisibilidade = false;
|
|
36
42
|
this._proactivePollInterval = null;
|
|
43
|
+
/** Voltou para a aba: o que estava avisado foi visto. */
|
|
44
|
+
this.aoMudarVisibilidade = () => {
|
|
45
|
+
if (document.visibilityState !== "visible") return;
|
|
46
|
+
this.naoVistasNavegador = 0;
|
|
47
|
+
this.fecharAvisoNavegador();
|
|
48
|
+
void this.marcarPresenca();
|
|
49
|
+
};
|
|
37
50
|
if (!config.widgetId && !config.agentId) {
|
|
38
51
|
throw new Error("[MenuIA] widgetId ou agentId e obrigatorio");
|
|
39
52
|
}
|
|
@@ -96,7 +109,9 @@ var MenuIAClient = class {
|
|
|
96
109
|
createdAt: m.createdAt,
|
|
97
110
|
mediaUrl: m.mediaUrl,
|
|
98
111
|
mediaType: m.mediaType,
|
|
99
|
-
authorName: m.authorName
|
|
112
|
+
authorName: m.authorName,
|
|
113
|
+
// Botoes / lista / carrossel: sem repassar, o app so teria a versao em texto (`content`).
|
|
114
|
+
interactive: m.interactive
|
|
100
115
|
}));
|
|
101
116
|
this.lastMessageCount = this.session.messages.length;
|
|
102
117
|
}
|
|
@@ -128,6 +143,9 @@ var MenuIAClient = class {
|
|
|
128
143
|
channel: this.config.channel,
|
|
129
144
|
sessionId: this.session.sessionId,
|
|
130
145
|
metadata: {
|
|
146
|
+
// Widget PRIVADO: o token prova QUEM escreve em cada mensagem (as ferramentas de conta do
|
|
147
|
+
// cliente dependem disso). Quem já manda o próprio `metadata.widgetSession` continua mandando.
|
|
148
|
+
...this.config.sessionToken ? { widgetSession: this.config.sessionToken } : {},
|
|
131
149
|
...this.config.metadata,
|
|
132
150
|
widgetId: this.getWidgetId(),
|
|
133
151
|
customData: this.config.customFields
|
|
@@ -172,6 +190,7 @@ var MenuIAClient = class {
|
|
|
172
190
|
this.saveSession();
|
|
173
191
|
this.setStatus("connected");
|
|
174
192
|
this.config.onMessage?.(assistantMsg);
|
|
193
|
+
void this.registrarPushPendente();
|
|
175
194
|
return data;
|
|
176
195
|
} catch (error) {
|
|
177
196
|
this.setStatus("error");
|
|
@@ -180,6 +199,13 @@ var MenuIAClient = class {
|
|
|
180
199
|
throw err;
|
|
181
200
|
}
|
|
182
201
|
}
|
|
202
|
+
/**
|
|
203
|
+
* Troca o token de sessão do widget privado (o servidor do site emite um novo antes de o anterior
|
|
204
|
+
* vencer). Vale para as próximas chamadas; a conversa continua a mesma.
|
|
205
|
+
*/
|
|
206
|
+
setSessionToken(token) {
|
|
207
|
+
if (typeof token === "string" && token.length > 20 && token.length < 4096) this.config.sessionToken = token;
|
|
208
|
+
}
|
|
183
209
|
/** Send a message and receive streaming response */
|
|
184
210
|
async sendMessageStream(options, onToken) {
|
|
185
211
|
this.setStatus("connecting");
|
|
@@ -191,6 +217,9 @@ var MenuIAClient = class {
|
|
|
191
217
|
channel: this.config.channel,
|
|
192
218
|
sessionId: this.session.sessionId,
|
|
193
219
|
metadata: {
|
|
220
|
+
// Widget PRIVADO: o token prova QUEM escreve em cada mensagem (as ferramentas de conta do
|
|
221
|
+
// cliente dependem disso). Quem já manda o próprio `metadata.widgetSession` continua mandando.
|
|
222
|
+
...this.config.sessionToken ? { widgetSession: this.config.sessionToken } : {},
|
|
194
223
|
...this.config.metadata,
|
|
195
224
|
widgetId: this.getWidgetId(),
|
|
196
225
|
customData: this.config.customFields
|
|
@@ -268,6 +297,7 @@ var MenuIAClient = class {
|
|
|
268
297
|
this.session.messages.push(assistantMsg);
|
|
269
298
|
this.saveSession();
|
|
270
299
|
this.config.onMessage?.(assistantMsg);
|
|
300
|
+
void this.registrarPushPendente();
|
|
271
301
|
return responseData;
|
|
272
302
|
} catch (error) {
|
|
273
303
|
this.setStatus("error");
|
|
@@ -299,7 +329,8 @@ var MenuIAClient = class {
|
|
|
299
329
|
// ⚠️ O endpoint devolve `mediaName` e o mapeamento o descartava: anexo recarregado do
|
|
300
330
|
// historico aparecia sem o nome do arquivo, mesmo com o nome gravado no banco.
|
|
301
331
|
mediaName: m.mediaName,
|
|
302
|
-
authorName: m.authorName
|
|
332
|
+
authorName: m.authorName,
|
|
333
|
+
interactive: m.interactive
|
|
303
334
|
}));
|
|
304
335
|
if (messages.length) {
|
|
305
336
|
this.session.messages = messages;
|
|
@@ -322,12 +353,104 @@ var MenuIAClient = class {
|
|
|
322
353
|
for (const msg of newMessages) {
|
|
323
354
|
if (msg.role === "assistant") {
|
|
324
355
|
this.config.onMessage?.(msg);
|
|
356
|
+
this.avisarNoNavegador(msg);
|
|
325
357
|
}
|
|
326
358
|
}
|
|
327
359
|
this.lastMessageCount = messages.length;
|
|
328
360
|
}
|
|
361
|
+
if (this.paginaVisivel()) void this.marcarPresenca();
|
|
329
362
|
}, intervalMs);
|
|
330
363
|
}
|
|
364
|
+
// =====================
|
|
365
|
+
// NOTIFICACOES
|
|
366
|
+
// =====================
|
|
367
|
+
/**
|
|
368
|
+
* Registra este aparelho para receber notificacao quando a equipe ou a IA responder no chat,
|
|
369
|
+
* mesmo com o app fechado. O envio usa a credencial do DONO do widget (painel > Notificacoes do
|
|
370
|
+
* chat); o app so entrega o token do aparelho.
|
|
371
|
+
*
|
|
372
|
+
* - Widget PRIVADO: vale para a PESSOA (identidade do token de sessao) em todas as conversas dela.
|
|
373
|
+
* - Widget publico: vale para a conversa deste aparelho. Sem conversa ainda, fica guardado e sai
|
|
374
|
+
* sozinho depois da primeira mensagem (`pendente: true`).
|
|
375
|
+
*
|
|
376
|
+
* O mesmo token registrado de novo muda de dono: num aparelho compartilhado, so quem entrou por
|
|
377
|
+
* ultimo recebe. Ao sair da conta, chame `removerPush(token)`.
|
|
378
|
+
*/
|
|
379
|
+
async registrarPush(opcoes) {
|
|
380
|
+
if (!this.config.widgetId) throw new Error("[MenuIA] registrarPush exige widgetId");
|
|
381
|
+
const tipo = String(opcoes?.tipo || "").toLowerCase();
|
|
382
|
+
const token = String(opcoes?.token || "").trim();
|
|
383
|
+
if (!token) throw new Error("[MenuIA] registrarPush: informe o token do aparelho");
|
|
384
|
+
if (tipo !== "fcm" && tipo !== "expo") throw new Error("[MenuIA] registrarPush: tipo deve ser 'fcm' ou 'expo'");
|
|
385
|
+
const pedido = { tipo, token, ...opcoes.plataforma ? { plataforma: opcoes.plataforma } : {} };
|
|
386
|
+
await this.ensureSession();
|
|
387
|
+
if (!this.config.sessionToken && !this.session.conversationId) {
|
|
388
|
+
this.session.pushPendente = pedido;
|
|
389
|
+
this.saveSession();
|
|
390
|
+
return { ok: true, pendente: true };
|
|
391
|
+
}
|
|
392
|
+
return this.enviarRegistroPush("push", pedido);
|
|
393
|
+
}
|
|
394
|
+
/** Desliga a notificacao neste aparelho (ex.: ao sair da conta no app). */
|
|
395
|
+
async removerPush(token) {
|
|
396
|
+
if (!this.config.widgetId) throw new Error("[MenuIA] removerPush exige widgetId");
|
|
397
|
+
if (this.session.pushPendente?.token === token) {
|
|
398
|
+
delete this.session.pushPendente;
|
|
399
|
+
this.saveSession();
|
|
400
|
+
}
|
|
401
|
+
if (!this.config.sessionToken && !this.session.conversationId) return { ok: true };
|
|
402
|
+
return this.enviarRegistroPush("push/remove", { token });
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Aviso do NAVEGADOR quando chega resposta com a aba escondida (Notification API).
|
|
406
|
+
*
|
|
407
|
+
* Chame dentro de um clique (ex.: botao "Avisar quando responderem"): o navegador so mostra o
|
|
408
|
+
* pedido de permissao em resposta a um gesto da pessoa. Funciona enquanto a pagina estiver aberta
|
|
409
|
+
* (em outra aba ou minimizada) e com `startPolling()` ligado; com a pagina FECHADA so o push de
|
|
410
|
+
* aplicativo (`registrarPush`) alcanca a pessoa.
|
|
411
|
+
*
|
|
412
|
+
* Devolve a permissao: 'granted' liga o aviso; 'denied'/'default' nao; 'indisponivel' quando o
|
|
413
|
+
* ambiente nao tem a API (app nativo, navegador antigo, iframe sem permissao).
|
|
414
|
+
*/
|
|
415
|
+
async ativarNotificacaoNoNavegador(opcoes = {}) {
|
|
416
|
+
const N = globalThis.Notification;
|
|
417
|
+
if (typeof window === "undefined" || !N) return "indisponivel";
|
|
418
|
+
let permissao = N.permission;
|
|
419
|
+
if (permissao === "default") {
|
|
420
|
+
try {
|
|
421
|
+
permissao = await N.requestPermission();
|
|
422
|
+
} catch {
|
|
423
|
+
return "indisponivel";
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
this.notifNavegador = permissao === "granted" ? { ...opcoes } : null;
|
|
427
|
+
if (this.notifNavegador) this.ouvirVisibilidade();
|
|
428
|
+
return permissao;
|
|
429
|
+
}
|
|
430
|
+
/** Desliga o aviso do navegador. */
|
|
431
|
+
desativarNotificacaoNoNavegador() {
|
|
432
|
+
this.notifNavegador = null;
|
|
433
|
+
this.fecharAvisoNavegador();
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Avisa que a pessoa esta com o chat na tela (o inbox mostra "online", e a notificacao no celular
|
|
437
|
+
* nao conta como nova o que ela ja viu). O `startPolling()` ja chama sozinho com a pagina
|
|
438
|
+
* visivel; em app nativo, chame enquanto a tela do chat estiver aberta (a cada ~20 s).
|
|
439
|
+
*/
|
|
440
|
+
async marcarPresenca() {
|
|
441
|
+
const conversationId = this.session.conversationId;
|
|
442
|
+
if (!conversationId) return;
|
|
443
|
+
if (Date.now() - this.ultimaPresenca < 15e3) return;
|
|
444
|
+
this.ultimaPresenca = Date.now();
|
|
445
|
+
try {
|
|
446
|
+
await fetch(`${this.config.apiUrl}/widget/heartbeat`, {
|
|
447
|
+
method: "POST",
|
|
448
|
+
headers: { "Content-Type": "application/json" },
|
|
449
|
+
body: JSON.stringify({ conversationId })
|
|
450
|
+
});
|
|
451
|
+
} catch {
|
|
452
|
+
}
|
|
453
|
+
}
|
|
331
454
|
/** Stop polling */
|
|
332
455
|
stopPolling() {
|
|
333
456
|
if (this.pollInterval) {
|
|
@@ -376,7 +499,8 @@ var MenuIAClient = class {
|
|
|
376
499
|
createdAt: m.createdAt,
|
|
377
500
|
authorName: m.authorName,
|
|
378
501
|
mediaType: m.mediaType,
|
|
379
|
-
mediaUrl: m.mediaUrl
|
|
502
|
+
mediaUrl: m.mediaUrl,
|
|
503
|
+
interactive: m.interactive
|
|
380
504
|
}));
|
|
381
505
|
this.lastMessageCount = this.session.messages.length;
|
|
382
506
|
this.saveSession();
|
|
@@ -421,10 +545,88 @@ var MenuIAClient = class {
|
|
|
421
545
|
destroy() {
|
|
422
546
|
this.stopPolling();
|
|
423
547
|
this.stopProactivePolling();
|
|
548
|
+
this.fecharAvisoNavegador();
|
|
549
|
+
if (this.ouvindoVisibilidade && typeof document !== "undefined") {
|
|
550
|
+
document.removeEventListener("visibilitychange", this.aoMudarVisibilidade);
|
|
551
|
+
this.ouvindoVisibilidade = false;
|
|
552
|
+
}
|
|
424
553
|
}
|
|
425
554
|
// =====================
|
|
426
555
|
// PRIVATE
|
|
427
556
|
// =====================
|
|
557
|
+
/** Registro guardado ate a 1a mensagem (widget publico). Falhou: fica para a proxima. */
|
|
558
|
+
async registrarPushPendente() {
|
|
559
|
+
const p = this.session.pushPendente;
|
|
560
|
+
if (!p || !this.session.conversationId) return;
|
|
561
|
+
const r = await this.enviarRegistroPush("push", p);
|
|
562
|
+
if (r.ok) {
|
|
563
|
+
delete this.session.pushPendente;
|
|
564
|
+
this.saveSession();
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
async enviarRegistroPush(rota, pedido) {
|
|
568
|
+
try {
|
|
569
|
+
const response = await fetch(`${this.config.apiUrl}/widget/${this.config.widgetId}/${rota}`, {
|
|
570
|
+
method: "POST",
|
|
571
|
+
headers: {
|
|
572
|
+
"Content-Type": "application/json",
|
|
573
|
+
// Widget privado: quem diz QUEM e o token assinado pelo servidor do site, no header.
|
|
574
|
+
...this.config.sessionToken ? { "x-widget-session": this.config.sessionToken } : {}
|
|
575
|
+
},
|
|
576
|
+
// Widget publico: a prova e a da propria conversa (sessionId e o token que a sessao devolveu).
|
|
577
|
+
body: JSON.stringify({
|
|
578
|
+
...pedido,
|
|
579
|
+
sessionId: this.session.sessionId,
|
|
580
|
+
...this.session.widgetToken ? { widgetToken: this.session.widgetToken } : {}
|
|
581
|
+
})
|
|
582
|
+
});
|
|
583
|
+
if (response.ok) return { ok: true };
|
|
584
|
+
const err = await response.json().catch(() => ({}));
|
|
585
|
+
const erro = String(err?.message || `HTTP ${response.status}`);
|
|
586
|
+
this.config.onError?.(new Error(`[MenuIA] notificacao: ${erro}`));
|
|
587
|
+
return { ok: false, erro };
|
|
588
|
+
} catch (e) {
|
|
589
|
+
return { ok: false, erro: e instanceof Error ? e.message : String(e) };
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
paginaVisivel() {
|
|
593
|
+
return typeof document !== "undefined" && document.visibilityState === "visible";
|
|
594
|
+
}
|
|
595
|
+
/** Resposta chegou pelo poll: com a aba escondida e o aviso ligado, mostra uma notificacao. */
|
|
596
|
+
avisarNoNavegador(msg) {
|
|
597
|
+
const N = globalThis.Notification;
|
|
598
|
+
if (!this.notifNavegador || !N || N.permission !== "granted") return;
|
|
599
|
+
if (typeof document === "undefined" || document.visibilityState !== "hidden") return;
|
|
600
|
+
this.naoVistasNavegador += 1;
|
|
601
|
+
const n = this.naoVistasNavegador;
|
|
602
|
+
const base = this.notifNavegador.titulo || "Nova mensagem";
|
|
603
|
+
const titulo = n > 1 ? `${base} \u2014 ${n} mensagens novas` : base;
|
|
604
|
+
try {
|
|
605
|
+
this.fecharAvisoNavegador();
|
|
606
|
+
const aviso = new N(titulo, { body: previaDaMensagem(msg), tag: `menuia-chat-${this.getWidgetId()}`, icon: this.notifNavegador.icone });
|
|
607
|
+
aviso.onclick = () => {
|
|
608
|
+
try {
|
|
609
|
+
window.focus();
|
|
610
|
+
} catch {
|
|
611
|
+
}
|
|
612
|
+
aviso.close();
|
|
613
|
+
};
|
|
614
|
+
this.avisoNavegador = aviso;
|
|
615
|
+
} catch {
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
fecharAvisoNavegador() {
|
|
619
|
+
try {
|
|
620
|
+
this.avisoNavegador?.close();
|
|
621
|
+
} catch {
|
|
622
|
+
}
|
|
623
|
+
this.avisoNavegador = null;
|
|
624
|
+
}
|
|
625
|
+
ouvirVisibilidade() {
|
|
626
|
+
if (this.ouvindoVisibilidade || typeof document === "undefined") return;
|
|
627
|
+
document.addEventListener("visibilitychange", this.aoMudarVisibilidade);
|
|
628
|
+
this.ouvindoVisibilidade = true;
|
|
629
|
+
}
|
|
428
630
|
setStatus(status) {
|
|
429
631
|
if (this.status !== status) {
|
|
430
632
|
this.status = status;
|
|
@@ -473,6 +675,19 @@ var MenuIAClient = class {
|
|
|
473
675
|
}
|
|
474
676
|
}
|
|
475
677
|
};
|
|
678
|
+
function previaDaMensagem(msg) {
|
|
679
|
+
let t = String(msg.content || "").trim();
|
|
680
|
+
if (!t) {
|
|
681
|
+
const tipo = String(msg.mediaType || "").toLowerCase();
|
|
682
|
+
if (tipo.includes("image")) return "Imagem";
|
|
683
|
+
if (tipo.includes("audio")) return "Audio";
|
|
684
|
+
if (tipo.includes("video")) return "Video";
|
|
685
|
+
return msg.mediaUrl ? "Arquivo" : "Mensagem nova";
|
|
686
|
+
}
|
|
687
|
+
if (t.startsWith("[INTERACTIVE]")) return "Opcoes para escolher no chat";
|
|
688
|
+
t = t.replace(/\[(?:BUTTON|BOTAO|BTN):([^:\]]+):[^\]]*\]/gi, "$1").replace(/[*_~`]+/g, "").replace(/https?:\/\/\S+/g, "link").replace(/\s+/g, " ").trim();
|
|
689
|
+
return t.length > 120 ? `${t.slice(0, 119).trimEnd()}\u2026` : t || "Mensagem nova";
|
|
690
|
+
}
|
|
476
691
|
// Annotate the CommonJS export names for ESM import in node:
|
|
477
692
|
0 && (module.exports = {
|
|
478
693
|
MenuIAClient
|
package/dist/index.mjs
CHANGED
|
@@ -7,7 +7,20 @@ var MenuIAClient = class {
|
|
|
7
7
|
this.pollInterval = null;
|
|
8
8
|
this.lastMessageCount = 0;
|
|
9
9
|
this.resolvedAgentId = null;
|
|
10
|
+
/** Aviso do navegador ligado (ativarNotificacaoNoNavegador) e quantas chegaram com a aba escondida. */
|
|
11
|
+
this.notifNavegador = null;
|
|
12
|
+
this.naoVistasNavegador = 0;
|
|
13
|
+
this.avisoNavegador = null;
|
|
14
|
+
this.ultimaPresenca = 0;
|
|
15
|
+
this.ouvindoVisibilidade = false;
|
|
10
16
|
this._proactivePollInterval = null;
|
|
17
|
+
/** Voltou para a aba: o que estava avisado foi visto. */
|
|
18
|
+
this.aoMudarVisibilidade = () => {
|
|
19
|
+
if (document.visibilityState !== "visible") return;
|
|
20
|
+
this.naoVistasNavegador = 0;
|
|
21
|
+
this.fecharAvisoNavegador();
|
|
22
|
+
void this.marcarPresenca();
|
|
23
|
+
};
|
|
11
24
|
if (!config.widgetId && !config.agentId) {
|
|
12
25
|
throw new Error("[MenuIA] widgetId ou agentId e obrigatorio");
|
|
13
26
|
}
|
|
@@ -70,7 +83,9 @@ var MenuIAClient = class {
|
|
|
70
83
|
createdAt: m.createdAt,
|
|
71
84
|
mediaUrl: m.mediaUrl,
|
|
72
85
|
mediaType: m.mediaType,
|
|
73
|
-
authorName: m.authorName
|
|
86
|
+
authorName: m.authorName,
|
|
87
|
+
// Botoes / lista / carrossel: sem repassar, o app so teria a versao em texto (`content`).
|
|
88
|
+
interactive: m.interactive
|
|
74
89
|
}));
|
|
75
90
|
this.lastMessageCount = this.session.messages.length;
|
|
76
91
|
}
|
|
@@ -102,6 +117,9 @@ var MenuIAClient = class {
|
|
|
102
117
|
channel: this.config.channel,
|
|
103
118
|
sessionId: this.session.sessionId,
|
|
104
119
|
metadata: {
|
|
120
|
+
// Widget PRIVADO: o token prova QUEM escreve em cada mensagem (as ferramentas de conta do
|
|
121
|
+
// cliente dependem disso). Quem já manda o próprio `metadata.widgetSession` continua mandando.
|
|
122
|
+
...this.config.sessionToken ? { widgetSession: this.config.sessionToken } : {},
|
|
105
123
|
...this.config.metadata,
|
|
106
124
|
widgetId: this.getWidgetId(),
|
|
107
125
|
customData: this.config.customFields
|
|
@@ -146,6 +164,7 @@ var MenuIAClient = class {
|
|
|
146
164
|
this.saveSession();
|
|
147
165
|
this.setStatus("connected");
|
|
148
166
|
this.config.onMessage?.(assistantMsg);
|
|
167
|
+
void this.registrarPushPendente();
|
|
149
168
|
return data;
|
|
150
169
|
} catch (error) {
|
|
151
170
|
this.setStatus("error");
|
|
@@ -154,6 +173,13 @@ var MenuIAClient = class {
|
|
|
154
173
|
throw err;
|
|
155
174
|
}
|
|
156
175
|
}
|
|
176
|
+
/**
|
|
177
|
+
* Troca o token de sessão do widget privado (o servidor do site emite um novo antes de o anterior
|
|
178
|
+
* vencer). Vale para as próximas chamadas; a conversa continua a mesma.
|
|
179
|
+
*/
|
|
180
|
+
setSessionToken(token) {
|
|
181
|
+
if (typeof token === "string" && token.length > 20 && token.length < 4096) this.config.sessionToken = token;
|
|
182
|
+
}
|
|
157
183
|
/** Send a message and receive streaming response */
|
|
158
184
|
async sendMessageStream(options, onToken) {
|
|
159
185
|
this.setStatus("connecting");
|
|
@@ -165,6 +191,9 @@ var MenuIAClient = class {
|
|
|
165
191
|
channel: this.config.channel,
|
|
166
192
|
sessionId: this.session.sessionId,
|
|
167
193
|
metadata: {
|
|
194
|
+
// Widget PRIVADO: o token prova QUEM escreve em cada mensagem (as ferramentas de conta do
|
|
195
|
+
// cliente dependem disso). Quem já manda o próprio `metadata.widgetSession` continua mandando.
|
|
196
|
+
...this.config.sessionToken ? { widgetSession: this.config.sessionToken } : {},
|
|
168
197
|
...this.config.metadata,
|
|
169
198
|
widgetId: this.getWidgetId(),
|
|
170
199
|
customData: this.config.customFields
|
|
@@ -242,6 +271,7 @@ var MenuIAClient = class {
|
|
|
242
271
|
this.session.messages.push(assistantMsg);
|
|
243
272
|
this.saveSession();
|
|
244
273
|
this.config.onMessage?.(assistantMsg);
|
|
274
|
+
void this.registrarPushPendente();
|
|
245
275
|
return responseData;
|
|
246
276
|
} catch (error) {
|
|
247
277
|
this.setStatus("error");
|
|
@@ -273,7 +303,8 @@ var MenuIAClient = class {
|
|
|
273
303
|
// ⚠️ O endpoint devolve `mediaName` e o mapeamento o descartava: anexo recarregado do
|
|
274
304
|
// historico aparecia sem o nome do arquivo, mesmo com o nome gravado no banco.
|
|
275
305
|
mediaName: m.mediaName,
|
|
276
|
-
authorName: m.authorName
|
|
306
|
+
authorName: m.authorName,
|
|
307
|
+
interactive: m.interactive
|
|
277
308
|
}));
|
|
278
309
|
if (messages.length) {
|
|
279
310
|
this.session.messages = messages;
|
|
@@ -296,12 +327,104 @@ var MenuIAClient = class {
|
|
|
296
327
|
for (const msg of newMessages) {
|
|
297
328
|
if (msg.role === "assistant") {
|
|
298
329
|
this.config.onMessage?.(msg);
|
|
330
|
+
this.avisarNoNavegador(msg);
|
|
299
331
|
}
|
|
300
332
|
}
|
|
301
333
|
this.lastMessageCount = messages.length;
|
|
302
334
|
}
|
|
335
|
+
if (this.paginaVisivel()) void this.marcarPresenca();
|
|
303
336
|
}, intervalMs);
|
|
304
337
|
}
|
|
338
|
+
// =====================
|
|
339
|
+
// NOTIFICACOES
|
|
340
|
+
// =====================
|
|
341
|
+
/**
|
|
342
|
+
* Registra este aparelho para receber notificacao quando a equipe ou a IA responder no chat,
|
|
343
|
+
* mesmo com o app fechado. O envio usa a credencial do DONO do widget (painel > Notificacoes do
|
|
344
|
+
* chat); o app so entrega o token do aparelho.
|
|
345
|
+
*
|
|
346
|
+
* - Widget PRIVADO: vale para a PESSOA (identidade do token de sessao) em todas as conversas dela.
|
|
347
|
+
* - Widget publico: vale para a conversa deste aparelho. Sem conversa ainda, fica guardado e sai
|
|
348
|
+
* sozinho depois da primeira mensagem (`pendente: true`).
|
|
349
|
+
*
|
|
350
|
+
* O mesmo token registrado de novo muda de dono: num aparelho compartilhado, so quem entrou por
|
|
351
|
+
* ultimo recebe. Ao sair da conta, chame `removerPush(token)`.
|
|
352
|
+
*/
|
|
353
|
+
async registrarPush(opcoes) {
|
|
354
|
+
if (!this.config.widgetId) throw new Error("[MenuIA] registrarPush exige widgetId");
|
|
355
|
+
const tipo = String(opcoes?.tipo || "").toLowerCase();
|
|
356
|
+
const token = String(opcoes?.token || "").trim();
|
|
357
|
+
if (!token) throw new Error("[MenuIA] registrarPush: informe o token do aparelho");
|
|
358
|
+
if (tipo !== "fcm" && tipo !== "expo") throw new Error("[MenuIA] registrarPush: tipo deve ser 'fcm' ou 'expo'");
|
|
359
|
+
const pedido = { tipo, token, ...opcoes.plataforma ? { plataforma: opcoes.plataforma } : {} };
|
|
360
|
+
await this.ensureSession();
|
|
361
|
+
if (!this.config.sessionToken && !this.session.conversationId) {
|
|
362
|
+
this.session.pushPendente = pedido;
|
|
363
|
+
this.saveSession();
|
|
364
|
+
return { ok: true, pendente: true };
|
|
365
|
+
}
|
|
366
|
+
return this.enviarRegistroPush("push", pedido);
|
|
367
|
+
}
|
|
368
|
+
/** Desliga a notificacao neste aparelho (ex.: ao sair da conta no app). */
|
|
369
|
+
async removerPush(token) {
|
|
370
|
+
if (!this.config.widgetId) throw new Error("[MenuIA] removerPush exige widgetId");
|
|
371
|
+
if (this.session.pushPendente?.token === token) {
|
|
372
|
+
delete this.session.pushPendente;
|
|
373
|
+
this.saveSession();
|
|
374
|
+
}
|
|
375
|
+
if (!this.config.sessionToken && !this.session.conversationId) return { ok: true };
|
|
376
|
+
return this.enviarRegistroPush("push/remove", { token });
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Aviso do NAVEGADOR quando chega resposta com a aba escondida (Notification API).
|
|
380
|
+
*
|
|
381
|
+
* Chame dentro de um clique (ex.: botao "Avisar quando responderem"): o navegador so mostra o
|
|
382
|
+
* pedido de permissao em resposta a um gesto da pessoa. Funciona enquanto a pagina estiver aberta
|
|
383
|
+
* (em outra aba ou minimizada) e com `startPolling()` ligado; com a pagina FECHADA so o push de
|
|
384
|
+
* aplicativo (`registrarPush`) alcanca a pessoa.
|
|
385
|
+
*
|
|
386
|
+
* Devolve a permissao: 'granted' liga o aviso; 'denied'/'default' nao; 'indisponivel' quando o
|
|
387
|
+
* ambiente nao tem a API (app nativo, navegador antigo, iframe sem permissao).
|
|
388
|
+
*/
|
|
389
|
+
async ativarNotificacaoNoNavegador(opcoes = {}) {
|
|
390
|
+
const N = globalThis.Notification;
|
|
391
|
+
if (typeof window === "undefined" || !N) return "indisponivel";
|
|
392
|
+
let permissao = N.permission;
|
|
393
|
+
if (permissao === "default") {
|
|
394
|
+
try {
|
|
395
|
+
permissao = await N.requestPermission();
|
|
396
|
+
} catch {
|
|
397
|
+
return "indisponivel";
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
this.notifNavegador = permissao === "granted" ? { ...opcoes } : null;
|
|
401
|
+
if (this.notifNavegador) this.ouvirVisibilidade();
|
|
402
|
+
return permissao;
|
|
403
|
+
}
|
|
404
|
+
/** Desliga o aviso do navegador. */
|
|
405
|
+
desativarNotificacaoNoNavegador() {
|
|
406
|
+
this.notifNavegador = null;
|
|
407
|
+
this.fecharAvisoNavegador();
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Avisa que a pessoa esta com o chat na tela (o inbox mostra "online", e a notificacao no celular
|
|
411
|
+
* nao conta como nova o que ela ja viu). O `startPolling()` ja chama sozinho com a pagina
|
|
412
|
+
* visivel; em app nativo, chame enquanto a tela do chat estiver aberta (a cada ~20 s).
|
|
413
|
+
*/
|
|
414
|
+
async marcarPresenca() {
|
|
415
|
+
const conversationId = this.session.conversationId;
|
|
416
|
+
if (!conversationId) return;
|
|
417
|
+
if (Date.now() - this.ultimaPresenca < 15e3) return;
|
|
418
|
+
this.ultimaPresenca = Date.now();
|
|
419
|
+
try {
|
|
420
|
+
await fetch(`${this.config.apiUrl}/widget/heartbeat`, {
|
|
421
|
+
method: "POST",
|
|
422
|
+
headers: { "Content-Type": "application/json" },
|
|
423
|
+
body: JSON.stringify({ conversationId })
|
|
424
|
+
});
|
|
425
|
+
} catch {
|
|
426
|
+
}
|
|
427
|
+
}
|
|
305
428
|
/** Stop polling */
|
|
306
429
|
stopPolling() {
|
|
307
430
|
if (this.pollInterval) {
|
|
@@ -350,7 +473,8 @@ var MenuIAClient = class {
|
|
|
350
473
|
createdAt: m.createdAt,
|
|
351
474
|
authorName: m.authorName,
|
|
352
475
|
mediaType: m.mediaType,
|
|
353
|
-
mediaUrl: m.mediaUrl
|
|
476
|
+
mediaUrl: m.mediaUrl,
|
|
477
|
+
interactive: m.interactive
|
|
354
478
|
}));
|
|
355
479
|
this.lastMessageCount = this.session.messages.length;
|
|
356
480
|
this.saveSession();
|
|
@@ -395,10 +519,88 @@ var MenuIAClient = class {
|
|
|
395
519
|
destroy() {
|
|
396
520
|
this.stopPolling();
|
|
397
521
|
this.stopProactivePolling();
|
|
522
|
+
this.fecharAvisoNavegador();
|
|
523
|
+
if (this.ouvindoVisibilidade && typeof document !== "undefined") {
|
|
524
|
+
document.removeEventListener("visibilitychange", this.aoMudarVisibilidade);
|
|
525
|
+
this.ouvindoVisibilidade = false;
|
|
526
|
+
}
|
|
398
527
|
}
|
|
399
528
|
// =====================
|
|
400
529
|
// PRIVATE
|
|
401
530
|
// =====================
|
|
531
|
+
/** Registro guardado ate a 1a mensagem (widget publico). Falhou: fica para a proxima. */
|
|
532
|
+
async registrarPushPendente() {
|
|
533
|
+
const p = this.session.pushPendente;
|
|
534
|
+
if (!p || !this.session.conversationId) return;
|
|
535
|
+
const r = await this.enviarRegistroPush("push", p);
|
|
536
|
+
if (r.ok) {
|
|
537
|
+
delete this.session.pushPendente;
|
|
538
|
+
this.saveSession();
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
async enviarRegistroPush(rota, pedido) {
|
|
542
|
+
try {
|
|
543
|
+
const response = await fetch(`${this.config.apiUrl}/widget/${this.config.widgetId}/${rota}`, {
|
|
544
|
+
method: "POST",
|
|
545
|
+
headers: {
|
|
546
|
+
"Content-Type": "application/json",
|
|
547
|
+
// Widget privado: quem diz QUEM e o token assinado pelo servidor do site, no header.
|
|
548
|
+
...this.config.sessionToken ? { "x-widget-session": this.config.sessionToken } : {}
|
|
549
|
+
},
|
|
550
|
+
// Widget publico: a prova e a da propria conversa (sessionId e o token que a sessao devolveu).
|
|
551
|
+
body: JSON.stringify({
|
|
552
|
+
...pedido,
|
|
553
|
+
sessionId: this.session.sessionId,
|
|
554
|
+
...this.session.widgetToken ? { widgetToken: this.session.widgetToken } : {}
|
|
555
|
+
})
|
|
556
|
+
});
|
|
557
|
+
if (response.ok) return { ok: true };
|
|
558
|
+
const err = await response.json().catch(() => ({}));
|
|
559
|
+
const erro = String(err?.message || `HTTP ${response.status}`);
|
|
560
|
+
this.config.onError?.(new Error(`[MenuIA] notificacao: ${erro}`));
|
|
561
|
+
return { ok: false, erro };
|
|
562
|
+
} catch (e) {
|
|
563
|
+
return { ok: false, erro: e instanceof Error ? e.message : String(e) };
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
paginaVisivel() {
|
|
567
|
+
return typeof document !== "undefined" && document.visibilityState === "visible";
|
|
568
|
+
}
|
|
569
|
+
/** Resposta chegou pelo poll: com a aba escondida e o aviso ligado, mostra uma notificacao. */
|
|
570
|
+
avisarNoNavegador(msg) {
|
|
571
|
+
const N = globalThis.Notification;
|
|
572
|
+
if (!this.notifNavegador || !N || N.permission !== "granted") return;
|
|
573
|
+
if (typeof document === "undefined" || document.visibilityState !== "hidden") return;
|
|
574
|
+
this.naoVistasNavegador += 1;
|
|
575
|
+
const n = this.naoVistasNavegador;
|
|
576
|
+
const base = this.notifNavegador.titulo || "Nova mensagem";
|
|
577
|
+
const titulo = n > 1 ? `${base} \u2014 ${n} mensagens novas` : base;
|
|
578
|
+
try {
|
|
579
|
+
this.fecharAvisoNavegador();
|
|
580
|
+
const aviso = new N(titulo, { body: previaDaMensagem(msg), tag: `menuia-chat-${this.getWidgetId()}`, icon: this.notifNavegador.icone });
|
|
581
|
+
aviso.onclick = () => {
|
|
582
|
+
try {
|
|
583
|
+
window.focus();
|
|
584
|
+
} catch {
|
|
585
|
+
}
|
|
586
|
+
aviso.close();
|
|
587
|
+
};
|
|
588
|
+
this.avisoNavegador = aviso;
|
|
589
|
+
} catch {
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
fecharAvisoNavegador() {
|
|
593
|
+
try {
|
|
594
|
+
this.avisoNavegador?.close();
|
|
595
|
+
} catch {
|
|
596
|
+
}
|
|
597
|
+
this.avisoNavegador = null;
|
|
598
|
+
}
|
|
599
|
+
ouvirVisibilidade() {
|
|
600
|
+
if (this.ouvindoVisibilidade || typeof document === "undefined") return;
|
|
601
|
+
document.addEventListener("visibilitychange", this.aoMudarVisibilidade);
|
|
602
|
+
this.ouvindoVisibilidade = true;
|
|
603
|
+
}
|
|
402
604
|
setStatus(status) {
|
|
403
605
|
if (this.status !== status) {
|
|
404
606
|
this.status = status;
|
|
@@ -447,6 +649,19 @@ var MenuIAClient = class {
|
|
|
447
649
|
}
|
|
448
650
|
}
|
|
449
651
|
};
|
|
652
|
+
function previaDaMensagem(msg) {
|
|
653
|
+
let t = String(msg.content || "").trim();
|
|
654
|
+
if (!t) {
|
|
655
|
+
const tipo = String(msg.mediaType || "").toLowerCase();
|
|
656
|
+
if (tipo.includes("image")) return "Imagem";
|
|
657
|
+
if (tipo.includes("audio")) return "Audio";
|
|
658
|
+
if (tipo.includes("video")) return "Video";
|
|
659
|
+
return msg.mediaUrl ? "Arquivo" : "Mensagem nova";
|
|
660
|
+
}
|
|
661
|
+
if (t.startsWith("[INTERACTIVE]")) return "Opcoes para escolher no chat";
|
|
662
|
+
t = t.replace(/\[(?:BUTTON|BOTAO|BTN):([^:\]]+):[^\]]*\]/gi, "$1").replace(/[*_~`]+/g, "").replace(/https?:\/\/\S+/g, "link").replace(/\s+/g, " ").trim();
|
|
663
|
+
return t.length > 120 ? `${t.slice(0, 119).trimEnd()}\u2026` : t || "Mensagem nova";
|
|
664
|
+
}
|
|
450
665
|
export {
|
|
451
666
|
MenuIAClient
|
|
452
667
|
};
|