planvortex 0.19.0 → 0.21.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.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { P as Paginated, S as SocialNetwork, C as ConnectLink, a as ConnectResult, E as EnableResult, b as ConnectSession, A as Account, c as AccountMetrics, D as Destination, d as PublishSettings, e as PersistentMenu, f as Dashboard, M as MetricName, g as DashboardMetricsResult, h as PublicationsSummaryResult, T as TopPublicationsResult, i as PublicationsStatsResult, j as PlanUse, k as Publication, l as AiPlanResultsSort, m as PlannerTemplateName, n as AiPlanCreateRequest, o as AiPlanCreateResult, p as AiPlan, q as AiPlanResults, r as ClientApp, s as ClientAppInput, t as SocialCapabilities, u as CommentActions, v as SocialLimits, w as PublicationLimits, x as AspectRatiosByNetwork, y as PlannerTemplate, z as CommentNetwork, B as Comment, F as CommentThread, G as CommentReplyResult, H as ContactExtraData, I as Contact, J as ContactCreate, K as ContactUpdate, L as IntegrationProviderName, N as IntegrationProvider, O as Integration, Q as IntegrationConnectRequest, R as IntegrationUpdate, U as IntegrationPickerConfig, V as IntegrationCatalogPage, W as MessageTemplate, X as Conversation, Y as ConversationTotals, Z as Message, _ as MessageInput, $ as Client, a0 as Organization, a1 as AiSettings, a2 as ClientWithOrganizations, a3 as AccountSelection, a4 as PlanData, a5 as PlanUseData, a6 as ConnectToken, a7 as AiContext, a8 as SocialCredentialsInput, a9 as Product, aa as ProductInput, ab as ProductCatalog, ac as ProductCatalogInput, ad as PublicationInput, ae as PublicationState, af as PublicationStats, ag as PublicationStatsHistory, ah as Upload } from './index-DD7oGNvm.cjs';
2
- export { ai as AccountError, aj as AccountMetricRow, ak as AccountStateChange, al as AccountWebhookChangeBase, am as AccountWithError, an as AiImageOrigin, ao as AiPlanCostEstimate, ap as AiPlanDestination, aq as AiPlanError, ar as AiPlanNotice, as as AiPlanOptions, at as AiPlanOptionsInput, au as AiPlanResult, av as AiPlanResultsGroup, aw as AiPlanResultsTemplateGroup, ax as AiPlanSource, ay as AiPlanSourceImageInput, az as AiPlanSourceInput, aA as AiPlanSourceProduct, aB as AiPlanState, aC as ApiErrorBody, aD as AspectRatios, aE as AuthError, aF as ClientPlan, aG as CommentAuthor, aH as CommentChange, aI as ConnectSessionAccount, aJ as ContactChannel, aK as ContactError, aL as DashboardAiPlanRef, aM as DashboardPublicationRef, aN as DashboardRange, aO as EngagementBase, aP as FileError, aQ as FileFormat, aR as FileProperties, aS as FileType, aT as IntegrationCatalogProduct, aU as IntegrationConfig, aV as IntegrationError, aW as IntegrationErrorChange, aX as IntegrationFormField, aY as MessageChange, aZ as MessageEchoChange, a_ as MessageOptions, a$ as MessageType, b0 as MessagingError, b1 as MetricRow, b2 as NO_ERROR_CODE, b3 as OpenApiComponents, b4 as OpenApiOperations, b5 as OpenApiPaths, b6 as OpenApiWebhooks, b7 as OpenEnum, b8 as OrganizationError, b9 as PLANVORTEX_ERROR_RANGES, ba as PlanLimitError, bb as PlanVortexAuthenticationError, bc as PlanVortexConfigError, bd as PlanVortexConnectionError, be as PlanVortexError, bf as PlanVortexErrorOptions, bg as PlanVortexErrorRange, bh as PlannerTemplateField, bi as PlannerTemplateFieldType, bj as ProductError, bk as PublicationAiGenerated, bl as PublicationDestination, bm as PublicationError, bn as PublicationErrorDetail, bo as PublicationMetrics, bp as PublicationPending, bq as PublicationStatsPoint, br as PublicationType, bs as PublicationsSummary, bt as RssConfig, bu as SocialAuthorizationMethod, bv as SocialCredentials, bw as SocialIdentifier, bx as SocialIdentifierInput, by as SocialLimitsMap, bz as TOKEN_ERROR_CODES, bA as TopPublication, bB as UnknownWebhookChange, bC as UserError, bD as WebhookAlgorithm, bE as WebhookChange, bF as WebhookEvent, bG as WithAccount, bH as WithPublication, bI as WooCommerceConnectRequest, bJ as account, bK as accountId, bL as errorFamilyForCode, bM as isPlanVortexError, bN as isTokenError, bO as messageContact, bP as messageContactId, bQ as messageDirection, bR as messageFileIds, bS as messageFiles, bT as publication, bU as publicationId } from './index-DD7oGNvm.cjs';
1
+ import { P as Paginated, S as SocialNetwork, C as ConnectLink, a as ConnectResult, E as EnableResult, b as ConnectSession, A as Account, c as AccountMetrics, D as Destination, d as PublishSettings, e as PersistentMenu, f as Dashboard, M as MetricName, g as DashboardMetricsResult, h as PublicationsSummaryResult, T as TopPublicationsResult, i as PublicationsStatsResult, j as PlanUse, k as Publication, l as AiPlanResultsSort, m as PlannerTemplateName, n as AiPlanCreateRequest, o as AiPlanCreateResult, p as AiPlan, q as AiPlanResults, r as ClientApp, s as ClientAppInput, t as SocialCapabilities, u as CommentActions, v as SocialLimits, w as PublicationLimits, x as AspectRatiosByNetwork, y as PlannerTemplate, z as CommentNetwork, B as Comment, F as CommentThread, G as CommentReplyResult, H as ContactExtraData, I as Contact, J as ContactCreate, K as ContactUpdate, L as IntegrationProviderName, N as IntegrationProvider, O as Integration, Q as IntegrationConnectRequest, R as IntegrationUpdate, U as IntegrationPickerConfig, V as IntegrationCatalogPage, W as MessageTemplate, X as Conversation, Y as ConversationTotals, Z as Message, _ as MessageInput, $ as Client, a0 as Organization, a1 as AiSettings, a2 as ClientWithOrganizations, a3 as AccountSelection, a4 as PlanData, a5 as PlanUseData, a6 as ConnectToken, a7 as AiContext, a8 as SocialCredentialsInput, a9 as Product, aa as ProductInput, ab as ProductCatalog, ac as ProductCatalogInput, ad as PublicationInput, ae as PublicationState, af as PublicationStats, ag as PublicationStatsHistory, ah as Upload } from './index-BsE8URFA.cjs';
2
+ export { ai as AccountError, aj as AccountMetricRow, ak as AccountStateChange, al as AccountWebhookChangeBase, am as AccountWithError, an as AiImageOrigin, ao as AiPlanCostEstimate, ap as AiPlanDestination, aq as AiPlanError, ar as AiPlanNotice, as as AiPlanOptions, at as AiPlanOptionsInput, au as AiPlanResult, av as AiPlanResultsGroup, aw as AiPlanResultsTemplateGroup, ax as AiPlanSource, ay as AiPlanSourceImageInput, az as AiPlanSourceInput, aA as AiPlanSourceProduct, aB as AiPlanState, aC as ApiErrorBody, aD as AspectRatios, aE as AuthError, aF as ClientPlan, aG as CommentAuthor, aH as CommentChange, aI as ConnectSessionAccount, aJ as ContactChannel, aK as ContactError, aL as DashboardAiPlanRef, aM as DashboardPublicationRef, aN as DashboardRange, aO as EngagementBase, aP as FileError, aQ as FileFormat, aR as FileProperties, aS as FileType, aT as IntegrationCatalogProduct, aU as IntegrationConfig, aV as IntegrationError, aW as IntegrationErrorChange, aX as IntegrationFormField, aY as MessageChange, aZ as MessageEchoChange, a_ as MessageOptions, a$ as MessageType, b0 as MessagingError, b1 as MetricRow, b2 as NO_ERROR_CODE, b3 as OpenApiComponents, b4 as OpenApiOperations, b5 as OpenApiPaths, b6 as OpenApiWebhooks, b7 as OpenEnum, b8 as OrganizationError, b9 as PLANVORTEX_ERROR_RANGES, ba as PlanLimitError, bb as PlanVortexAuthenticationError, bc as PlanVortexConfigError, bd as PlanVortexConnectionError, be as PlanVortexError, bf as PlanVortexErrorOptions, bg as PlanVortexErrorRange, bh as PlannerTemplateField, bi as PlannerTemplateFieldType, bj as ProductError, bk as PublicationAiGenerated, bl as PublicationDestination, bm as PublicationError, bn as PublicationErrorDetail, bo as PublicationMetrics, bp as PublicationPending, bq as PublicationStatsPoint, br as PublicationType, bs as PublicationsSummary, bt as RssConfig, bu as SocialAuthorizationMethod, bv as SocialCredentials, bw as SocialIdentifier, bx as SocialIdentifierInput, by as SocialLimitsMap, bz as TOKEN_ERROR_CODES, bA as TopPublication, bB as UnknownWebhookChange, bC as UserError, bD as WebhookAlgorithm, bE as WebhookChange, bF as WebhookEvent, bG as WithAccount, bH as WithPublication, bI as WooCommerceConnectRequest, bJ as account, bK as accountId, bL as errorFamilyForCode, bM as isPlanVortexError, bN as isTokenError, bO as messageContact, bP as messageContactId, bQ as messageDirection, bR as messageFileIds, bS as messageFiles, bT as publication, bU as publicationId } from './index-BsE8URFA.cjs';
3
3
 
