@botozap/sdk 0.7.0 → 0.9.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/CHANGELOG.md +47 -0
- package/README.md +126 -0
- package/dist/index.cjs +163 -20
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +465 -19
- package/dist/index.d.ts +465 -19
- package/dist/index.js +158 -19
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,52 @@
|
|
|
1
1
|
# @botozap/sdk
|
|
2
2
|
|
|
3
|
+
## 0.9.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- Cover the API additions of 2026-09-29:
|
|
8
|
+
|
|
9
|
+
- SDK: `messages.sendInteractive` (button/list/cta_url in Cloud API shape, typed as `InteractivePayload`), `messages.sendLocation` and `messages.sendReaction` (target is the internal UUID or wamid of a received message; `emoji: ""` removes it; `SendResult.reaction` echoes target and action). `messages.list({ sort: "created_at" | "event_at" })`; `Message.source` (`MessageSource`), `created_at`, `event_at` and `Conversation.last_message`. `WEBHOOK_CATEGORIES` with the opt-in `app_messages` category; `WebhookDeliveryStatus` gains `limited`. `ai.providers.get()` types `providers` as `AiProviderInfo` with `accepts_new_credentials`; `AI_CREDENTIAL_PROVIDERS` (openai, anthropic). `BotoZapErrorCode`, `PLAN_ERROR_CODES` and `isPlanError` for `plan_restricted`, `free_form_limit_reached` and `free_number_cap`.
|
|
10
|
+
- CLI: `messages send-interactive`, `messages send-location`, `messages react` (`--remove`), `messages list --sort` and an ORIGEM column; help for `app_messages` and `limited`.
|
|
11
|
+
- MCP: `send_message` accepts `interactive`, `location` and `reaction`; `list_messages` accepts `sort`; `send_message` output includes `reaction`; delivery status `limited`; webhook tools document `app_messages`.
|
|
12
|
+
|
|
13
|
+
- ca116b8: Add authenticated account introspection through `boto.me.get()`. MCP initializes from `/me`, limits its tools to the credential scopes and environment, and declares tool safety annotations.
|
|
14
|
+
|
|
15
|
+
Deploy the BotoZap API with `GET /v1/me` before upgrading MCP. MCP startup fails closed when introspection is unavailable; it does not fall back to the complete tool catalog.
|
|
16
|
+
|
|
17
|
+
Compact MCP JSON responses and publish the validated schema projection for typed entities. Preserve business content and pagination, expose webhook signing secrets only at creation, and clarify tool identifiers and side effects.
|
|
18
|
+
|
|
19
|
+
Compatibility changes:
|
|
20
|
+
|
|
21
|
+
- Tools outside the credential scopes or supported environment are omitted from discovery. OAuth additionally requires the concrete API routes used by each tool; operations still pass through API authorization.
|
|
22
|
+
- In Streamable HTTP, a session caches its identity for 60 seconds. API keys remain bound to their original fingerprint. OAuth bearer changes trigger introspection and must preserve the account, environment, user, client and grant. Tools and event polls share the cache and concurrent refresh; API calls still authorize each operation.
|
|
23
|
+
- Typed MCP results now discard fields outside their schemas in both `structuredContent` and legacy JSON text. The reviewed endpoint responses have no identified public field removed by this change; `list_users.data[].id` and its `user_id` alias were already declared and remain available. Webhook `secret` is retained only in `create_webhook`; it is excluded from list/get/update results. `authorization_secret_id`, `private_trace` and `internal_debug` are concrete extras discarded by regression fixtures, not fields currently returned by the reviewed API presenters.
|
|
24
|
+
- Deploy and verify `GET /v1/me` on every supported API base URL **before publishing either SDK or MCP**. Versionless `npx @botozap/mcp` or `pnpm dlx @botozap/mcp` can pick up the new release immediately; delaying the API deploy would break their session initialization.
|
|
25
|
+
|
|
26
|
+
The field audit and ordered release checks are recorded in `docs/chatgpt-phase1-release.md`.
|
|
27
|
+
|
|
28
|
+
- ef10a36: Add optional `idempotencyKey` options to `messages.send`, `sendTemplate`, `sendMedia` and `conversations.reply`. Calls without this option retain their existing HTTP payload and behavior.
|
|
29
|
+
|
|
30
|
+
MCP send tools accept optional `idempotency_key`: call the read-only `prepare_send_intent` once before a new send, or reuse `draft.idempotency_key` returned by `stage_review_reply`. Keep the same key and payload after a timeout. Never generate a replacement key to bypass pending/conflicting sends. Existing tool calls remain valid without a key or preparation step and retain legacy behavior. New review UI sends always include a key; public API clients and ordinary SDK callers may also continue omitting the header.
|
|
31
|
+
|
|
32
|
+
Add an opt-in MCP Apps review panel (`BOTOZAP_MCP_UI_ENABLED=true`), thread entrypoint, Radar/history context, explicit confirmation and retry using the original intent. The UI bundle is packaged locally with no external assets. Deploy API idempotency support before upgrading these send tools. Plugin manifests are local candidates, not published directory listings.
|
|
33
|
+
|
|
34
|
+
- 9453f19: Support OAuth bearer credentials and rotating access-token providers in the SDK. MCP publishes protected-resource metadata, validates each request against account introspection, and binds OAuth sessions to the user, client, grant and account so token refresh preserves the connection.
|
|
35
|
+
|
|
36
|
+
Require current scopes and allowed routes for tools and background event reads. API-key authentication retains its existing behavior. Enable OAuth only after deploying the coordinated BotoZap authorization endpoints and grant policies.
|
|
37
|
+
|
|
38
|
+
### Patch Changes
|
|
39
|
+
|
|
40
|
+
- bc67b0c: Preserve the API's validated `outcome` and `retry` enums on SDK/MCP errors. Confirmed rejection releases the idempotency claim, so the same key can retry after backoff or correction. The review UI unlocks a confirmed rejection and keeps unknown outcomes protected. Existing calls without keys remain unchanged.
|
|
41
|
+
|
|
42
|
+
## 0.8.0
|
|
43
|
+
|
|
44
|
+
### Minor Changes
|
|
45
|
+
|
|
46
|
+
- 505f0a6: **Breaking (types only):** remove `provision_phone_number` from `CreateSetupLinkParams` and `SetupLink`. Number provisioning is not offered: the option never had any effect and the API ignores it and stops returning it. Code that still passes it gets a TypeScript error; just drop the field. No runtime change.
|
|
47
|
+
|
|
48
|
+
Document the setup link redirects as the API ships them: `success_redirect_url`/`failure_redirect_url` must be `https://`, without credentials and up to 2048 characters (otherwise `422 invalid_redirect_url`). After a final state the customer goes to the success URL with `setup_link_id` and `status=completed`, to the failure URL with `status=failed` when the link is exhausted, or with `status=cancelled` when they choose to go back on a retryable error (the link stays valid). The partner's query string is preserved and the link token is never sent. `theme_config` is documented as reserved (always `null`).
|
|
49
|
+
|
|
3
50
|
## 0.7.0
|
|
4
51
|
|
|
5
52
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -95,8 +95,49 @@ await boto.messages.send({
|
|
|
95
95
|
await boto.conversations.reply("uuid-da-conversa", {
|
|
96
96
|
text: "Resposta do agente",
|
|
97
97
|
});
|
|
98
|
+
|
|
99
|
+
// Botões de resposta, lista ou botão de link (objeto interactive da Cloud API)
|
|
100
|
+
await boto.messages.sendInteractive({
|
|
101
|
+
to: "+5531988887777",
|
|
102
|
+
interactive: {
|
|
103
|
+
type: "button",
|
|
104
|
+
body: { text: "Confirma o horário?" },
|
|
105
|
+
action: {
|
|
106
|
+
buttons: [
|
|
107
|
+
{ type: "reply", reply: { id: "sim", title: "Sim" } },
|
|
108
|
+
{ type: "reply", reply: { id: "nao", title: "Não" } },
|
|
109
|
+
],
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
// Localização
|
|
115
|
+
await boto.messages.sendLocation({
|
|
116
|
+
to: "+5531988887777",
|
|
117
|
+
latitude: -3.119,
|
|
118
|
+
longitude: -60.0217,
|
|
119
|
+
name: "Loja Centro",
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
// Reação a uma mensagem RECEBIDA (UUID interno ou wamid, até 30 dias); "" retira
|
|
123
|
+
const r = await boto.messages.sendReaction({
|
|
124
|
+
to: "+5531988887777",
|
|
125
|
+
message_id: "wamid.HBgM...",
|
|
126
|
+
emoji: "👍",
|
|
127
|
+
});
|
|
128
|
+
r.reaction?.action; // "react" | "unreact"
|
|
129
|
+
|
|
130
|
+
// Listar na ordem real das mensagens (histórico importado incluído)
|
|
131
|
+
const page = await boto.messages.list({ sort: "event_at", limit: 50 });
|
|
132
|
+
page.data[0]?.source; // "api" | "app" | "history" | "broadcast"
|
|
98
133
|
```
|
|
99
134
|
|
|
135
|
+
Interactive, localização e reação são mensagens livres: exigem a janela de 24h
|
|
136
|
+
aberta. A API valida o `interactive` (limites da Cloud API) e recusa com `422
|
|
137
|
+
invalid_request`; reação recusa com `invalid_reaction`, `missing_reaction_target`,
|
|
138
|
+
`reaction_target_not_found`, `reaction_target_invalid` ou `reaction_target_expired`.
|
|
139
|
+
O cursor de `messages.list` vale só para o `sort` que o gerou.
|
|
140
|
+
|
|
100
141
|
## Clientes e templates
|
|
101
142
|
|
|
102
143
|
```ts
|
|
@@ -209,6 +250,33 @@ catch (err) {
|
|
|
209
250
|
|
|
210
251
|
`err.headers` traz só os headers da resposta — nenhuma credencial de request entra nele.
|
|
211
252
|
|
|
253
|
+
### Recusas de plano
|
|
254
|
+
|
|
255
|
+
`isPlanError(err)` reconhece recusas que só um upgrade resolve (retry não):
|
|
256
|
+
`403 plan_restricted` nas escritas de IA, Agenda, Calendário, Jornadas e execuções
|
|
257
|
+
(`422 plan_restricted` em funil, aquecimento e regras de comentário),
|
|
258
|
+
`429 free_form_limit_reached` (limite de mensagens 1:1 do Free) e
|
|
259
|
+
`402 free_number_cap` no setup além do teto de Números do Free. Credencial de IA
|
|
260
|
+
nova só para `openai`/`anthropic` (`AI_CREDENTIAL_PROVIDERS`; os demais respondem
|
|
261
|
+
`422 provider_not_enabled`); `ai.providers.get()` traz `accepts_new_credentials`
|
|
262
|
+
por provedor.
|
|
263
|
+
|
|
264
|
+
```ts
|
|
265
|
+
import { isPlanError } from "@botozap/sdk";
|
|
266
|
+
|
|
267
|
+
catch (err) {
|
|
268
|
+
if (isPlanError(err)) mostrarUpgrade(err.code);
|
|
269
|
+
}
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
### Webhooks
|
|
273
|
+
|
|
274
|
+
`WEBHOOK_CATEGORIES` lista as categorias de `webhooks.create({ events })`:
|
|
275
|
+
`messages`, `statuses`, `crm`, `account` (inclui `whatsapp.phone_number.connected`)
|
|
276
|
+
e `app_messages`, opt-in, com `whatsapp.message.echo`, `.edited` e `.revoked` do
|
|
277
|
+
app WhatsApp Business em coexistência. Em `webhookDeliveries.list`, o status
|
|
278
|
+
`limited` marca a entrega cortada pelo limite de repasse do Free (sem retry).
|
|
279
|
+
|
|
212
280
|
## Configuração
|
|
213
281
|
|
|
214
282
|
```ts
|
|
@@ -238,8 +306,17 @@ O SDK cobre os recursos da API `/v1`:
|
|
|
238
306
|
- `media` — subir arquivo (obter um media_id) e **buscar metadados + URL de download** de uma mídia recebida
|
|
239
307
|
- `events` — reler inbound e mudanças de status pelo cursor durável da Conta/ambiente
|
|
240
308
|
- `usage` — `metaCosts`: custo aproximado da Meta por dia, categoria e moeda (Pricing Analytics), com estimativa por tarifa publicada onde a Meta não devolveu custo
|
|
309
|
+
- `me` — `get`: Conta, ambiente (`live` ou `sandbox`) e scopes efetivos da chave autenticada; não retorna a chave nem uma identidade pessoal
|
|
241
310
|
- `users`, `apiLogs`, `webhookDeliveries` — leitura
|
|
242
311
|
|
|
312
|
+
`me.get()` é útil para conferir a identidade configurada antes de executar
|
|
313
|
+
operações em uma integração:
|
|
314
|
+
|
|
315
|
+
```ts
|
|
316
|
+
const identity = await boto.me.get();
|
|
317
|
+
// { account_id: "…", environment: "live", scopes: ["messages:write"] }
|
|
318
|
+
```
|
|
319
|
+
|
|
243
320
|
Inbound e mudanças de status compartilham um stream crescente. Guarde
|
|
244
321
|
`paging.cursor` e use-o como `after` na leitura seguinte; após uma desconexão,
|
|
245
322
|
isso recupera o intervalo persistido sem depender de memória do processo:
|
|
@@ -306,7 +383,16 @@ const msgs = await boto.messages.list({ limit: 50, direction: "inbound" });
|
|
|
306
383
|
await boto.customers.update(customerId, { name: "Padaria do João" });
|
|
307
384
|
const link = await boto.customers.createSetupLink(customerId, {
|
|
308
385
|
allowed_connection_types: ["dedicated"],
|
|
386
|
+
// https, sem usuário/senha, até 2048 caracteres (senão 422 invalid_redirect_url).
|
|
387
|
+
// Concluído → success com ?setup_link_id=…&status=completed. Link esgotado →
|
|
388
|
+
// failure com status=failed; cliente volta num erro recuperável → failure com
|
|
389
|
+
// status=cancelled (o link segue válido). A query da URL é preservada e o
|
|
390
|
+
// token do link nunca é enviado.
|
|
391
|
+
success_redirect_url: "https://seu-app.com/whatsapp/ok?ref=42",
|
|
392
|
+
failure_redirect_url: "https://seu-app.com/whatsapp/erro",
|
|
309
393
|
});
|
|
394
|
+
// Envie link.url ao Cliente. No sucesso, confirme o número em phoneNumbers.list:
|
|
395
|
+
// uma conexão concluída ainda pode ter pendência de registro.
|
|
310
396
|
|
|
311
397
|
await boto.webhooks.create({
|
|
312
398
|
url: "https://seu-app.com/hooks",
|
|
@@ -376,3 +462,43 @@ substitui snapshots nem transforma uma inferência incerta em custo zero.
|
|
|
376
462
|
|
|
377
463
|
A CLI `ai usage save-rate` recebe o mesmo JSON por `--input-file`; o MCP expõe
|
|
378
464
|
`audio_pricing` opcional e anulável na ferramenta `ai_usage_save_rate`.
|
|
465
|
+
|
|
466
|
+
## Token OAuth
|
|
467
|
+
|
|
468
|
+
Além de `apiKey`, o cliente aceita `accessToken`. Um provider permite usar o token renovado em cada requisição:
|
|
469
|
+
|
|
470
|
+
```ts
|
|
471
|
+
const boto = new BotoZap({
|
|
472
|
+
accessToken: async () => getCurrentOAuthAccessToken(),
|
|
473
|
+
});
|
|
474
|
+
await boto.contacts.list();
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
Informe uma única credencial. O SDK envia `Authorization: Bearer` e não realiza o fluxo de login ou a renovação; o aplicativo fornece o token atual. `boto.me.get()` devolve os scopes e, para OAuth, `auth_type`, `user_id`, `client_id`, `grant_id` e `allowed_routes`. A autorização sempre é revalidada pelo servidor.
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
### Repetir um envio sem duplicar a intenção
|
|
481
|
+
|
|
482
|
+
A opção `idempotencyKey` é opcional. Crie uma chave antes da primeira tentativa
|
|
483
|
+
e preserve-a se perder a resposta; o corpo e a credencial também devem ser os
|
|
484
|
+
mesmos. Sem a opção, o SDK mantém o comportamento anterior.
|
|
485
|
+
|
|
486
|
+
```ts
|
|
487
|
+
const options = { idempotencyKey: crypto.randomUUID() };
|
|
488
|
+
await boto.messages.send({ to: "5511999999999", text: "Seu pedido está pronto." }, options);
|
|
489
|
+
// Retry da mesma intenção: use novamente o mesmo payload e options.
|
|
490
|
+
```
|
|
491
|
+
|
|
492
|
+
`sendTemplate`, `sendMedia` e `conversations.reply` aceitam a mesma opção como
|
|
493
|
+
último argumento. O servidor retorna a resposta original; payload diferente ou
|
|
494
|
+
tentativa pendente retornam 409. Resultados terminais ficam disponíveis por 24h.
|
|
495
|
+
Pendências desconhecidas não reabrem automaticamente. Depois de 24h, confira o
|
|
496
|
+
histórico antes de reenviar; nunca troque a chave para contornar uma pendência.
|
|
497
|
+
Requer a API com suporte a `Idempotency-Key` em `POST /v1/messages`.
|
|
498
|
+
|
|
499
|
+
Recusas confirmadas (`outcome: rejected`) liberam a chave. Aguarde o backoff ou
|
|
500
|
+
corrija a causa e repita com a mesma chave; após liberação, outro payload é uma
|
|
501
|
+
nova intenção. `unknown` ou `accepted` exigem conciliação antes de considerar
|
|
502
|
+
outro envio. SDK e MCP preservam `outcome` e `retry` da API. Resultados concluídos
|
|
503
|
+
vencidos são removidos pelo cron a cada minuto; claims incertas não são removidas
|
|
504
|
+
por tempo, conforme o runbook `botozap/docs/ops/message-send-receipts.md`.
|
package/dist/index.cjs
CHANGED
|
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
21
21
|
var index_exports = {};
|
|
22
22
|
__export(index_exports, {
|
|
23
23
|
AI_CONFIGURABLE_PURPOSES: () => AI_CONFIGURABLE_PURPOSES,
|
|
24
|
+
AI_CREDENTIAL_PROVIDERS: () => AI_CREDENTIAL_PROVIDERS,
|
|
24
25
|
AI_OPERATIONS: () => AI_OPERATIONS,
|
|
25
26
|
AI_PURPOSES: () => AI_PURPOSES,
|
|
26
27
|
AgendaConfiguration: () => AgendaConfiguration,
|
|
@@ -57,8 +58,11 @@ __export(index_exports, {
|
|
|
57
58
|
CrmResource: () => CrmResource,
|
|
58
59
|
Inbox: () => Inbox,
|
|
59
60
|
Journeys: () => Journeys,
|
|
61
|
+
PLAN_ERROR_CODES: () => PLAN_ERROR_CODES,
|
|
60
62
|
Radar: () => Radar,
|
|
61
|
-
SavedReplies: () => SavedReplies
|
|
63
|
+
SavedReplies: () => SavedReplies,
|
|
64
|
+
WEBHOOK_CATEGORIES: () => WEBHOOK_CATEGORIES,
|
|
65
|
+
isPlanError: () => isPlanError
|
|
62
66
|
});
|
|
63
67
|
module.exports = __toCommonJS(index_exports);
|
|
64
68
|
|
|
@@ -103,16 +107,28 @@ function assertAudioPricing(value) {
|
|
|
103
107
|
var BotoZapError = class extends Error {
|
|
104
108
|
code;
|
|
105
109
|
status;
|
|
110
|
+
outcome;
|
|
111
|
+
retry;
|
|
106
112
|
/** Headers da resposta HTTP. Ausente em erros sem resposta (status 0). */
|
|
107
113
|
headers;
|
|
108
|
-
constructor(code, message, status, headers) {
|
|
114
|
+
constructor(code, message, status, headers, details) {
|
|
109
115
|
super(message);
|
|
110
116
|
this.name = "BotoZapError";
|
|
111
117
|
this.code = code;
|
|
112
118
|
this.status = status;
|
|
113
119
|
this.headers = headers;
|
|
120
|
+
this.outcome = details?.outcome;
|
|
121
|
+
this.retry = details?.retry;
|
|
114
122
|
}
|
|
115
123
|
};
|
|
124
|
+
var PLAN_ERROR_CODES = [
|
|
125
|
+
"plan_restricted",
|
|
126
|
+
"free_form_limit_reached",
|
|
127
|
+
"free_number_cap"
|
|
128
|
+
];
|
|
129
|
+
function isPlanError(error) {
|
|
130
|
+
return error instanceof BotoZapError && PLAN_ERROR_CODES.includes(error.code);
|
|
131
|
+
}
|
|
116
132
|
|
|
117
133
|
// src/resources/ai/upload.ts
|
|
118
134
|
var receipts = /* @__PURE__ */ new WeakMap();
|
|
@@ -3877,6 +3893,7 @@ var AI_OPERATIONS = [
|
|
|
3877
3893
|
];
|
|
3878
3894
|
|
|
3879
3895
|
// src/resources/ai/types.ts
|
|
3896
|
+
var AI_CREDENTIAL_PROVIDERS = ["openai", "anthropic"];
|
|
3880
3897
|
var AI_PURPOSES = [
|
|
3881
3898
|
"default",
|
|
3882
3899
|
"agent_turn",
|
|
@@ -4000,7 +4017,7 @@ var AiCredentialsResource = class {
|
|
|
4000
4017
|
get(input) {
|
|
4001
4018
|
return request(this.client, AI_OPERATIONS[11], input);
|
|
4002
4019
|
}
|
|
4003
|
-
/** Cria credencial própria no Vault; a resposta nunca contém a chave. */
|
|
4020
|
+
/** Cria credencial própria no Vault; a resposta nunca contém a chave. Só `AI_CREDENTIAL_PROVIDERS` (openai/anthropic); os demais: 422 `provider_not_enabled`. */
|
|
4004
4021
|
create(input) {
|
|
4005
4022
|
return request(this.client, AI_OPERATIONS[12], input);
|
|
4006
4023
|
}
|
|
@@ -5144,8 +5161,9 @@ var Messages = class {
|
|
|
5144
5161
|
}
|
|
5145
5162
|
client;
|
|
5146
5163
|
/** Envia uma mensagem de texto. */
|
|
5147
|
-
async send(params) {
|
|
5164
|
+
async send(params, options = {}) {
|
|
5148
5165
|
const result = await this.client.requestObject("POST", "/messages", {
|
|
5166
|
+
idempotencyKey: options.idempotencyKey,
|
|
5149
5167
|
body: {
|
|
5150
5168
|
to: params.to,
|
|
5151
5169
|
type: "text",
|
|
@@ -5156,8 +5174,9 @@ var Messages = class {
|
|
|
5156
5174
|
return assertSendResult(result);
|
|
5157
5175
|
}
|
|
5158
5176
|
/** Envia uma mensagem usando um template aprovado. */
|
|
5159
|
-
async sendTemplate(params) {
|
|
5177
|
+
async sendTemplate(params, options = {}) {
|
|
5160
5178
|
const result = await this.client.requestObject("POST", "/messages", {
|
|
5179
|
+
idempotencyKey: options.idempotencyKey,
|
|
5161
5180
|
body: {
|
|
5162
5181
|
to: params.to,
|
|
5163
5182
|
type: "template",
|
|
@@ -5168,7 +5187,7 @@ var Messages = class {
|
|
|
5168
5187
|
return assertSendResult(result);
|
|
5169
5188
|
}
|
|
5170
5189
|
/** Envia mídia por URL pública. */
|
|
5171
|
-
async sendMedia(params) {
|
|
5190
|
+
async sendMedia(params, options = {}) {
|
|
5172
5191
|
const media = { link: params.link };
|
|
5173
5192
|
if ("caption" in params && params.caption !== void 0) {
|
|
5174
5193
|
media.caption = params.caption;
|
|
@@ -5177,6 +5196,7 @@ var Messages = class {
|
|
|
5177
5196
|
media.filename = params.filename;
|
|
5178
5197
|
}
|
|
5179
5198
|
const result = await this.client.requestObject("POST", "/messages", {
|
|
5199
|
+
idempotencyKey: options.idempotencyKey,
|
|
5180
5200
|
body: {
|
|
5181
5201
|
to: params.to,
|
|
5182
5202
|
from: params.from,
|
|
@@ -5186,6 +5206,47 @@ var Messages = class {
|
|
|
5186
5206
|
});
|
|
5187
5207
|
return assertSendResult(result);
|
|
5188
5208
|
}
|
|
5209
|
+
/**
|
|
5210
|
+
* Envia botões de resposta, lista ou botão de link (WhatsApp; mensagem livre,
|
|
5211
|
+
* exige janela de 24h aberta).
|
|
5212
|
+
*/
|
|
5213
|
+
async sendInteractive(params, options = {}) {
|
|
5214
|
+
return postMessage(
|
|
5215
|
+
this.client,
|
|
5216
|
+
{ to: params.to, from: params.from, type: "interactive", interactive: params.interactive },
|
|
5217
|
+
options
|
|
5218
|
+
);
|
|
5219
|
+
}
|
|
5220
|
+
/** Envia uma localização (WhatsApp; mensagem livre). */
|
|
5221
|
+
async sendLocation(params, options = {}) {
|
|
5222
|
+
const location = {
|
|
5223
|
+
latitude: params.latitude,
|
|
5224
|
+
longitude: params.longitude
|
|
5225
|
+
};
|
|
5226
|
+
if (params.name !== void 0) location.name = params.name;
|
|
5227
|
+
if (params.address !== void 0) location.address = params.address;
|
|
5228
|
+
return postMessage(
|
|
5229
|
+
this.client,
|
|
5230
|
+
{ to: params.to, from: params.from, type: "location", location },
|
|
5231
|
+
options
|
|
5232
|
+
);
|
|
5233
|
+
}
|
|
5234
|
+
/**
|
|
5235
|
+
* Reage a uma mensagem recebida (WhatsApp). `emoji: ""` retira a reação.
|
|
5236
|
+
* O retorno traz `reaction` com o alvo e a ação.
|
|
5237
|
+
*/
|
|
5238
|
+
async sendReaction(params, options = {}) {
|
|
5239
|
+
return postMessage(
|
|
5240
|
+
this.client,
|
|
5241
|
+
{
|
|
5242
|
+
to: params.to,
|
|
5243
|
+
from: params.from,
|
|
5244
|
+
type: "reaction",
|
|
5245
|
+
reaction: { message_id: params.message_id, emoji: params.emoji }
|
|
5246
|
+
},
|
|
5247
|
+
options
|
|
5248
|
+
);
|
|
5249
|
+
}
|
|
5189
5250
|
/** Lista as mensagens da conta (paginação por cursor). */
|
|
5190
5251
|
list(params = {}) {
|
|
5191
5252
|
return this.client.requestCursorList("GET", "/messages", {
|
|
@@ -5193,6 +5254,7 @@ var Messages = class {
|
|
|
5193
5254
|
limit: params.limit,
|
|
5194
5255
|
after: params.after,
|
|
5195
5256
|
before: params.before,
|
|
5257
|
+
sort: params.sort,
|
|
5196
5258
|
phone_number_id: params.phone_number_id,
|
|
5197
5259
|
conversation_id: params.conversation_id,
|
|
5198
5260
|
direction: params.direction,
|
|
@@ -5210,6 +5272,13 @@ var Messages = class {
|
|
|
5210
5272
|
);
|
|
5211
5273
|
}
|
|
5212
5274
|
};
|
|
5275
|
+
async function postMessage(client, body, options) {
|
|
5276
|
+
const result = await client.requestObject("POST", "/messages", {
|
|
5277
|
+
idempotencyKey: options.idempotencyKey,
|
|
5278
|
+
body
|
|
5279
|
+
});
|
|
5280
|
+
return assertSendResult(result);
|
|
5281
|
+
}
|
|
5213
5282
|
function assertSendResult(value) {
|
|
5214
5283
|
if (typeof value.wamid !== "string" || typeof value.to !== "string" || typeof value.status !== "string" || value.id !== null && typeof value.id !== "string") {
|
|
5215
5284
|
throw new BotoZapError(
|
|
@@ -5264,7 +5333,12 @@ var Customers = class {
|
|
|
5264
5333
|
{ query: { page: params.page, per_page: params.per_page } }
|
|
5265
5334
|
);
|
|
5266
5335
|
}
|
|
5267
|
-
/**
|
|
5336
|
+
/**
|
|
5337
|
+
* Cria um link de setup sob um cliente (expira em 30 dias). Envie a `url`
|
|
5338
|
+
* devolvida ao Cliente; veja em {@link CreateSetupLinkParams} como funcionam
|
|
5339
|
+
* os redirecionamentos. URL de redirecionamento inválida lança
|
|
5340
|
+
* `BotoZapError` com `code: "invalid_redirect_url"` (422).
|
|
5341
|
+
*/
|
|
5268
5342
|
createSetupLink(customerId, params = {}) {
|
|
5269
5343
|
return this.client.requestItem(
|
|
5270
5344
|
"POST",
|
|
@@ -5495,7 +5569,7 @@ var Conversations = class {
|
|
|
5495
5569
|
* A leitura e o envio usam a mesma chave; o POST /messages revalida Conta,
|
|
5496
5570
|
* ambiente, identidade, janela, quota e billing antes de chamar a Meta.
|
|
5497
5571
|
*/
|
|
5498
|
-
async reply(id, params) {
|
|
5572
|
+
async reply(id, params, options = {}) {
|
|
5499
5573
|
const conversation = await this.get(id);
|
|
5500
5574
|
const from = conversation.phone_number_id;
|
|
5501
5575
|
if (typeof from !== "string" || !from.trim()) {
|
|
@@ -5514,7 +5588,7 @@ var Conversations = class {
|
|
|
5514
5588
|
422
|
|
5515
5589
|
);
|
|
5516
5590
|
}
|
|
5517
|
-
return this.client.messages.send({ to, text: params.text, from });
|
|
5591
|
+
return this.client.messages.send({ to, text: params.text, from }, options);
|
|
5518
5592
|
}
|
|
5519
5593
|
update(id, params) {
|
|
5520
5594
|
return this.client.requestItem(
|
|
@@ -5627,10 +5701,19 @@ var PhoneNumbers = class {
|
|
|
5627
5701
|
`/phone_numbers/${enc6(id)}`
|
|
5628
5702
|
);
|
|
5629
5703
|
}
|
|
5630
|
-
|
|
5631
|
-
|
|
5632
|
-
|
|
5633
|
-
|
|
5704
|
+
/**
|
|
5705
|
+
* Atualiza o nome local (`label`) do Número. É o único campo editável:
|
|
5706
|
+
* identidade e dados sincronizados da Meta (`display_phone_number`,
|
|
5707
|
+
* `verified_name`, `quality_rating`) não mudam por aqui. `{id}` aceita o
|
|
5708
|
+
* UUID interno ou o `phone_number_id` da Meta.
|
|
5709
|
+
*/
|
|
5710
|
+
update(id, params) {
|
|
5711
|
+
return this.client.requestItem(
|
|
5712
|
+
"PATCH",
|
|
5713
|
+
`/phone_numbers/${enc6(id)}`,
|
|
5714
|
+
{ body: { label: params.label } }
|
|
5715
|
+
);
|
|
5716
|
+
}
|
|
5634
5717
|
/** Remove um número. Responde 204 (sem corpo). */
|
|
5635
5718
|
delete(id) {
|
|
5636
5719
|
return this.client.request("DELETE", `/phone_numbers/${enc6(id)}`);
|
|
@@ -5706,6 +5789,28 @@ var Events = class {
|
|
|
5706
5789
|
}
|
|
5707
5790
|
};
|
|
5708
5791
|
|
|
5792
|
+
// src/resources/usage.ts
|
|
5793
|
+
var Usage = class {
|
|
5794
|
+
constructor(client) {
|
|
5795
|
+
this.client = client;
|
|
5796
|
+
}
|
|
5797
|
+
client;
|
|
5798
|
+
/**
|
|
5799
|
+
* Custo da Meta por dia, categoria e tipo, lido da Pricing Analytics
|
|
5800
|
+
* sincronizada uma vez por dia por WABA. Scope `customers:read`; o sandbox
|
|
5801
|
+
* fica de fora. Intervalo grande demais responde 422 `range_too_large`.
|
|
5802
|
+
*/
|
|
5803
|
+
metaCosts(params = {}) {
|
|
5804
|
+
return this.client.requestItem("GET", "/usage/meta-costs", {
|
|
5805
|
+
query: {
|
|
5806
|
+
customer_id: params.customer_id,
|
|
5807
|
+
from: params.from,
|
|
5808
|
+
to: params.to
|
|
5809
|
+
}
|
|
5810
|
+
});
|
|
5811
|
+
}
|
|
5812
|
+
};
|
|
5813
|
+
|
|
5709
5814
|
// src/resources/read-only.ts
|
|
5710
5815
|
var Users = class {
|
|
5711
5816
|
constructor(client) {
|
|
@@ -5760,6 +5865,18 @@ var WebhookDeliveries = class {
|
|
|
5760
5865
|
}
|
|
5761
5866
|
};
|
|
5762
5867
|
|
|
5868
|
+
// src/resources/me.ts
|
|
5869
|
+
var MeResource = class {
|
|
5870
|
+
constructor(client) {
|
|
5871
|
+
this.client = client;
|
|
5872
|
+
}
|
|
5873
|
+
client;
|
|
5874
|
+
/** Retorna a Conta, o ambiente e os scopes efetivos da chave. */
|
|
5875
|
+
get() {
|
|
5876
|
+
return this.client.requestItem("GET", "/me");
|
|
5877
|
+
}
|
|
5878
|
+
};
|
|
5879
|
+
|
|
5763
5880
|
// src/client.ts
|
|
5764
5881
|
var DEFAULT_BASE_URL = "https://botozap.com.br/api/v1";
|
|
5765
5882
|
var BotoZap = class {
|
|
@@ -5784,17 +5901,19 @@ var BotoZap = class {
|
|
|
5784
5901
|
radar;
|
|
5785
5902
|
media;
|
|
5786
5903
|
events;
|
|
5904
|
+
usage;
|
|
5787
5905
|
users;
|
|
5788
5906
|
apiLogs;
|
|
5789
5907
|
webhookDeliveries;
|
|
5790
|
-
|
|
5908
|
+
me;
|
|
5909
|
+
credential;
|
|
5791
5910
|
baseUrl;
|
|
5792
5911
|
fetchImpl;
|
|
5793
5912
|
constructor(options) {
|
|
5794
|
-
if (!options ||
|
|
5795
|
-
throw new Error("BotoZap: apiKey
|
|
5913
|
+
if (!options || Boolean(options.apiKey) === Boolean(options.accessToken)) {
|
|
5914
|
+
throw new Error("BotoZap: informe apenas apiKey ou accessToken.");
|
|
5796
5915
|
}
|
|
5797
|
-
this.
|
|
5916
|
+
this.credential = options.accessToken ?? options.apiKey;
|
|
5798
5917
|
this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
5799
5918
|
const resolvedFetch = options.fetch ?? globalThis.fetch;
|
|
5800
5919
|
if (typeof resolvedFetch !== "function") {
|
|
@@ -5824,9 +5943,11 @@ var BotoZap = class {
|
|
|
5824
5943
|
this.phoneNumbers = new PhoneNumbers(this);
|
|
5825
5944
|
this.media = new Media(this);
|
|
5826
5945
|
this.events = new Events(this);
|
|
5946
|
+
this.usage = new Usage(this);
|
|
5827
5947
|
this.users = new Users(this);
|
|
5828
5948
|
this.apiLogs = new ApiLogs(this);
|
|
5829
5949
|
this.webhookDeliveries = new WebhookDeliveries(this);
|
|
5950
|
+
this.me = new MeResource(this);
|
|
5830
5951
|
}
|
|
5831
5952
|
/** PUT de artefato em URL assinada, sem token BotoZap nem cookies. Não segue redirecionamentos. */
|
|
5832
5953
|
async putArtifact(url, contentType, file) {
|
|
@@ -5868,12 +5989,16 @@ var BotoZap = class {
|
|
|
5868
5989
|
if (value !== void 0) url.searchParams.set(key, String(value));
|
|
5869
5990
|
}
|
|
5870
5991
|
}
|
|
5992
|
+
const credential = typeof this.credential === "function" ? await this.credential() : this.credential;
|
|
5993
|
+
if (!credential || /[\s,]/.test(credential)) {
|
|
5994
|
+
throw new BotoZapError("invalid_credential", "Credencial Bearer inv\xE1lida.", 401);
|
|
5995
|
+
}
|
|
5871
5996
|
let res;
|
|
5872
5997
|
try {
|
|
5873
5998
|
res = await this.fetchImpl(url.toString(), {
|
|
5874
5999
|
method,
|
|
5875
6000
|
headers: {
|
|
5876
|
-
Authorization: `Bearer ${
|
|
6001
|
+
Authorization: `Bearer ${credential}`,
|
|
5877
6002
|
...opts.body instanceof FormData ? {} : { "Content-Type": "application/json" },
|
|
5878
6003
|
Accept: "application/json",
|
|
5879
6004
|
...opts.idempotencyKey ? { "Idempotency-Key": opts.idempotencyKey } : {}
|
|
@@ -5882,6 +6007,7 @@ var BotoZap = class {
|
|
|
5882
6007
|
signal: opts.signal
|
|
5883
6008
|
});
|
|
5884
6009
|
} catch (cause) {
|
|
6010
|
+
if (cause instanceof BotoZapError) throw cause;
|
|
5885
6011
|
const detail = cause instanceof Error ? cause.message : String(cause);
|
|
5886
6012
|
throw new BotoZapError(
|
|
5887
6013
|
"network_error",
|
|
@@ -5902,7 +6028,11 @@ var BotoZap = class {
|
|
|
5902
6028
|
envelope?.error?.code ?? "http_error",
|
|
5903
6029
|
envelope?.error?.message ?? `HTTP ${res.status}`,
|
|
5904
6030
|
res.status,
|
|
5905
|
-
headers
|
|
6031
|
+
headers,
|
|
6032
|
+
{
|
|
6033
|
+
outcome: envelope?.error?.outcome === "rejected" || envelope?.error?.outcome === "accepted" || envelope?.error?.outcome === "unknown" ? envelope.error.outcome : void 0,
|
|
6034
|
+
retry: envelope?.error?.retry === "backoff" || envelope?.error?.retry === "after_correction" || envelope?.error?.retry === "reconcile_first" || envelope?.error?.retry === "unknown" ? envelope.error.retry : void 0
|
|
6035
|
+
}
|
|
5906
6036
|
);
|
|
5907
6037
|
}
|
|
5908
6038
|
return data;
|
|
@@ -5966,9 +6096,19 @@ function safeJson(text) {
|
|
|
5966
6096
|
return text;
|
|
5967
6097
|
}
|
|
5968
6098
|
}
|
|
6099
|
+
|
|
6100
|
+
// src/types.ts
|
|
6101
|
+
var WEBHOOK_CATEGORIES = [
|
|
6102
|
+
"messages",
|
|
6103
|
+
"statuses",
|
|
6104
|
+
"crm",
|
|
6105
|
+
"account",
|
|
6106
|
+
"app_messages"
|
|
6107
|
+
];
|
|
5969
6108
|
// Annotate the CommonJS export names for ESM import in node:
|
|
5970
6109
|
0 && (module.exports = {
|
|
5971
6110
|
AI_CONFIGURABLE_PURPOSES,
|
|
6111
|
+
AI_CREDENTIAL_PROVIDERS,
|
|
5972
6112
|
AI_OPERATIONS,
|
|
5973
6113
|
AI_PURPOSES,
|
|
5974
6114
|
AgendaConfiguration,
|
|
@@ -6005,7 +6145,10 @@ function safeJson(text) {
|
|
|
6005
6145
|
CrmResource,
|
|
6006
6146
|
Inbox,
|
|
6007
6147
|
Journeys,
|
|
6148
|
+
PLAN_ERROR_CODES,
|
|
6008
6149
|
Radar,
|
|
6009
|
-
SavedReplies
|
|
6150
|
+
SavedReplies,
|
|
6151
|
+
WEBHOOK_CATEGORIES,
|
|
6152
|
+
isPlanError
|
|
6010
6153
|
});
|
|
6011
6154
|
//# sourceMappingURL=index.cjs.map
|