@botozap/sdk 0.1.0 → 0.3.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/dist/index.d.ts CHANGED
@@ -9,6 +9,8 @@ interface SendResult {
9
9
  id: string | null;
10
10
  wamid: string;
11
11
  to: string;
12
+ /** Destinatário efetivamente usado após normalização de telefone/BSUID. */
13
+ sent_to?: string;
12
14
  status: MessageStatus;
13
15
  /** Presente apenas quando a chave é do ambiente sandbox. */
14
16
  sandbox?: boolean;
@@ -89,6 +91,14 @@ interface Contact {
89
91
  }
90
92
  interface Conversation {
91
93
  id: string;
94
+ /** UUID interno do Número da própria Conversa. */
95
+ phone_number_id?: string;
96
+ contact?: {
97
+ /** Identidade canônica do Contato: telefone ou BSUID. */
98
+ wa_id?: string | null;
99
+ phone?: string | null;
100
+ [key: string]: unknown;
101
+ };
92
102
  [key: string]: unknown;
93
103
  }
94
104
  interface Assignment {
@@ -125,6 +135,30 @@ interface WebhookDelivery {
125
135
  id: string;
126
136
  [key: string]: unknown;
127
137
  }
138
+ /** Evento autoritativo do stream durável da Conta e ambiente autenticados. */
139
+ interface BotoZapEvent {
140
+ id: string;
141
+ /** Cursor monotônico e contíguo, serializado como string. */
142
+ cursor: string;
143
+ type: string;
144
+ /** WAMID da mensagem que originou o Evento. */
145
+ message_id: string;
146
+ /** UUID interno da Mensagem; pode ser null em status de Broadcast. */
147
+ message_resource_id: string | null;
148
+ occurred_at: string;
149
+ created_at: string;
150
+ data: Record<string, unknown>;
151
+ }
152
+ /** Paginação crescente do stream; `cursor` é seguro para o próximo `after`. */
153
+ interface EventPaging {
154
+ cursor: string;
155
+ next: string | null;
156
+ has_more: boolean;
157
+ }
158
+ interface EventList {
159
+ data: BotoZapEvent[];
160
+ paging: EventPaging;
161
+ }
128
162
  /**
129
163
  * Retorno de POST /v1/media. A rota responde `{ ingest_id, target, resource }`:
130
164
  * `target.kind` diz o pipeline usado (`meta_media` traz `media_id` usável em
@@ -149,6 +183,28 @@ interface MediaUploadResult {
149
183
  [key: string]: unknown;
150
184
  };
151
185
  }
186
+ /**
187
+ * Retorno de GET /v1/media/:id — metadados de uma mídia RECEBIDA (inbound) já
188
+ * espelhada, mais a `download_url` (URL assinada, efêmera) para baixar o binário.
189
+ * O `id` é o `media_id` da Cloud API (não um uuid interno).
190
+ *
191
+ * `mime_type`/`file_size`/`sha256` podem vir `null` (a Meta nem sempre informa
192
+ * todos). Se a mídia AINDA está sendo espelhada, a rota responde 202 e o SDK
193
+ * lança `BotoZapError` com `code: "media_not_ready"` (ver `media.get`) — nesse
194
+ * caso este objeto nunca é devolvido.
195
+ */
196
+ interface MediaAsset {
197
+ /** media_id da Cloud API. */
198
+ id: string;
199
+ mime_type: string | null;
200
+ /** Tamanho em bytes. */
201
+ file_size: number | null;
202
+ sha256: string | null;
203
+ /** URL assinada para baixar o binário. Válida até `expires_at`. */
204
+ download_url: string;
205
+ /** ISO 8601 — quando a `download_url` deixa de valer. */
206
+ expires_at: string;
207
+ }
152
208
  /**
153
209
  * Link de setup de um cliente (Embedded Signup). Shape do contrato
154
210
  * (ver `/v1/customers/:id/setup_links`): a `url` embute o token opaco; o token
@@ -190,14 +246,44 @@ interface SendTextParams {
190
246
  to: string;
191
247
  /** Corpo do texto. */
192
248
  text: string;
193
- /** phone_number_id de origem (obrigatório se a conta tem mais de um número). */
249
+ /** ID Meta ou UUID interno do Número de origem (obrigatório se houver mais de um). */
194
250
  from?: string;
195
251
  }
196
252
  interface SendTemplateParams {
197
253
  to: string;
198
254
  template: TemplatePayload;
255
+ /** ID Meta ou UUID interno do Número de origem. */
256
+ from?: string;
257
+ }
258
+ interface SendImageParams {
259
+ to: string;
260
+ type: "image";
261
+ link: string;
262
+ caption?: string;
263
+ from?: string;
264
+ }
265
+ interface SendAudioParams {
266
+ to: string;
267
+ type: "audio";
268
+ link: string;
199
269
  from?: string;
200
270
  }
271
+ interface SendVideoParams {
272
+ to: string;
273
+ type: "video";
274
+ link: string;
275
+ caption?: string;
276
+ from?: string;
277
+ }
278
+ interface SendDocumentParams {
279
+ to: string;
280
+ type: "document";
281
+ link: string;
282
+ caption?: string;
283
+ filename?: string;
284
+ from?: string;
285
+ }
286
+ type SendMediaParams = SendImageParams | SendVideoParams | SendAudioParams | SendDocumentParams;
201
287
  /** Endpoints de mensagem (POST /v1/messages, GET /v1/messages/:id). */
202
288
  declare class Messages {
203
289
  private readonly client;
@@ -206,6 +292,8 @@ declare class Messages {
206
292
  send(params: SendTextParams): Promise<SendResult>;
207
293
  /** Envia uma mensagem usando um template aprovado. */
208
294
  sendTemplate(params: SendTemplateParams): Promise<SendResult>;
295
+ /** Envia mídia por URL pública. */
296
+ sendMedia(params: SendMediaParams): Promise<SendResult>;
209
297
  /** Lista as mensagens da conta (paginação por cursor). */
210
298
  list(params?: ListMessagesParams): Promise<CursorList<Message>>;
211
299
  /** Busca uma mensagem pelo id interno. */
@@ -429,6 +517,10 @@ interface CreateAssignmentParams {
429
517
  user_id: string;
430
518
  notes?: string;
431
519
  }
520
+ interface ReplyConversationParams {
521
+ /** Corpo da resposta livre dentro da janela de 24h. */
522
+ text: string;
523
+ }
432
524
  /** Conversas (read + status) e atribuições a membros. */
433
525
  declare class Conversations {
434
526
  private readonly client;
@@ -436,6 +528,12 @@ declare class Conversations {
436
528
  /** Lista as conversas da conta (paginação por cursor). */
437
529
  list(params?: ListConversationsParams): Promise<CursorList<Conversation>>;
438
530
  get(id: string): Promise<Conversation>;
531
+ /**
532
+ * Responde uma Conversa sem o chamador precisar combinar Contato e Número.
533
+ * A leitura e o envio usam a mesma chave; o POST /messages revalida Conta,
534
+ * ambiente, identidade, janela, quota e billing antes de chamar a Meta.
535
+ */
536
+ reply(id: string, params: ReplyConversationParams): Promise<SendResult>;
439
537
  update(id: string, params: Record<string, unknown>): Promise<Conversation>;
440
538
  /** Lista as atribuições da conversa (paginação por offset/página). */
441
539
  listAssignments(id: string, params?: OffsetParams): Promise<OffsetList<Assignment>>;
@@ -562,6 +660,49 @@ declare class Media {
562
660
  private readonly client;
563
661
  constructor(client: BotoZap);
564
662
  upload(params: UploadMediaParams): Promise<MediaUploadResult>;
663
+ /**
664
+ * Busca os metadados de uma mídia RECEBIDA pelo `media_id` da Cloud API,
665
+ * incluindo `download_url` — uma URL assinada e efêmera que você pode baixar
666
+ * direto (GET), válida até `expires_at`.
667
+ *
668
+ * A mídia é espelhada de forma assíncrona; se você consultar antes de terminar,
669
+ * a rota responde 202 e este método lança `BotoZapError` com
670
+ * `code: "media_not_ready"`. Nesse caso, aguarde e retente — o segundo que faltar
671
+ * está em `err.headers?.["retry-after"]`:
672
+ *
673
+ * ```ts
674
+ * try {
675
+ * const media = await boto.media.get("wamid_media_id");
676
+ * // baixe media.download_url direto
677
+ * } catch (err) {
678
+ * if (err instanceof BotoZapError && err.code === "media_not_ready") {
679
+ * const wait = Number(err.headers?.["retry-after"] ?? 5);
680
+ * // retente após `wait` segundos
681
+ * }
682
+ * }
683
+ * ```
684
+ *
685
+ * Existe também `GET /v1/media/:id/download`, que responde 302 redirecionando
686
+ * para a mesma URL assinada; não há método SDK dedicado porque `download_url`
687
+ * (acima) já entrega essa URL sem o hop de redirect.
688
+ */
689
+ get(id: string): Promise<MediaAsset>;
690
+ }
691
+
692
+ /** Posição exclusiva no stream durável de Eventos. */
693
+ interface ListEventsParams {
694
+ /** Cursor retornado pela leitura anterior; omita para começar em zero. */
695
+ after?: string;
696
+ /** Quantidade máxima de Eventos na página (1..100). */
697
+ limit?: number;
698
+ /** Cancela uma leitura/tail que deixou de ser necessário. */
699
+ signal?: AbortSignal;
700
+ }
701
+ /** Stream durável de Eventos da Conta e ambiente derivados da chave. */
702
+ declare class Events {
703
+ private readonly client;
704
+ constructor(client: BotoZap);
705
+ list(params?: ListEventsParams): Promise<EventList>;
565
706
  }
566
707
 
567
708
  /** Membros da conta (somente leitura via API). */
@@ -611,6 +752,8 @@ interface BotoZapOptions {
611
752
  interface RequestOptions {
612
753
  query?: Record<string, string | number | undefined>;
613
754
  body?: unknown;
755
+ /** Cancela o I/O HTTP sem alterar o envelope de erro do SDK. */
756
+ signal?: AbortSignal;
614
757
  }
615
758
  /**
616
759
  * Cliente da API da BotoZap.
@@ -631,6 +774,7 @@ declare class BotoZap {
631
774
  readonly phoneNumbers: PhoneNumbers;
632
775
  readonly flows: Flows;
633
776
  readonly media: Media;
777
+ readonly events: Events;
634
778
  readonly users: Users;
635
779
  readonly apiLogs: ApiLogs;
636
780
  readonly webhookDeliveries: WebhookDeliveries;
@@ -672,4 +816,4 @@ declare class BotoZapError extends Error {
672
816
  constructor(code: string, message: string, status: number, headers?: Record<string, string>);
673
817
  }
674
818
 
675
- export { type AddRecipientsResult, type ApiLog, type Assignment, BotoZap, BotoZapError, type BotoZapOptions, type Broadcast, type BroadcastRecipient, type Contact, type Conversation, type CreateAssignmentParams, type CreateBroadcastParams, type CreateContactParams, type CreateCustomerParams, type CreateFlowParams, type CreateFlowVersionParams, type CreateSetupLinkParams, type CreateTemplateParams, type CreateWebhookParams, type CursorList, type CursorPaging, type CursorParams, type Customer, type Flow, type FlowPhoneParams, type FlowVersion, type ListApiLogsParams, type ListBroadcastsParams, type ListContactsParams, type ListConversationsParams, type ListFlowsParams, type ListMessagesParams, type ListPhoneNumbersParams, type ListRecipientsParams, type ListTemplatesParams, type ListWebhookDeliveriesParams, type MediaUploadResult, type Message, type MessageStatus, type OffsetList, type OffsetMeta, type OffsetParams, type PhoneNumber, type RequestOptions, type ScheduleBroadcastParams, type SendResult, type SendTemplateParams, type SendTextParams, type SetFlowDataEndpointParams, type SetupLink, type Template, type TemplatePayload, type UpdateBroadcastParams, type UpdateCustomerParams, type UpdateSetupLinkParams, type UploadMediaParams, type User, type Webhook, type WebhookDelivery };
819
+ export { type AddRecipientsResult, type ApiLog, type Assignment, BotoZap, BotoZapError, type BotoZapEvent, type BotoZapOptions, type Broadcast, type BroadcastRecipient, type Contact, type Conversation, type CreateAssignmentParams, type CreateBroadcastParams, type CreateContactParams, type CreateCustomerParams, type CreateFlowParams, type CreateFlowVersionParams, type CreateSetupLinkParams, type CreateTemplateParams, type CreateWebhookParams, type CursorList, type CursorPaging, type CursorParams, type Customer, type EventList, type EventPaging, type Flow, type FlowPhoneParams, type FlowVersion, type ListApiLogsParams, type ListBroadcastsParams, type ListContactsParams, type ListConversationsParams, type ListEventsParams, type ListFlowsParams, type ListMessagesParams, type ListPhoneNumbersParams, type ListRecipientsParams, type ListTemplatesParams, type ListWebhookDeliveriesParams, type MediaAsset, type MediaUploadResult, type Message, type MessageStatus, type OffsetList, type OffsetMeta, type OffsetParams, type PhoneNumber, type ReplyConversationParams, type RequestOptions, type ScheduleBroadcastParams, type SendAudioParams, type SendDocumentParams, type SendImageParams, type SendMediaParams, type SendResult, type SendTemplateParams, type SendTextParams, type SendVideoParams, type SetFlowDataEndpointParams, type SetupLink, type Template, type TemplatePayload, type UpdateBroadcastParams, type UpdateCustomerParams, type UpdateSetupLinkParams, type UploadMediaParams, type User, type Webhook, type WebhookDelivery };
package/dist/index.js CHANGED
@@ -43,6 +43,25 @@ var Messages = class {
43
43
  });
44
44
  return assertSendResult(result);
45
45
  }
46
+ /** Envia mídia por URL pública. */
47
+ async sendMedia(params) {
48
+ const media = { link: params.link };
49
+ if ("caption" in params && params.caption !== void 0) {
50
+ media.caption = params.caption;
51
+ }
52
+ if ("filename" in params && params.filename !== void 0) {
53
+ media.filename = params.filename;
54
+ }
55
+ const result = await this.client.requestObject("POST", "/messages", {
56
+ body: {
57
+ to: params.to,
58
+ from: params.from,
59
+ type: params.type,
60
+ [params.type]: media
61
+ }
62
+ });
63
+ return assertSendResult(result);
64
+ }
46
65
  /** Lista as mensagens da conta (paginação por cursor). */
47
66
  list(params = {}) {
48
67
  return this.client.requestCursorList("GET", "/messages", {
@@ -334,6 +353,32 @@ var Conversations = class {
334
353
  `/conversations/${enc4(id)}`
335
354
  );
336
355
  }
356
+ /**
357
+ * Responde uma Conversa sem o chamador precisar combinar Contato e Número.
358
+ * A leitura e o envio usam a mesma chave; o POST /messages revalida Conta,
359
+ * ambiente, identidade, janela, quota e billing antes de chamar a Meta.
360
+ */
361
+ async reply(id, params) {
362
+ const conversation = await this.get(id);
363
+ const from = conversation.phone_number_id;
364
+ if (typeof from !== "string" || !from.trim()) {
365
+ throw new BotoZapError(
366
+ "malformed_response",
367
+ "Conversa sem UUID interno do N\xFAmero de origem.",
368
+ 0
369
+ );
370
+ }
371
+ const contact = conversation.contact;
372
+ const to = typeof contact?.wa_id === "string" && contact.wa_id.trim() ? contact.wa_id : typeof contact?.phone === "string" && contact.phone.trim() ? contact.phone : null;
373
+ if (!to) {
374
+ throw new BotoZapError(
375
+ "conversation_recipient_unavailable",
376
+ "Conversa sem destinat\xE1rio utiliz\xE1vel no Contato.",
377
+ 422
378
+ );
379
+ }
380
+ return this.client.messages.send({ to, text: params.text, from });
381
+ }
337
382
  update(id, params) {
338
383
  return this.client.requestItem(
339
384
  "PATCH",
@@ -555,6 +600,52 @@ var Media = class {
555
600
  body: params
556
601
  });
557
602
  }
603
+ /**
604
+ * Busca os metadados de uma mídia RECEBIDA pelo `media_id` da Cloud API,
605
+ * incluindo `download_url` — uma URL assinada e efêmera que você pode baixar
606
+ * direto (GET), válida até `expires_at`.
607
+ *
608
+ * A mídia é espelhada de forma assíncrona; se você consultar antes de terminar,
609
+ * a rota responde 202 e este método lança `BotoZapError` com
610
+ * `code: "media_not_ready"`. Nesse caso, aguarde e retente — o segundo que faltar
611
+ * está em `err.headers?.["retry-after"]`:
612
+ *
613
+ * ```ts
614
+ * try {
615
+ * const media = await boto.media.get("wamid_media_id");
616
+ * // baixe media.download_url direto
617
+ * } catch (err) {
618
+ * if (err instanceof BotoZapError && err.code === "media_not_ready") {
619
+ * const wait = Number(err.headers?.["retry-after"] ?? 5);
620
+ * // retente após `wait` segundos
621
+ * }
622
+ * }
623
+ * ```
624
+ *
625
+ * Existe também `GET /v1/media/:id/download`, que responde 302 redirecionando
626
+ * para a mesma URL assinada; não há método SDK dedicado porque `download_url`
627
+ * (acima) já entrega essa URL sem o hop de redirect.
628
+ */
629
+ get(id) {
630
+ return this.client.requestItem(
631
+ "GET",
632
+ `/media/${encodeURIComponent(id)}`
633
+ );
634
+ }
635
+ };
636
+
637
+ // src/resources/events.ts
638
+ var Events = class {
639
+ constructor(client) {
640
+ this.client = client;
641
+ }
642
+ client;
643
+ list(params = {}) {
644
+ return this.client.requestCursorList("GET", "/events", {
645
+ query: { after: params.after, limit: params.limit },
646
+ signal: params.signal
647
+ });
648
+ }
558
649
  };
559
650
 
560
651
  // src/resources/read-only.ts
@@ -624,6 +715,7 @@ var BotoZap = class {
624
715
  phoneNumbers;
625
716
  flows;
626
717
  media;
718
+ events;
627
719
  users;
628
720
  apiLogs;
629
721
  webhookDeliveries;
@@ -653,6 +745,7 @@ var BotoZap = class {
653
745
  this.phoneNumbers = new PhoneNumbers(this);
654
746
  this.flows = new Flows(this);
655
747
  this.media = new Media(this);
748
+ this.events = new Events(this);
656
749
  this.users = new Users(this);
657
750
  this.apiLogs = new ApiLogs(this);
658
751
  this.webhookDeliveries = new WebhookDeliveries(this);
@@ -674,7 +767,8 @@ var BotoZap = class {
674
767
  "Content-Type": "application/json",
675
768
  Accept: "application/json"
676
769
  },
677
- body: opts.body === void 0 ? void 0 : JSON.stringify(opts.body)
770
+ body: opts.body === void 0 ? void 0 : JSON.stringify(opts.body),
771
+ signal: opts.signal
678
772
  });
679
773
  } catch (cause) {
680
774
  const detail = cause instanceof Error ? cause.message : String(cause);
@@ -686,8 +780,9 @@ var BotoZap = class {
686
780
  }
687
781
  const raw = await res.text();
688
782
  const data = raw ? safeJson(raw) : void 0;
689
- if (!res.ok) {
690
- const envelope = data;
783
+ const envelope = data;
784
+ const hasErrorEnvelope = typeof envelope === "object" && envelope !== null && typeof envelope.error === "object" && envelope.error !== null;
785
+ if (!res.ok || hasErrorEnvelope) {
691
786
  const headers = {};
692
787
  res.headers.forEach((value, key) => {
693
788
  headers[key] = value;