4
4
  /**
5
5
  * Las dos constantes que todo lo demás necesita. Viven aparte de `index.ts` para que `client.ts`
@@ -15,7 +15,7 @@ declare const PLANVORTEX_API_URL = "https://api.planvortex.com/v1.0.0";
15
15
  * de ejecución obliga a empaquetarlo y se rompe distinto en ESM y en CJS. La mantiene sincronizada
16
16
  * un test.
17
17
  */
18
- declare const VERSION = "0.19.0";
18
+ declare const VERSION = "0.21.0";
19
19
 
20
20
  /** `fetch` con la firma que usamos. Se puede sustituir en tests o para meter un proxy. */
21
21
  type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
@@ -87,8 +87,12 @@ interface HttpRequest {
87
87
  * nada — hoy, `POST /oauth/token`.
88
88
  */
89
89
  idempotent?: boolean;
90
- /** `none` salta el parseo del cuerpo. Por defecto se intenta JSON. */
91
- parse?: "json" | "none";
90
+ /**
91
+ * `none` salta el parseo del cuerpo y `binary` lo devuelve como bytes (`Uint8Array`), que es lo
92
+ * que hace falta para un archivo. Por defecto se intenta JSON. Un error se lee SIEMPRE como
93
+ * JSON, sea cual sea este valor: el cuerpo de un 4xx es el sobre de error de la API.
94
+ */
95
+ parse?: "json" | "none" | "binary";
92
96
  }
93
97
  interface HttpResponse<T> {
94
98
  data: T;
@@ -113,6 +117,23 @@ interface RequestSender {
113
117
  request<T>(request: HttpRequest): Promise<HttpResponse<T>>;
114
118
  }
115
119
  type Query = Record<string, QueryValue>;
120
+ /**
121
+ * Un archivo que llegó de la red (la foto de un mensaje privado, el sticker de un comentario),
122
+ * pedido a PlanVortex, que lo pide a la red en ese momento y lo reenvía sin guardar una copia.
123
+ */
124
+ interface DownloadedFile {
125
+ /** Los bytes, tal cual los dio la red. */
126
+ data: Uint8Array;
127
+ /** El `Content-Type` real del archivo. Es el que manda, no el `mime_type` que se apuntó. */
128
+ contentType: string;
129
+ /** El nombre del documento, cuando la red lo da. */
130
+ fileName: string | undefined;
131
+ /**
132
+ * `inline` para imágenes, vídeos y audios; `attachment` para todo lo demás. Un documento lo
133
+ * mandó alguien de fuera del negocio: no lo pintes dentro de tus propias páginas.
134
+ */
135
+ disposition: "inline" | "attachment";
136
+ }
116
137
  /** Opciones por llamada que cualquier método acepta: cancelar y ajustar el timeout. */
117
138
  interface RequestOptions {
118
139
  signal?: AbortSignal | undefined;
@@ -122,6 +143,12 @@ declare abstract class Resource {
122
143
  protected readonly client: RequestSender;
123
144
  constructor(client: RequestSender);
124
145
  protected dispatch<T>(request: HttpRequest, options?: RequestOptions): Promise<T>;
146
+ /**
147
+ * Un archivo, en bytes y con lo que dicen sus cabeceras. Lo usan las dos rutas de archivos de la
148
+ * API, la de mensajes y la de comentarios. Lleva `_` al final por lo mismo que los verbos llevan
149
+ * `http` delante: el método público de los recursos se llama `downloadFile`.
150
+ */
151
+ protected downloadFile_(path: string, options?: RequestOptions): Promise<DownloadedFile>;
125
152
  protected httpGet<T>(path: string, query?: Query, options?: RequestOptions): Promise<T>;
126
153
  protected httpPost<T>(path: string, body?: unknown, options?: RequestOptions, query?: Query): Promise<T>;
127
154
  protected httpPut<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
@@ -171,7 +198,7 @@ declare const MAX_PAGES = 10000;
171
198
  * `catalog.socialCapabilities()`, aplicadas en el servidor: es la forma de pedir "las cuentas con
172
199
  * las que puedo publicar" sin mantener tu propia tabla de qué red hace qué.
173
200
  */
174
- type AccountCapability = "publications" | "messages" | "products" | "webhooks" | "persistent_menu" | "comments";
201
+ type AccountCapability = "publications" | "messages" | "products" | "webhooks" | "persistent_menu" | "comments" | "statistics";
175
202
  interface AccountListOptions extends PageOptions {
176
203
  /** Búsqueda libre sobre el nombre y el usuario de la cuenta. */
177
204
  name?: string | undefined;
@@ -181,7 +208,9 @@ interface AccountListOptions extends PageOptions {
181
208
  accounts?: readonly string[] | undefined;
182
209
  /**
183
210
  * Sólo las cuentas cuya red sabe hacer esto. `comments` mira además la cuenta: deja fuera los
184
- * perfiles personales de LinkedIn, que no tienen bandeja aunque las páginas sí.
211
+ * perfiles personales de LinkedIn, que no tienen bandeja aunque las páginas sí. `statistics`
212
+ * deja fuera las redes de las que PlanVortex no lee ninguna métrica (hoy WhatsApp): son las
213
+ * cuentas que tiene sentido ofrecer en una pantalla de estadísticas.
185
214
  */
186
215
  capability?: AccountCapability | undefined;
187
216
  }
@@ -889,8 +918,8 @@ declare class CatalogResource extends Resource {
889
918
  */
890
919
  allowedSocialMessages(options?: RequestOptions): Promise<SocialNetwork[]>;
891
920
  /**
892
- * La matriz red → qué sabe hacer: publicar, mensajes, productos, webhooks, menú persistente y
893
- * comentarios.
921
+ * La matriz red → qué sabe hacer: publicar, mensajes, productos, webhooks, menú persistente,
922
+ * comentarios y estadísticas (`statistics`, hoy todas menos WhatsApp).
894
923
  *
895
924
  * Es lo que evita ofrecer una cuenta en una pantalla que su red no soporta — WhatsApp en el
896
925
  * compositor, LinkedIn en el chat.
@@ -1111,6 +1140,20 @@ declare class CommentsResource extends Resource {
1111
1140
  * justo después de responder no enseñaría nada y parecería que no se envió.
1112
1141
  */
1113
1142
  replies(idOrganization: string, idComment: string, options?: CommentThreadOptions & RequestOptions): Promise<CommentThread>;
1143
+ /**
1144
+ * Un archivo del comentario (la foto, el GIF, el sticker o el vídeo de `files_urls[index]`),
1145
+ * pedido a la red en ese momento: PlanVortex no lo guarda y lo reenvía sin quedarse una copia.
1146
+ *
1147
+ * Hace falta cuando el archivo no trae `url` (LinkedIn solo da el id de la imagen; el enlace de
1148
+ * Telegram lleva el token del bot; el vídeo de Bluesky es una lista HLS) o cuando el `url` ya no
1149
+ * carga (Facebook, Threads y Discord lo caducan). Si la red ya no lo tiene, error 1515; si el
1150
+ * comentario no tiene archivo en esa posición, 2602. Un bot de Telegram no baja más de 20 MB:
1151
+ * pasado eso es un 1515 con `data.reason: "too_big"`.
1152
+ *
1153
+ * Un `disposition: "attachment"` es un documento que alguien de fuera colgó: no lo pintes dentro
1154
+ * de tus propias páginas.
1155
+ */
1156
+ downloadFile(idOrganization: string, idComment: string, index: number, options?: RequestOptions): Promise<DownloadedFile>;
1114
1157
  /**
1115
1158
  * Responde EN PÚBLICO, colgando de ese comentario.
1116
1159
  *
@@ -1174,6 +1217,9 @@ declare class CommentsResource extends Resource {
1174
1217
  * lo explica y {@link ContactsResource.merge} lo evita.
1175
1218
  * - **Borrar un contacto borra también sus mensajes**, y borrar los de la organización los borra
1176
1219
  * todos. No hay papelera.
1220
+ * - **En WhatsApp un contacto puede no tener teléfono.** Quien usa nombre de usuario puede no
1221
+ * darnos su número: su `external_identifier` es entonces su BSUID (`ES.1349...`, el mismo valor
1222
+ * que `user_id`), que no se enseña como si fuera un teléfono. Ver el tipo `SocialIdentifier`.
1177
1223
  * - **Exige plan de pago** (error 516).
1178
1224
  */
1179
1225
 
@@ -1608,6 +1654,20 @@ declare class MessagesResource extends Resource {
1608
1654
  * para desambiguar entre idiomas de la misma plantilla. Van en la query, no en el cuerpo.
1609
1655
  */
1610
1656
  deleteTemplate(idOrganization: string, idAccount: string, templateId: string, templateName: string, options?: RequestOptions): Promise<void>;
1657
+ /**
1658
+ * Un archivo de un mensaje que llegó de la red (`message_options.files_urls[index]`): una foto,
1659
+ * un vídeo, una nota de voz, un documento o un sticker. PlanVortex no lo guarda: lo pide a la red
1660
+ * en ese momento y lo reenvía sin quedarse una copia.
1661
+ *
1662
+ * En WhatsApp es la ÚNICA forma de abrir un archivo: ninguno trae `url`, porque WhatsApp solo los
1663
+ * entrega con el token de la cuenta. En Instagram y Messenger hace falta cuando el `url` del CDN
1664
+ * de Meta caducó. WhatsApp suelta un archivo 7 días después de que llegara: a partir de ahí es un
1665
+ * error 1515. Un 1516 es que el mensaje no es de esa cuenta o no tiene archivo en esa posición.
1666
+ *
1667
+ * Un `disposition: "attachment"` es un documento que mandó alguien de fuera: no lo pintes dentro
1668
+ * de tus propias páginas.
1669
+ */
1670
+ downloadFile(idOrganization: string, idAccount: string, idMessage: string, index: number, options?: RequestOptions): Promise<DownloadedFile>;
1611
1671
  private accountPath;
1612
1672
  private threadPath;
1613
1673
  }
@@ -2280,4 +2340,4 @@ interface AuthProvider {
2280
2340
  /** Margen con el que se pide un token nuevo antes de que caduque el que hay. */
2281
2341
  declare const TOKEN_REFRESH_MARGIN_MS = 60000;
2282
2342
 
2283
- export { Account, type AccountCapability, type AccountDestinationOptions, type AccountListOptions, AccountMetrics, type AccountMetricsOptions, AccountSelection, AccountsResource, AiContext, AiPlan, AiPlanCreateRequest, AiPlanCreateResult, type AiPlanListOptions, type AiPlanRegenerateResult, type AiPlanRegenerateTarget, AiPlanResults, type AiPlanResultsOptions, AiPlanResultsSort, AiPlansResource, AiSettings, AppsResource, AspectRatiosByNetwork, type AuthProvider, CatalogResource, type ChildOrganizationListOptions, Client, ClientApp, ClientAppInput, type ClientCredentialsToken, type ClientListOptions, ClientWithOrganizations, ClientsResource, Comment, CommentActions, type CommentListOptions, CommentNetwork, CommentReplyResult, CommentThread, type CommentThreadOptions, type CommentUpdate, CommentsResource, type ConnectCallbackParams, ConnectLink, type ConnectLinkOptions, type ConnectLinksOptions, ConnectResult, ConnectSession, ConnectToken, type ConnectTokenOptions, Contact, ContactCreate, ContactExtraData, type ContactExtraFilter, type ContactListOptions, ContactUpdate, ContactsResource, Conversation, type ConversationGroupBy, ConversationTotals, type ConversationTotalsOptions, DEFAULT_PAGE_SIZE, DEFAULT_RETRY, DEFAULT_TIMEOUT_MS, Dashboard, DashboardMetricsResult, DashboardResource, Destination, EnableResult, type FetchLike, type FileInput, type FileSource, type HttpHooks, type HttpMethod, type HttpRequest, type HttpResponse, type ImportError, type ImportFileInput, type ImportResult, Integration, IntegrationCatalogPage, IntegrationConnectRequest, type IntegrationListOptions, IntegrationPickerConfig, type IntegrationProductsOptions, IntegrationProvider, IntegrationProviderName, IntegrationUpdate, IntegrationsResource, MAX_PAGES, Message, MessageInput, MessageTemplate, type MessageTemplateResult, MessagesResource, MetricName, type MetricsGroupBy, type MetricsOptions, Organization, type OrganizationInput, type OrganizationListOptions, type OrganizationOptions, type OrganizationPlanInput, OrganizationsResource, PLANVORTEX_API_URL, type PageOptions, Paginated, PersistentMenu, PlanData, PlanUse, PlanUseData, PlanVortex, type PlanVortexOptions, PlannerTemplate, PlannerTemplateName, Product, ProductCatalog, ProductCatalogInput, ProductInput, ProductsResource, Publication, PublicationInput, PublicationLimits, type PublicationListOptions, type PublicationRetryResult, PublicationState, PublicationStats, PublicationStatsHistory, PublicationsResource, type PublicationsStatsOptions, PublicationsStatsResult, PublicationsSummaryResult, PublishSettings, type QueryValue, type RangeOptions, type RequestInfo, type RequestOptions, type RequestSender, type ResponseInfo, type RetryConfig, type RetryInfo, SocialCapabilities, SocialLimits, SocialNetwork, TOKEN_REFRESH_MARGIN_MS, type TopPublicationsOptions, TopPublicationsResult, Upload, type UploadUpdate, UploadsResource, VERSION, guessContentType };
2343
+ export { Account, type AccountCapability, type AccountDestinationOptions, type AccountListOptions, AccountMetrics, type AccountMetricsOptions, AccountSelection, AccountsResource, AiContext, AiPlan, AiPlanCreateRequest, AiPlanCreateResult, type AiPlanListOptions, type AiPlanRegenerateResult, type AiPlanRegenerateTarget, AiPlanResults, type AiPlanResultsOptions, AiPlanResultsSort, AiPlansResource, AiSettings, AppsResource, AspectRatiosByNetwork, type AuthProvider, CatalogResource, type ChildOrganizationListOptions, Client, ClientApp, ClientAppInput, type ClientCredentialsToken, type ClientListOptions, ClientWithOrganizations, ClientsResource, Comment, CommentActions, type CommentListOptions, CommentNetwork, CommentReplyResult, CommentThread, type CommentThreadOptions, type CommentUpdate, CommentsResource, type ConnectCallbackParams, ConnectLink, type ConnectLinkOptions, type ConnectLinksOptions, ConnectResult, ConnectSession, ConnectToken, type ConnectTokenOptions, Contact, ContactCreate, ContactExtraData, type ContactExtraFilter, type ContactListOptions, ContactUpdate, ContactsResource, Conversation, type ConversationGroupBy, ConversationTotals, type ConversationTotalsOptions, DEFAULT_PAGE_SIZE, DEFAULT_RETRY, DEFAULT_TIMEOUT_MS, Dashboard, DashboardMetricsResult, DashboardResource, Destination, type DownloadedFile, EnableResult, type FetchLike, type FileInput, type FileSource, type HttpHooks, type HttpMethod, type HttpRequest, type HttpResponse, type ImportError, type ImportFileInput, type ImportResult, Integration, IntegrationCatalogPage, IntegrationConnectRequest, type IntegrationListOptions, IntegrationPickerConfig, type IntegrationProductsOptions, IntegrationProvider, IntegrationProviderName, IntegrationUpdate, IntegrationsResource, MAX_PAGES, Message, MessageInput, MessageTemplate, type MessageTemplateResult, MessagesResource, MetricName, type MetricsGroupBy, type MetricsOptions, Organization, type OrganizationInput, type OrganizationListOptions, type OrganizationOptions, type OrganizationPlanInput, OrganizationsResource, PLANVORTEX_API_URL, type PageOptions, Paginated, PersistentMenu, PlanData, PlanUse, PlanUseData, PlanVortex, type PlanVortexOptions, PlannerTemplate, PlannerTemplateName, Product, ProductCatalog, ProductCatalogInput, ProductInput, ProductsResource, Publication, PublicationInput, PublicationLimits, type PublicationListOptions, type PublicationRetryResult, PublicationState, PublicationStats, PublicationStatsHistory, PublicationsResource, type PublicationsStatsOptions, PublicationsStatsResult, PublicationsSummaryResult, PublishSettings, type QueryValue, type RangeOptions, type RequestInfo, type RequestOptions, type RequestSender, type ResponseInfo, type RetryConfig, type RetryInfo, SocialCapabilities, SocialLimits, SocialNetwork, TOKEN_REFRESH_MARGIN_MS, type TopPublicationsOptions, TopPublicationsResult, Upload, type UploadUpdate, UploadsResource, VERSION, guessContentType };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { P as Paginated, S as SocialNetwork, C as ConnectLink, a as ConnectResult, E as EnableResult, b as ConnectSession, A as Account, c as AccountMetrics, D as Destination, d as PublishSettings, e as PersistentMenu, f as Dashboard, M as MetricName, g as DashboardMetricsResult, h as PublicationsSummaryResult, T as TopPublicationsResult, i as PublicationsStatsResult, j as PlanUse, k as Publication, l as AiPlanResultsSort, m as PlannerTemplateName, n as AiPlanCreateRequest, o as AiPlanCreateResult, p as AiPlan, q as AiPlanResults, r as ClientApp, s as ClientAppInput, t as SocialCapabilities, u as CommentActions, v as SocialLimits, w as PublicationLimits, x as AspectRatiosByNetwork, y as PlannerTemplate, z as CommentNetwork, B as Comment, F as CommentThread, G as CommentReplyResult, H as ContactExtraData, I as Contact, J as ContactCreate, K as ContactUpdate, L as IntegrationProviderName, N as IntegrationProvider, O as Integration, Q as IntegrationConnectRequest, R as IntegrationUpdate, U as IntegrationPickerConfig, V as IntegrationCatalogPage, W as MessageTemplate, X as Conversation, Y as ConversationTotals, Z as Message, _ as MessageInput, $ as Client, a0 as Organization, a1 as AiSettings, a2 as ClientWithOrganizations, a3 as AccountSelection, a4 as PlanData, a5 as PlanUseData, a6 as ConnectToken, a7 as AiContext, a8 as SocialCredentialsInput, a9 as Product, aa as ProductInput, ab as ProductCatalog, ac as ProductCatalogInput, ad as PublicationInput, ae as PublicationState, af as PublicationStats, ag as PublicationStatsHistory, ah as Upload } from './index-DD7oGNvm.js';
2
- export { ai as AccountError, aj as AccountMetricRow, ak as AccountStateChange, al as AccountWebhookChangeBase, am as AccountWithError, an as AiImageOrigin, ao as AiPlanCostEstimate, ap as AiPlanDestination, aq as AiPlanError, ar as AiPlanNotice, as as AiPlanOptions, at as AiPlanOptionsInput, au as AiPlanResult, av as AiPlanResultsGroup, aw as AiPlanResultsTemplateGroup, ax as AiPlanSource, ay as AiPlanSourceImageInput, az as AiPlanSourceInput, aA as AiPlanSourceProduct, aB as AiPlanState, aC as ApiErrorBody, aD as AspectRatios, aE as AuthError, aF as ClientPlan, aG as CommentAuthor, aH as CommentChange, aI as ConnectSessionAccount, aJ as ContactChannel, aK as ContactError, aL as DashboardAiPlanRef, aM as DashboardPublicationRef, aN as DashboardRange, aO as EngagementBase, aP as FileError, aQ as FileFormat, aR as FileProperties, aS as FileType, aT as IntegrationCatalogProduct, aU as IntegrationConfig, aV as IntegrationError, aW as IntegrationErrorChange, aX as IntegrationFormField, aY as MessageChange, aZ as MessageEchoChange, a_ as MessageOptions, a$ as MessageType, b0 as MessagingError, b1 as MetricRow, b2 as NO_ERROR_CODE, b3 as OpenApiComponents, b4 as OpenApiOperations, b5 as OpenApiPaths, b6 as OpenApiWebhooks, b7 as OpenEnum, b8 as OrganizationError, b9 as PLANVORTEX_ERROR_RANGES, ba as PlanLimitError, bb as PlanVortexAuthenticationError, bc as PlanVortexConfigError, bd as PlanVortexConnectionError, be as PlanVortexError, bf as PlanVortexErrorOptions, bg as PlanVortexErrorRange, bh as PlannerTemplateField, bi as PlannerTemplateFieldType, bj as ProductError, bk as PublicationAiGenerated, bl as PublicationDestination, bm as PublicationError, bn as PublicationErrorDetail, bo as PublicationMetrics, bp as PublicationPending, bq as PublicationStatsPoint, br as PublicationType, bs as PublicationsSummary, bt as RssConfig, bu as SocialAuthorizationMethod, bv as SocialCredentials, bw as SocialIdentifier, bx as SocialIdentifierInput, by as SocialLimitsMap, bz as TOKEN_ERROR_CODES, bA as TopPublication, bB as UnknownWebhookChange, bC as UserError, bD as WebhookAlgorithm, bE as WebhookChange, bF as WebhookEvent, bG as WithAccount, bH as WithPublication, bI as WooCommerceConnectRequest, bJ as account, bK as accountId, bL as errorFamilyForCode, bM as isPlanVortexError, bN as isTokenError, bO as messageContact, bP as messageContactId, bQ as messageDirection, bR as messageFileIds, bS as messageFiles, bT as publication, bU as publicationId } from './index-DD7oGNvm.js';
1
+ import { P as Paginated, S as SocialNetwork, C as ConnectLink, a as ConnectResult, E as EnableResult, b as ConnectSession, A as Account, c as AccountMetrics, D as Destination, d as PublishSettings, e as PersistentMenu, f as Dashboard, M as MetricName, g as DashboardMetricsResult, h as PublicationsSummaryResult, T as TopPublicationsResult, i as PublicationsStatsResult, j as PlanUse, k as Publication, l as AiPlanResultsSort, m as PlannerTemplateName, n as AiPlanCreateRequest, o as AiPlanCreateResult, p as AiPlan, q as AiPlanResults, r as ClientApp, s as ClientAppInput, t as SocialCapabilities, u as CommentActions, v as SocialLimits, w as PublicationLimits, x as AspectRatiosByNetwork, y as PlannerTemplate, z as CommentNetwork, B as Comment, F as CommentThread, G as CommentReplyResult, H as ContactExtraData, I as Contact, J as ContactCreate, K as ContactUpdate, L as IntegrationProviderName, N as IntegrationProvider, O as Integration, Q as IntegrationConnectRequest, R as IntegrationUpdate, U as IntegrationPickerConfig, V as IntegrationCatalogPage, W as MessageTemplate, X as Conversation, Y as ConversationTotals, Z as Message, _ as MessageInput, $ as Client, a0 as Organization, a1 as AiSettings, a2 as ClientWithOrganizations, a3 as AccountSelection, a4 as PlanData, a5 as PlanUseData, a6 as ConnectToken, a7 as AiContext, a8 as SocialCredentialsInput, a9 as Product, aa as ProductInput, ab as ProductCatalog, ac as ProductCatalogInput, ad as PublicationInput, ae as PublicationState, af as PublicationStats, ag as PublicationStatsHistory, ah as Upload } from './index-BsE8URFA.js';
2
+ export { ai as AccountError, aj as AccountMetricRow, ak as AccountStateChange, al as AccountWebhookChangeBase, am as AccountWithError, an as AiImageOrigin, ao as AiPlanCostEstimate, ap as AiPlanDestination, aq as AiPlanError, ar as AiPlanNotice, as as AiPlanOptions, at as AiPlanOptionsInput, au as AiPlanResult, av as AiPlanResultsGroup, aw as AiPlanResultsTemplateGroup, ax as AiPlanSource, ay as AiPlanSourceImageInput, az as AiPlanSourceInput, aA as AiPlanSourceProduct, aB as AiPlanState, aC as ApiErrorBody, aD as AspectRatios, aE as AuthError, aF as ClientPlan, aG as CommentAuthor, aH as CommentChange, aI as ConnectSessionAccount, aJ as ContactChannel, aK as ContactError, aL as DashboardAiPlanRef, aM as DashboardPublicationRef, aN as DashboardRange, aO as EngagementBase, aP as FileError, aQ as FileFormat, aR as FileProperties, aS as FileType, aT as IntegrationCatalogProduct, aU as IntegrationConfig, aV as IntegrationError, aW as IntegrationErrorChange, aX as IntegrationFormField, aY as MessageChange, aZ as MessageEchoChange, a_ as MessageOptions, a$ as MessageType, b0 as MessagingError, b1 as MetricRow, b2 as NO_ERROR_CODE, b3 as OpenApiComponents, b4 as OpenApiOperations, b5 as OpenApiPaths, b6 as OpenApiWebhooks, b7 as OpenEnum, b8 as OrganizationError, b9 as PLANVORTEX_ERROR_RANGES, ba as PlanLimitError, bb as PlanVortexAuthenticationError, bc as PlanVortexConfigError, bd as PlanVortexConnectionError, be as PlanVortexError, bf as PlanVortexErrorOptions, bg as PlanVortexErrorRange, bh as PlannerTemplateField, bi as PlannerTemplateFieldType, bj as ProductError, bk as PublicationAiGenerated, bl as PublicationDestination, bm as PublicationError, bn as PublicationErrorDetail, bo as PublicationMetrics, bp as PublicationPending, bq as PublicationStatsPoint, br as PublicationType, bs as PublicationsSummary, bt as RssConfig, bu as SocialAuthorizationMethod, bv as SocialCredentials, bw as SocialIdentifier, bx as SocialIdentifierInput, by as SocialLimitsMap, bz as TOKEN_ERROR_CODES, bA as TopPublication, bB as UnknownWebhookChange, bC as UserError, bD as WebhookAlgorithm, bE as WebhookChange, bF as WebhookEvent, bG as WithAccount, bH as WithPublication, bI as WooCommerceConnectRequest, bJ as account, bK as accountId, bL as errorFamilyForCode, bM as isPlanVortexError, bN as isTokenError, bO as messageContact, bP as messageContactId, bQ as messageDirection, bR as messageFileIds, bS as messageFiles, bT as publication, bU as publicationId } from './index-BsE8URFA.js';
3
3
 
4
4
  /**
5
5
  * Las dos constantes que todo lo demás necesita. Viven aparte de `index.ts` para que `client.ts`
@@ -15,7 +15,7 @@ declare const PLANVORTEX_API_URL = "https://api.planvortex.com/v1.0.0";
15
15
  * de ejecución obliga a empaquetarlo y se rompe distinto en ESM y en CJS. La mantiene sincronizada
16
16
  * un test.
17
17
  */
18
- declare const VERSION = "0.19.0";
18
+ declare const VERSION = "0.21.0";
19
19
 
20
20
  /** `fetch` con la firma que usamos. Se puede sustituir en tests o para meter un proxy. */
21
21
  type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
@@ -87,8 +87,12 @@ interface HttpRequest {
87
87
  * nada — hoy, `POST /oauth/token`.
88
88
  */
89
89
  idempotent?: boolean;
90
- /** `none` salta el parseo del cuerpo. Por defecto se intenta JSON. */
91
- parse?: "json" | "none";
90
+ /**
91
+ * `none` salta el parseo del cuerpo y `binary` lo devuelve como bytes (`Uint8Array`), que es lo
92
+ * que hace falta para un archivo. Por defecto se intenta JSON. Un error se lee SIEMPRE como
93
+ * JSON, sea cual sea este valor: el cuerpo de un 4xx es el sobre de error de la API.
94
+ */
95
+ parse?: "json" | "none" | "binary";
92
96
  }
93
97
  interface HttpResponse<T> {
94
98
  data: T;
@@ -113,6 +117,23 @@ interface RequestSender {
113
117
  request<T>(request: HttpRequest): Promise<HttpResponse<T>>;
114
118
  }
115
119
  type Query = Record<string, QueryValue>;
120
+ /**
121
+ * Un archivo que llegó de la red (la foto de un mensaje privado, el sticker de un comentario),
122
+ * pedido a PlanVortex, que lo pide a la red en ese momento y lo reenvía sin guardar una copia.
123
+ */
124
+ interface DownloadedFile {
125
+ /** Los bytes, tal cual los dio la red. */
126
+ data: Uint8Array;
127
+ /** El `Content-Type` real del archivo. Es el que manda, no el `mime_type` que se apuntó. */
128
+ contentType: string;
129
+ /** El nombre del documento, cuando la red lo da. */
130
+ fileName: string | undefined;
131
+ /**
132
+ * `inline` para imágenes, vídeos y audios; `attachment` para todo lo demás. Un documento lo
133
+ * mandó alguien de fuera del negocio: no lo pintes dentro de tus propias páginas.
134
+ */
135
+ disposition: "inline" | "attachment";
136
+ }
116
137
  /** Opciones por llamada que cualquier método acepta: cancelar y ajustar el timeout. */
117
138
  interface RequestOptions {
118
139
  signal?: AbortSignal | undefined;
@@ -122,6 +143,12 @@ declare abstract class Resource {
122
143
  protected readonly client: RequestSender;
123
144
  constructor(client: RequestSender);
124
145
  protected dispatch<T>(request: HttpRequest, options?: RequestOptions): Promise<T>;
146
+ /**
147
+ * Un archivo, en bytes y con lo que dicen sus cabeceras. Lo usan las dos rutas de archivos de la
148
+ * API, la de mensajes y la de comentarios. Lleva `_` al final por lo mismo que los verbos llevan
149
+ * `http` delante: el método público de los recursos se llama `downloadFile`.
150
+ */
151
+ protected downloadFile_(path: string, options?: RequestOptions): Promise<DownloadedFile>;
125
152
  protected httpGet<T>(path: string, query?: Query, options?: RequestOptions): Promise<T>;
126
153
  protected httpPost<T>(path: string, body?: unknown, options?: RequestOptions, query?: Query): Promise<T>;
127
154
  protected httpPut<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
@@ -171,7 +198,7 @@ declare const MAX_PAGES = 10000;
171
198
  * `catalog.socialCapabilities()`, aplicadas en el servidor: es la forma de pedir "las cuentas con
172
199
  * las que puedo publicar" sin mantener tu propia tabla de qué red hace qué.
173
200
  */
174
- type AccountCapability = "publications" | "messages" | "products" | "webhooks" | "persistent_menu" | "comments";
201
+ type AccountCapability = "publications" | "messages" | "products" | "webhooks" | "persistent_menu" | "comments" | "statistics";
175
202
  interface AccountListOptions extends PageOptions {
176
203
  /** Búsqueda libre sobre el nombre y el usuario de la cuenta. */
177
204
  name?: string | undefined;
@@ -181,7 +208,9 @@ interface AccountListOptions extends PageOptions {
181
208
  accounts?: readonly string[] | undefined;
182
209
  /**
183
210
  * Sólo las cuentas cuya red sabe hacer esto. `comments` mira además la cuenta: deja fuera los
184
- * perfiles personales de LinkedIn, que no tienen bandeja aunque las páginas sí.
211
+ * perfiles personales de LinkedIn, que no tienen bandeja aunque las páginas sí. `statistics`
212
+ * deja fuera las redes de las que PlanVortex no lee ninguna métrica (hoy WhatsApp): son las
213
+ * cuentas que tiene sentido ofrecer en una pantalla de estadísticas.
185
214
  */
186
215
  capability?: AccountCapability | undefined;
187
216
  }
@@ -889,8 +918,8 @@ declare class CatalogResource extends Resource {
889
918
  */
890
919
  allowedSocialMessages(options?: RequestOptions): Promise<SocialNetwork[]>;
891
920
  /**
892
- * La matriz red → qué sabe hacer: publicar, mensajes, productos, webhooks, menú persistente y
893
- * comentarios.
921
+ * La matriz red → qué sabe hacer: publicar, mensajes, productos, webhooks, menú persistente,
922
+ * comentarios y estadísticas (`statistics`, hoy todas menos WhatsApp).
894
923
  *
895
924
  * Es lo que evita ofrecer una cuenta en una pantalla que su red no soporta — WhatsApp en el
896
925
  * compositor, LinkedIn en el chat.
@@ -1111,6 +1140,20 @@ declare class CommentsResource extends Resource {
1111
1140
  * justo después de responder no enseñaría nada y parecería que no se envió.
1112
1141
  */
1113
1142
  replies(idOrganization: string, idComment: string, options?: CommentThreadOptions & RequestOptions): Promise<CommentThread>;
1143
+ /**
1144
+ * Un archivo del comentario (la foto, el GIF, el sticker o el vídeo de `files_urls[index]`),
1145
+ * pedido a la red en ese momento: PlanVortex no lo guarda y lo reenvía sin quedarse una copia.
1146
+ *
1147
+ * Hace falta cuando el archivo no trae `url` (LinkedIn solo da el id de la imagen; el enlace de
1148
+ * Telegram lleva el token del bot; el vídeo de Bluesky es una lista HLS) o cuando el `url` ya no
1149
+ * carga (Facebook, Threads y Discord lo caducan). Si la red ya no lo tiene, error 1515; si el
1150
+ * comentario no tiene archivo en esa posición, 2602. Un bot de Telegram no baja más de 20 MB:
1151
+ * pasado eso es un 1515 con `data.reason: "too_big"`.
1152
+ *
1153
+ * Un `disposition: "attachment"` es un documento que alguien de fuera colgó: no lo pintes dentro
1154
+ * de tus propias páginas.
1155
+ */
1156
+ downloadFile(idOrganization: string, idComment: string, index: number, options?: RequestOptions): Promise<DownloadedFile>;
1114
1157
  /**
1115
1158
  * Responde EN PÚBLICO, colgando de ese comentario.
1116
1159
  *
@@ -1174,6 +1217,9 @@ declare class CommentsResource extends Resource {
1174
1217
  * lo explica y {@link ContactsResource.merge} lo evita.
1175
1218
  * - **Borrar un contacto borra también sus mensajes**, y borrar los de la organización los borra
1176
1219
  * todos. No hay papelera.
1220
+ * - **En WhatsApp un contacto puede no tener teléfono.** Quien usa nombre de usuario puede no
1221
+ * darnos su número: su `external_identifier` es entonces su BSUID (`ES.1349...`, el mismo valor
1222
+ * que `user_id`), que no se enseña como si fuera un teléfono. Ver el tipo `SocialIdentifier`.
1177
1223
  * - **Exige plan de pago** (error 516).
1178
1224
  */
1179
1225
 
@@ -1608,6 +1654,20 @@ declare class MessagesResource extends Resource {
1608
1654
  * para desambiguar entre idiomas de la misma plantilla. Van en la query, no en el cuerpo.
1609
1655
  */
1610
1656
  deleteTemplate(idOrganization: string, idAccount: string, templateId: string, templateName: string, options?: RequestOptions): Promise<void>;
1657
+ /**
1658
+ * Un archivo de un mensaje que llegó de la red (`message_options.files_urls[index]`): una foto,
1659
+ * un vídeo, una nota de voz, un documento o un sticker. PlanVortex no lo guarda: lo pide a la red
1660
+ * en ese momento y lo reenvía sin quedarse una copia.
1661
+ *
1662
+ * En WhatsApp es la ÚNICA forma de abrir un archivo: ninguno trae `url`, porque WhatsApp solo los
1663
+ * entrega con el token de la cuenta. En Instagram y Messenger hace falta cuando el `url` del CDN
1664
+ * de Meta caducó. WhatsApp suelta un archivo 7 días después de que llegara: a partir de ahí es un
1665
+ * error 1515. Un 1516 es que el mensaje no es de esa cuenta o no tiene archivo en esa posición.
1666
+ *
1667
+ * Un `disposition: "attachment"` es un documento que mandó alguien de fuera: no lo pintes dentro
1668
+ * de tus propias páginas.
1669
+ */
1670
+ downloadFile(idOrganization: string, idAccount: string, idMessage: string, index: number, options?: RequestOptions): Promise<DownloadedFile>;
1611
1671
  private accountPath;
1612
1672
  private threadPath;
1613
1673
  }
@@ -2280,4 +2340,4 @@ interface AuthProvider {
2280
2340
  /** Margen con el que se pide un token nuevo antes de que caduque el que hay. */
2281
2341
  declare const TOKEN_REFRESH_MARGIN_MS = 60000;
2282
2342
 
2283
- export { Account, type AccountCapability, type AccountDestinationOptions, type AccountListOptions, AccountMetrics, type AccountMetricsOptions, AccountSelection, AccountsResource, AiContext, AiPlan, AiPlanCreateRequest, AiPlanCreateResult, type AiPlanListOptions, type AiPlanRegenerateResult, type AiPlanRegenerateTarget, AiPlanResults, type AiPlanResultsOptions, AiPlanResultsSort, AiPlansResource, AiSettings, AppsResource, AspectRatiosByNetwork, type AuthProvider, CatalogResource, type ChildOrganizationListOptions, Client, ClientApp, ClientAppInput, type ClientCredentialsToken, type ClientListOptions, ClientWithOrganizations, ClientsResource, Comment, CommentActions, type CommentListOptions, CommentNetwork, CommentReplyResult, CommentThread, type CommentThreadOptions, type CommentUpdate, CommentsResource, type ConnectCallbackParams, ConnectLink, type ConnectLinkOptions, type ConnectLinksOptions, ConnectResult, ConnectSession, ConnectToken, type ConnectTokenOptions, Contact, ContactCreate, ContactExtraData, type ContactExtraFilter, type ContactListOptions, ContactUpdate, ContactsResource, Conversation, type ConversationGroupBy, ConversationTotals, type ConversationTotalsOptions, DEFAULT_PAGE_SIZE, DEFAULT_RETRY, DEFAULT_TIMEOUT_MS, Dashboard, DashboardMetricsResult, DashboardResource, Destination, EnableResult, type FetchLike, type FileInput, type FileSource, type HttpHooks, type HttpMethod, type HttpRequest, type HttpResponse, type ImportError, type ImportFileInput, type ImportResult, Integration, IntegrationCatalogPage, IntegrationConnectRequest, type IntegrationListOptions, IntegrationPickerConfig, type IntegrationProductsOptions, IntegrationProvider, IntegrationProviderName, IntegrationUpdate, IntegrationsResource, MAX_PAGES, Message, MessageInput, MessageTemplate, type MessageTemplateResult, MessagesResource, MetricName, type MetricsGroupBy, type MetricsOptions, Organization, type OrganizationInput, type OrganizationListOptions, type OrganizationOptions, type OrganizationPlanInput, OrganizationsResource, PLANVORTEX_API_URL, type PageOptions, Paginated, PersistentMenu, PlanData, PlanUse, PlanUseData, PlanVortex, type PlanVortexOptions, PlannerTemplate, PlannerTemplateName, Product, ProductCatalog, ProductCatalogInput, ProductInput, ProductsResource, Publication, PublicationInput, PublicationLimits, type PublicationListOptions, type PublicationRetryResult, PublicationState, PublicationStats, PublicationStatsHistory, PublicationsResource, type PublicationsStatsOptions, PublicationsStatsResult, PublicationsSummaryResult, PublishSettings, type QueryValue, type RangeOptions, type RequestInfo, type RequestOptions, type RequestSender, type ResponseInfo, type RetryConfig, type RetryInfo, SocialCapabilities, SocialLimits, SocialNetwork, TOKEN_REFRESH_MARGIN_MS, type TopPublicationsOptions, TopPublicationsResult, Upload, type UploadUpdate, UploadsResource, VERSION, guessContentType };
2343
+ export { Account, type AccountCapability, type AccountDestinationOptions, type AccountListOptions, AccountMetrics, type AccountMetricsOptions, AccountSelection, AccountsResource, AiContext, AiPlan, AiPlanCreateRequest, AiPlanCreateResult, type AiPlanListOptions, type AiPlanRegenerateResult, type AiPlanRegenerateTarget, AiPlanResults, type AiPlanResultsOptions, AiPlanResultsSort, AiPlansResource, AiSettings, AppsResource, AspectRatiosByNetwork, type AuthProvider, CatalogResource, type ChildOrganizationListOptions, Client, ClientApp, ClientAppInput, type ClientCredentialsToken, type ClientListOptions, ClientWithOrganizations, ClientsResource, Comment, CommentActions, type CommentListOptions, CommentNetwork, CommentReplyResult, CommentThread, type CommentThreadOptions, type CommentUpdate, CommentsResource, type ConnectCallbackParams, ConnectLink, type ConnectLinkOptions, type ConnectLinksOptions, ConnectResult, ConnectSession, ConnectToken, type ConnectTokenOptions, Contact, ContactCreate, ContactExtraData, type ContactExtraFilter, type ContactListOptions, ContactUpdate, ContactsResource, Conversation, type ConversationGroupBy, ConversationTotals, type ConversationTotalsOptions, DEFAULT_PAGE_SIZE, DEFAULT_RETRY, DEFAULT_TIMEOUT_MS, Dashboard, DashboardMetricsResult, DashboardResource, Destination, type DownloadedFile, EnableResult, type FetchLike, type FileInput, type FileSource, type HttpHooks, type HttpMethod, type HttpRequest, type HttpResponse, type ImportError, type ImportFileInput, type ImportResult, Integration, IntegrationCatalogPage, IntegrationConnectRequest, type IntegrationListOptions, IntegrationPickerConfig, type IntegrationProductsOptions, IntegrationProvider, IntegrationProviderName, IntegrationUpdate, IntegrationsResource, MAX_PAGES, Message, MessageInput, MessageTemplate, type MessageTemplateResult, MessagesResource, MetricName, type MetricsGroupBy, type MetricsOptions, Organization, type OrganizationInput, type OrganizationListOptions, type OrganizationOptions, type OrganizationPlanInput, OrganizationsResource, PLANVORTEX_API_URL, type PageOptions, Paginated, PersistentMenu, PlanData, PlanUse, PlanUseData, PlanVortex, type PlanVortexOptions, PlannerTemplate, PlannerTemplateName, Product, ProductCatalog, ProductCatalogInput, ProductInput, ProductsResource, Publication, PublicationInput, PublicationLimits, type PublicationListOptions, type PublicationRetryResult, PublicationState, PublicationStats, PublicationStatsHistory, PublicationsResource, type PublicationsStatsOptions, PublicationsStatsResult, PublicationsSummaryResult, PublishSettings, type QueryValue, type RangeOptions, type RequestInfo, type RequestOptions, type RequestSender, type ResponseInfo, type RetryConfig, type RetryInfo, SocialCapabilities, SocialLimits, SocialNetwork, TOKEN_REFRESH_MARGIN_MS, type TopPublicationsOptions, TopPublicationsResult, Upload, type UploadUpdate, UploadsResource, VERSION, guessContentType };
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import { createErrorFromResponse, NO_ERROR_CODE, PlanVortexError, PlanVortexConfigError, isTokenError, PlanVortexConnectionError, PlanVortexAuthenticationError, isPlanVortexError } from './chunk-ZHS7FY3T.js';
2
- export { AccountError, AiPlanError, AuthError, ContactError, FileError, IntegrationError, MessagingError, NO_ERROR_CODE, OrganizationError, PLANVORTEX_ERROR_RANGES, PlanLimitError, PlanVortexAuthenticationError, PlanVortexConfigError, PlanVortexConnectionError, PlanVortexError, ProductError, PublicationError, TOKEN_ERROR_CODES, UserError, errorFamilyForCode, isPlanVortexError, isTokenError } from './chunk-ZHS7FY3T.js';
1
+ import { createErrorFromResponse, NO_ERROR_CODE, PlanVortexError, PlanVortexConfigError, isTokenError, PlanVortexConnectionError, PlanVortexAuthenticationError, isPlanVortexError } from './chunk-A77VAAQH.js';
2
+ export { AccountError, AiPlanError, AuthError, ContactError, FileError, IntegrationError, MessagingError, NO_ERROR_CODE, OrganizationError, PLANVORTEX_ERROR_RANGES, PlanLimitError, PlanVortexAuthenticationError, PlanVortexConfigError, PlanVortexConnectionError, PlanVortexError, ProductError, PublicationError, TOKEN_ERROR_CODES, UserError, errorFamilyForCode, isPlanVortexError, isTokenError } from './chunk-A77VAAQH.js';
3
3
  import { basename } from 'path';
4
4
 
5
5
  // src/version.ts
6
6
  var PLANVORTEX_API_URL = "https://api.planvortex.com/v1.0.0";
7
- var VERSION = "0.19.0";
7
+ var VERSION = "0.21.0";
8
8
 
9
9
  // src/core/auth.ts
10
10
  var TOKEN_REFRESH_MARGIN_MS = 6e4;
@@ -313,6 +313,9 @@ var HttpClient = class {
313
313
  if (request.parse === "none" || response.status === 204) {
314
314
  return void 0;
315
315
  }
316
+ if (request.parse === "binary") {
317
+ return new Uint8Array(await response.arrayBuffer());
318
+ }
316
319
  return this.readBody(response);
317
320
  }
318
321
  /** JSON si se puede; si no, el texto crudo. Un cuerpo vacío es `undefined`, nunca un throw. */
@@ -394,6 +397,19 @@ async function* iteratePages(fetchPage, options = {}) {
394
397
  }
395
398
 
396
399
  // src/resources/base.ts
400
+ function dispositionFileName(header) {
401
+ if (!header) {
402
+ return void 0;
403
+ }
404
+ const encoded = /filename\*=UTF-8''([^;]+)/i.exec(header);
405
+ if (encoded?.[1]) {
406
+ try {
407
+ return decodeURIComponent(encoded[1]);
408
+ } catch {
409
+ }
410
+ }
411
+ return /filename="([^"]*)"/i.exec(header)?.[1];
412
+ }
397
413
  var Resource = class {
398
414
  constructor(client) {
399
415
  this.client = client;
@@ -417,6 +433,27 @@ var Resource = class {
417
433
  * nombre obvio de mandar un mensaje, y con el genérico ocupando `send` la subclase no
418
434
  * compilaba.
419
435
  */
436
+ /**
437
+ * Un archivo, en bytes y con lo que dicen sus cabeceras. Lo usan las dos rutas de archivos de la
438
+ * API, la de mensajes y la de comentarios. Lleva `_` al final por lo mismo que los verbos llevan
439
+ * `http` delante: el método público de los recursos se llama `downloadFile`.
440
+ */
441
+ async downloadFile_(path, options = {}) {
442
+ const response = await this.client.request({
443
+ method: "GET",
444
+ path,
445
+ parse: "binary",
446
+ ...options.signal === void 0 ? {} : { signal: options.signal },
447
+ ...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs }
448
+ });
449
+ const disposition = response.headers?.get("content-disposition") ?? null;
450
+ return {
451
+ data: response.data ?? new Uint8Array(),
452
+ contentType: (response.headers?.get("content-type") ?? "application/octet-stream").split(";")[0].trim(),
453
+ fileName: dispositionFileName(disposition),
454
+ disposition: disposition?.toLowerCase().startsWith("inline") ? "inline" : "attachment"
455
+ };
456
+ }
420
457
  httpGet(path, query, options) {
421
458
  return this.dispatch({ method: "GET", path, ...query ? { query } : {} }, options);
422
459
  }
@@ -455,6 +492,12 @@ function requireId(value, name) {
455
492
  }
456
493
  return value;
457
494
  }
495
+ function fileIndex(index) {
496
+ if (!Number.isInteger(index) || index < 0) {
497
+ throw new TypeError(`index tiene que ser un entero desde 0, y es ${String(index)}.`);
498
+ }
499
+ return index;
500
+ }
458
501
 
459
502
  // src/resources/accounts.ts
460
503
  var AccountsResource = class extends Resource {
@@ -1131,8 +1174,8 @@ var CatalogResource = class extends Resource {
1131
1174
  );
1132
1175
  }
1133
1176
  /**
1134
- * La matriz red → qué sabe hacer: publicar, mensajes, productos, webhooks, menú persistente y
1135
- * comentarios.
1177
+ * La matriz red → qué sabe hacer: publicar, mensajes, productos, webhooks, menú persistente,
1178
+ * comentarios y estadísticas (`statistics`, hoy todas menos WhatsApp).
1136
1179
  *
1137
1180
  * Es lo que evita ofrecer una cuenta en una pantalla que su red no soporta — WhatsApp en el
1138
1181
  * compositor, LinkedIn en el chat.
@@ -1364,6 +1407,22 @@ var CommentsResource = class extends Resource {
1364
1407
  options
1365
1408
  );
1366
1409
  }
1410
+ /**
1411
+ * Un archivo del comentario (la foto, el GIF, el sticker o el vídeo de `files_urls[index]`),
1412
+ * pedido a la red en ese momento: PlanVortex no lo guarda y lo reenvía sin quedarse una copia.
1413
+ *
1414
+ * Hace falta cuando el archivo no trae `url` (LinkedIn solo da el id de la imagen; el enlace de
1415
+ * Telegram lleva el token del bot; el vídeo de Bluesky es una lista HLS) o cuando el `url` ya no
1416
+ * carga (Facebook, Threads y Discord lo caducan). Si la red ya no lo tiene, error 1515; si el
1417
+ * comentario no tiene archivo en esa posición, 2602. Un bot de Telegram no baja más de 20 MB:
1418
+ * pasado eso es un 1515 con `data.reason: "too_big"`.
1419
+ *
1420
+ * Un `disposition: "attachment"` es un documento que alguien de fuera colgó: no lo pintes dentro
1421
+ * de tus propias páginas.
1422
+ */
1423
+ async downloadFile(idOrganization, idComment, index, options = {}) {
1424
+ return this.downloadFile_(`${this.path(idOrganization, idComment)}/files/${fileIndex(index)}`, options);
1425
+ }
1367
1426
  /**
1368
1427
  * Responde EN PÚBLICO, colgando de ese comentario.
1369
1428
  *
@@ -2055,6 +2114,25 @@ var MessagesResource = class extends Resource {
2055
2114
  options
2056
2115
  );
2057
2116
  }
2117
+ /**
2118
+ * Un archivo de un mensaje que llegó de la red (`message_options.files_urls[index]`): una foto,
2119
+ * un vídeo, una nota de voz, un documento o un sticker. PlanVortex no lo guarda: lo pide a la red
2120
+ * en ese momento y lo reenvía sin quedarse una copia.
2121
+ *
2122
+ * En WhatsApp es la ÚNICA forma de abrir un archivo: ninguno trae `url`, porque WhatsApp solo los
2123
+ * entrega con el token de la cuenta. En Instagram y Messenger hace falta cuando el `url` del CDN
2124
+ * de Meta caducó. WhatsApp suelta un archivo 7 días después de que llegara: a partir de ahí es un
2125
+ * error 1515. Un 1516 es que el mensaje no es de esa cuenta o no tiene archivo en esa posición.
2126
+ *
2127
+ * Un `disposition: "attachment"` es un documento que mandó alguien de fuera: no lo pintes dentro
2128
+ * de tus propias páginas.
2129
+ */
2130
+ async downloadFile(idOrganization, idAccount, idMessage, index, options = {}) {
2131
+ return this.downloadFile_(
2132
+ `${this.accountPath(idOrganization, idAccount)}/messages/${requireId(idMessage, "idMessage")}/files/${fileIndex(index)}`,
2133
+ options
2134
+ );
2135
+ }
2058
2136
  accountPath(idOrganization, idAccount) {
2059
2137
  return `/organizations/${requireId(idOrganization, "idOrganization")}/accounts/${requireId(idAccount, "idAccount")}`;
2060
2138
  }