planvortex 0.21.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -100,22 +100,22 @@ for await (const publication of pv.publications.iterate(orgId, { state: ["ready"
100
100
 
101
101
  ### What is available
102
102
 
103
- | Resource | Methods |
104
- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
103
+ | Resource | Methods |
104
+ | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
105
105
  | `pv.catalog` | `socialNetworks`, `socialLimits`, `socialCapabilities`, `socialCommentActions`, `allowedAspectRatios`, `publicationLimits`, `allowedSocialPublications`, `allowedSocialMessages`, `plannerTemplates` — all cached in memory per client |
106
- | `pv.clients` | `list`, `iterate`, `get`, `update`, `updateAiSettings`, `withOrganizations`, `organizations`, `iterateOrganizations`, `createOrganization`, `updateOrganization`, `deleteOrganization` |
107
- | `pv.organizations` | `get`, `update`, `remove`, `children`, `iterateChildren`, `createChild`, `limits`, `use`, `createConnectToken`, `updateAiContext`, `updateSocialCredentials`, `deleteSocialCredentials` |
108
- | `pv.accounts` | `list`, `iterate`, `get`, `update`, `remove`, `metrics`, `metricList`, `destinations`, `destination`, `publishSettings`, `getPersistentMenu`, `setPersistentMenu`, `connectLinks`, `connect`, `enable` |
109
- | `pv.uploads` | `create`, `list`, `iterate`, `get`, `update`, `remove`, `import` |
110
- | `pv.publications` | `create`, `get`, `list`, `iterate`, `listByAccount`, `update`, `updateByAccount`, `remove`, `retry`, `metrics`, `stats`, `listOnNetwork` |
111
- | `pv.comments` | `list`, `iterate`, `unreadCount`, `thread`, `threadByAccount`, `replies`, `reply`, `update`, `markRead`, `remove`, `actions`, `downloadFile` |
112
- | `pv.messages` | `conversations`, `iterateConversations`, `conversationTotals`, `list`, `iterate`, `send`, `unreadCount`, `removeByAccount`, `templates`, `createTemplate`, `deleteTemplate`, `downloadFile` |
113
- | `pv.contacts` | `list`, `iterate`, `get`, `create`, `update`, `merge`, `remove`, `removeAll` |
114
- | `pv.products` | `list`, `iterate`, `get`, `create`, `catalogs`, `createCatalog` |
115
- | `pv.integrations` | `providers`, `list`, `iterate`, `get`, `connectLink`, `connect`, `reconnect`, `update`, `remove`, `pickerConfig`, `products` |
116
- | `pv.aiPlans` | `create`, `get`, `list`, `iterate`, `results`, `validate`, `retry`, `regenerate`, `archive`, `unarchive`, `remove` |
117
- | `pv.dashboard` | `summary`, `metrics`, `publications`, `topPublications`, `publicationStats`, `use` |
118
- | `pv.apps` | `list`, `get`, `create`, `update`, `remove`, `secret`, `rotateSecret` — **needs a user token**, not app credentials |
106
+ | `pv.clients` | `list`, `iterate`, `get`, `update`, `updateAiSettings`, `withOrganizations`, `organizations`, `iterateOrganizations`, `createOrganization`, `updateOrganization`, `deleteOrganization` |
107
+ | `pv.organizations` | `get`, `update`, `remove`, `children`, `iterateChildren`, `createChild`, `limits`, `use`, `createConnectToken`, `updateAiContext`, `updateSocialCredentials`, `deleteSocialCredentials` |
108
+ | `pv.accounts` | `list`, `iterate`, `get`, `update`, `remove`, `metrics`, `metricList`, `destinations`, `destination`, `publishSettings`, `getPersistentMenu`, `setPersistentMenu`, `connectLinks`, `connect`, `enable` |
109
+ | `pv.uploads` | `create`, `list`, `iterate`, `get`, `update`, `remove`, `import` |
110
+ | `pv.publications` | `create`, `get`, `list`, `iterate`, `listByAccount`, `update`, `updateByAccount`, `remove`, `retry`, `metrics`, `stats`, `listOnNetwork` |
111
+ | `pv.comments` | `list`, `iterate`, `unreadCount`, `thread`, `threadByAccount`, `replies`, `reply`, `update`, `markRead`, `remove`, `actions`, `downloadFile` |
112
+ | `pv.messages` | `conversations`, `iterateConversations`, `conversationTotals`, `list`, `iterate`, `send`, `markConversationRead`, `unreadCount`, `removeByAccount`, `templates`, `createTemplate`, `deleteTemplate`, `downloadFile` |
113
+ | `pv.contacts` | `list`, `iterate`, `get`, `create`, `update`, `merge`, `remove`, `removeAll` |
114
+ | `pv.products` | `list`, `iterate`, `get`, `create`, `catalogs`, `createCatalog` |
115
+ | `pv.integrations` | `providers`, `list`, `iterate`, `get`, `connectLink`, `connect`, `reconnect`, `update`, `remove`, `pickerConfig`, `products` |
116
+ | `pv.aiPlans` | `create`, `get`, `list`, `iterate`, `results`, `validate`, `retry`, `regenerate`, `archive`, `unarchive`, `remove` |
117
+ | `pv.dashboard` | `summary`, `metrics`, `publications`, `topPublications`, `publicationStats`, `use` |
118
+ | `pv.apps` | `list`, `get`, `create`, `update`, `remove`, `secret`, `rotateSecret` — **needs a user token**, not app credentials |
119
119
 
120
120
  Every documented endpoint has a method. `pv.request(...)` is still there as an escape hatch — for
121
121
  an endpoint added to the API before this package catches up — and the response types are published,
@@ -212,7 +212,7 @@ if (actions?.delete_others) {
212
212
  }
213
213
  ```
214
214
 
215
- Four things that surprise everybody:
215
+ Five things that surprise everybody:
216
216
 
217
217
  - **The inbox and the thread are not the same read.** The inbox is a photograph — `collected_date`
218
218
  says how old — and costs nothing. The thread is live, and on X it costs a credit per comment
@@ -221,8 +221,14 @@ Four things that surprise everybody:
221
221
  opaque `next_cursor` of the previous page, as `offset`.
222
222
  - **A Google Business review hangs off the listing, not off a post**, so it has its own route:
223
223
  `pv.comments.threadByAccount(orgId, accountId)`. It can arrive with a `rating` and no text at all.
224
- - **Reading a message thread marks it read.** First page only, and there is no way to opt out — it
225
- is what makes `unreadCount()` go down.
224
+ - **TikTok comments are turned on per account, in the PlanVortex dashboard.** It is a second
225
+ authorization of the account (personal or Business) that TikTok sends back to the dashboard,
226
+ so the API cannot do it. Until then that account answers error 2600;
227
+ `account.extra_data?.tiktok_business?.comments` says whether they are on.
228
+ - **Reading a message thread marks it read in PlanVortex, not on the network.** First page only,
229
+ and there is no way to opt out: it is what makes `unreadCount()` go down. The contact still sees
230
+ their messages as unread until you call `pv.messages.markConversationRead()` (blue ticks on
231
+ WhatsApp, "Seen" on Messenger and Instagram) or reply, which marks them on its own.
226
232
 
227
233
  A complete, runnable version is in [examples/comments.ts](examples/comments.ts) — the badge, the
228
234
  inbox, the action matrix, a live thread and a reply. It only replies when you ask it to.
@@ -426,25 +432,26 @@ The class you catch comes from the **range** the code falls in. There is no sepa
426
432
  the same ranges are published in the API documentation, and `PLANVORTEX_ERROR_RANGES` exports them
427
433
  if you would rather branch on `error.family`.
428
434
 
429
- | Codes | What went wrong | Class |
430
- | -------------------- | ------------------------------------------------------ | ------------------- |
431
- | 500-554 | Authentication, tokens, permissions, client apps | `AuthError` |
432
- | 601-612 | Users | `UserError` |
433
- | 700-716 | Social accounts — disconnected, revoked, no slot left | `AccountError` |
434
- | 800-810 | Files | `FileError` |
435
- | 900-996 | Publications, every per-network limit, the two rate brakes, Slack and Pinterest | `PublicationError` |
436
- | 1000-1003 | General | `PlanVortexError` |
437
- | 1100-1111 | Organizations | `OrganizationError` |
438
- | 1200-1207 | Roles | `PlanVortexError` |
439
- | 1300-1308, 1400-1408 | Plan quota exhausted, at client and organization level | `PlanLimitError` |
440
- | 1500-1517 | Messaging | `MessagingError` |
441
- | 1600-1601 | Contacts | `ContactError` |
442
- | 1900-1906 | Payments | `PlanVortexError` |
443
- | 2000-2099 | Products | `ProductError` |
444
- | 2100-2199 | AI plans | `AiPlanError` |
445
- | 2200-2299 | Integrations | `IntegrationError` |
435
+ | Codes | What went wrong | Class |
436
+ | -------------------- | ------------------------------------------------------------------------------------ | ------------------- |
437
+ | 500-554 | Authentication, tokens, permissions, client apps | `AuthError` |
438
+ | 601-612 | Users | `UserError` |
439
+ | 700-716 | Social accounts — disconnected, revoked, no slot left | `AccountError` |
440
+ | 800-810 | Files | `FileError` |
441
+ | 900-996 | Publications, every per-network limit, the two rate brakes, Slack and Pinterest | `PublicationError` |
442
+ | 1000-1003 | General | `PlanVortexError` |
443
+ | 1100-1111 | Organizations | `OrganizationError` |
444
+ | 1200-1207 | Roles | `PlanVortexError` |
445
+ | 1300-1308, 1400-1408 | Plan quota exhausted, at client and organization level | `PlanLimitError` |
446
+ | 1500-1517 | Messaging | `MessagingError` |
447
+ | 1600-1601 | Contacts | `ContactError` |
448
+ | 1900-1906 | Payments | `PlanVortexError` |
449
+ | 2000-2099 | Products | `ProductError` |
450
+ | 2100-2199 | AI plans | `AiPlanError` |
451
+ | 2200-2299 | Integrations | `IntegrationError` |
446
452
  | 2500-2599 | Publication fields: visibility, made for kids, TikTok settings (only 2508 is thrown) | `PublicationError` |
447
- | 2600-2699 | Comments: an account with no inbox (a LinkedIn personal profile) | `PublicationError` |
453
+ | 2600-2699 | Comments: an account with no inbox (a LinkedIn profile, TikTok without comments on) | `PublicationError` |
454
+ | 2800-2899 | TikTok comments: turn them on again (2804), TikTok throttling (2805) | `PublicationError` |
448
455
 
449
456
  A code outside every range — the catalogue grows — arrives as the base `PlanVortexError` with its
450
457
  `code` and `message` untouched, never swallowed and never renamed. And when the failure never got a
@@ -41,7 +41,11 @@ var PLANVORTEX_ERROR_RANGES = [
41
41
  //exige la auditoría de TikTok). Casi todos viajan en `publication_errors`, pero el 2508 se
42
42
  //LANZA: `accounts.publishSettings()` en una red que no los tiene.
43
43
  { from: 2500, to: 2599, family: "publication" },
44
- { from: 2600, to: 2699, family: "publication" }
44
+ { from: 2600, to: 2699, family: "publication" },
45
+ //Los comentarios de TikTok, que van por otra API (TikTok API for Business) con su propia
46
+ //credencial: 2804 = hay que volver a activarlos, 2805 = TikTok frena a la app (temporal),
47
+ //2809 = TikTok mantiene oculto el comentario. Son comentarios, así que la misma familia.
48
+ { from: 2800, to: 2899, family: "publication" }
45
49
  ];
46
50
  var NO_ERROR_CODE = 0;
47
51
  var TOKEN_ERROR_CODES = [501, 522];
@@ -162,5 +166,5 @@ function isTokenError(error) {
162
166
  }
163
167
 
164
168
  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, createErrorFromResponse, errorFamilyForCode, isPlanVortexError, isTokenError };
165
- //# sourceMappingURL=chunk-A77VAAQH.js.map
166
- //# sourceMappingURL=chunk-A77VAAQH.js.map
169
+ //# sourceMappingURL=chunk-L2DNKFA2.js.map
170
+ //# sourceMappingURL=chunk-L2DNKFA2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/errors.ts"],"names":[],"mappings":";AAuBO,IAAM,uBAAA,GAA2D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMpE,EAAE,IAAA,EAAM,GAAA,EAAK,EAAA,EAAI,GAAA,EAAK,QAAQ,MAAA,EAAO;AAAA,EACrC,EAAE,IAAA,EAAM,GAAA,EAAK,EAAA,EAAI,GAAA,EAAK,QAAQ,MAAA,EAAO;AAAA;AAAA;AAAA,EAGrC,EAAE,IAAA,EAAM,GAAA,EAAK,EAAA,EAAI,GAAA,EAAK,QAAQ,SAAA,EAAU;AAAA,EACxC,EAAE,IAAA,EAAM,GAAA,EAAK,EAAA,EAAI,GAAA,EAAK,QAAQ,MAAA,EAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMrC,EAAE,IAAA,EAAM,GAAA,EAAK,EAAA,EAAI,GAAA,EAAK,QAAQ,aAAA,EAAc;AAAA,EAC5C,EAAE,IAAA,EAAM,GAAA,EAAM,EAAA,EAAI,IAAA,EAAM,QAAQ,SAAA,EAAU;AAAA,EAC1C,EAAE,IAAA,EAAM,IAAA,EAAM,EAAA,EAAI,IAAA,EAAM,QAAQ,cAAA,EAAe;AAAA,EAC/C,EAAE,IAAA,EAAM,IAAA,EAAM,EAAA,EAAI,IAAA,EAAM,QAAQ,MAAA,EAAO;AAAA;AAAA,EAEvC,EAAE,IAAA,EAAM,IAAA,EAAM,EAAA,EAAI,IAAA,EAAM,QAAQ,YAAA,EAAa;AAAA,EAC7C,EAAE,IAAA,EAAM,IAAA,EAAM,EAAA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IAAA,GAC1C,KAAA,CAAM,IAAA,GACP,EAAE,IAAA,EAAM,MAAM,IAAA;AAAK,GAChC,CAAA;AACL;AAGO,SAAS,kBAAkB,KAAA,EAA0C;AACxE,EAAA,OAAO,KAAA,YAAiB,eAAA;AAC5B;AAOO,SAAS,aAAa,KAAA,EAAyB;AAClD,EAAA,OAAO,kBAAkB,KAAK,CAAA,IAAK,iBAAA,CAAkB,QAAA,CAAS,MAAM,IAAI,CAAA;AAC5E","file":"chunk-L2DNKFA2.js","sourcesContent":["/**\n * El catálogo de errores de PlanVortex, por rangos, y las clases que salen de él.\n *\n * LA REGLA, y no es negociable: **los errores se clasifican por `body.code`, nunca por el status\n * HTTP.** Todo error de dominio viaja con un 400 — un token caducado, una cuenta desconectada, el\n * cupo del plan agotado y un texto demasiado largo son los cuatro un 400. Sólo el 520 (permisos)\n * sale 401 y un fallo inesperado sale 500. Un `if (response.status === 401) refreshToken()` sería\n * un bug silencioso: los códigos de token, 501 y 522, viajan dentro de un 400.\n *\n * El catálogo del servidor crece cada mes, así que un código fuera de estos rangos NO es un error\n * del cliente: cae en la clase base con su `code` y su `message` intactos. Nunca se traga y nunca\n * se renombra.\n */\n\nexport type PlanVortexErrorRange = {\n /** Primer código del rango, incluido */\n from: number;\n /** Último código del rango, incluido */\n to: number;\n /** Qué familia de problemas es */\n family: string;\n};\n\nexport const PLANVORTEX_ERROR_RANGES: readonly PlanVortexErrorRange[] = [\n //Hasta 548, no 544: la API publica se abrio a todos los planes y trajo dos codigos nuevos\n //—545 (ritmo por plan, que sale 429) y 546 (correo sin verificar al crear una app)—, y las\n //apps dos mas —547 (el identificador de una app no se cambia) y 548 (fallo al rotar el\n //secreto, que es justo lo que estreno `apps.rotateSecret`)—. Y hasta 554 desde que el selector\n //de cuentas puede ponerlo el integrador (549-554: el modo y su sesion de conexion).\n { from: 500, to: 554, family: \"auth\" },\n { from: 601, to: 612, family: \"user\" },\n //716: la sesion de Bluesky la esta renovando otro proceso. Es temporal, y fuera de familia no\n //habia forma de saber que la respuesta es reintentar.\n { from: 700, to: 716, family: \"account\" },\n { from: 800, to: 810, family: \"file\" },\n //El techo sube con el catalogo del servidor, y subir tarde no da un error: da un consejo\n //equivocado. Los codigos de Bluesky, Discord, Telegram y Threads (961-977) y los dos frenos\n //de ritmo de la fase de publicaciones ilimitadas (978, 979) nacieron por encima de 960 y\n //caian fuera de toda familia. Slack estreno el 980-986, que es el mismo caso otra vez, y\n //Pinterest el 987-996 — la tercera vez.\n { from: 900, to: 996, family: \"publication\" },\n { from: 1000, to: 1003, family: \"general\" },\n { from: 1100, to: 1111, family: \"organization\" },\n { from: 1200, to: 1207, family: \"role\" },\n //1308 es el tope de APPS del plan, que nacio al quitar el candado de precio de la API.\n { from: 1300, to: 1308, family: \"plan_limit\" },\n { from: 1400, to: 1408, family: \"plan_limit\" },\n //1513 y 1514 son las plantillas de WhatsApp: el formato que Meta rechazaria sin decir por que,\n //y Meta rechazandola al crearla. Nacieron por encima del techo, la cuarta vez que pasa. 1515 y\n //1516 son los archivos que llegan de la red: 1515 = la red ya no lo tiene (tambien en un\n //comentario), 1516 = ese mensaje o esa posicion no existen. 1517 = ese audio o video no se pudo\n //convertir con `playable` (el original sigue ahi sin el parametro): la quinta vez.\n { from: 1500, to: 1517, family: \"messaging\" },\n { from: 1600, to: 1601, family: \"contact\" },\n { from: 1900, to: 1906, family: \"payment\" },\n { from: 2000, to: 2099, family: \"product\" },\n { from: 2100, to: 2199, family: \"ai_plan\" },\n { from: 2200, to: 2299, family: \"integration\" },\n //Los COMENTARIOS siguen aquí porque sus 945-948 se llenaron, y van con ellos a `publication`:\n //el 2600 (esta cuenta no tiene bandeja, un perfil personal de LinkedIn) es la versión por\n //cuenta del 945, y separarlos daría dos clases para el mismo «aquí no hay comentarios».\n //Los campos de publicación que no cabían en los 9xx (2500-2507: visibilidad, niños, y lo que\n //exige la auditoría de TikTok). Casi todos viajan en `publication_errors`, pero el 2508 se\n //LANZA: `accounts.publishSettings()` en una red que no los tiene.\n { from: 2500, to: 2599, family: \"publication\" },\n { from: 2600, to: 2699, family: \"publication\" },\n //Los comentarios de TikTok, que van por otra API (TikTok API for Business) con su propia\n //credencial: 2804 = hay que volver a activarlos, 2805 = TikTok frena a la app (temporal),\n //2809 = TikTok mantiene oculto el comentario. Son comentarios, así que la misma familia.\n { from: 2800, to: 2899, family: \"publication\" },\n] as const;\n\n/**\n * El `code` que lleva un error que **no** trae código del servidor: un fallo de red, un timeout, un\n * 502 de un proxy con cuerpo HTML, o el propio constructor quejándose de la configuración.\n *\n * El servidor no emite nunca el 0, así que sirve de centinela sin pisar el catálogo. Cuál de esos\n * casos es se distingue por `family`: `connection`, `http`, `oauth`, `config` o `webhook`.\n */\nexport const NO_ERROR_CODE = 0;\n\n/**\n * Los dos códigos que significan \"tu token ya no sirve\". Los dos llegan **dentro de un 400**, que es\n * justo por lo que existe esta constante: quien mire el status no los va a encontrar.\n *\n * El 520 (permisos) NO está aquí a propósito: sale 401, pero pedir un token nuevo no lo arregla — a\n * la app le faltan permisos, y con un token recién emitido le seguirán faltando.\n */\nexport const TOKEN_ERROR_CODES: readonly number[] = [501, 522];\n\n/** Opciones de construcción de un error. Todas opcionales: un error siempre se puede construir. */\nexport interface PlanVortexErrorOptions {\n /** El `data` del cuerpo — lo que el servidor adjuntó con `.withData({...})`. `{}` si no vino nada. */\n data?: Record<string, unknown>;\n /** Status HTTP. `undefined` cuando la petición no llegó a tener respuesta. */\n status?: number;\n /** `x-request-id` de la respuesta, si el despliegue lo pone delante. */\n requestId?: string;\n /** Segundos de la cabecera `Retry-After`, cuando la hay. */\n retryAfter?: number;\n /** El error original (un `TypeError` de `fetch`, por ejemplo). */\n cause?: unknown;\n /**\n * Familia, sólo para los errores que NO salen del catálogo: `connection`, `http`, `oauth`,\n * `config` y `webhook`. Los de dominio la deducen de su `code` y no la pasan nunca.\n */\n family?: string;\n}\n\n/**\n * La base de todo lo que lanza esta librería.\n *\n * Un `catch (e) { if (e instanceof PlanVortexError) }` los coge todos: los de dominio, los de red y\n * los de configuración. Para afinar están las subclases y el `code`.\n */\nexport class PlanVortexError extends Error {\n /** El `code` del cuerpo, tal cual. {@link NO_ERROR_CODE} si el error no viene del catálogo. */\n readonly code: number;\n /** La familia del rango: `auth`, `publication`, `plan_limit`... Ver {@link PLANVORTEX_ERROR_RANGES}. */\n readonly family: string;\n /** El `data` del cuerpo. */\n readonly data: Record<string, unknown>;\n /** Status HTTP, o `undefined` si nunca hubo respuesta. */\n readonly status: number | undefined;\n /** `x-request-id`, si el despliegue lo pone. Hoy el servidor no lo emite; un proxy delante sí. */\n readonly requestId: string | undefined;\n /** Segundos que pidió esperar la cabecera `Retry-After`, si llegó. */\n readonly retryAfter: number | undefined;\n\n constructor(code: number, message: string, options: PlanVortexErrorOptions = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = new.target.name;\n this.code = code;\n this.family = options.family ?? errorFamilyForCode(code) ?? \"unknown\";\n this.data = options.data ?? {};\n this.status = options.status;\n this.requestId = options.requestId;\n this.retryAfter = options.retryAfter;\n }\n}\n\n/** 500-554 — tokens, apps de cliente, permisos, sesiones de conexion. Incluye el 501 y el 522, los de token caducado. */\nexport class AuthError extends PlanVortexError {}\n/** 601-612 — el usuario final. */\nexport class UserError extends PlanVortexError {}\n/** 700-716 — cuentas sociales: desconectada, sin permisos en la red, sin refrescar. */\nexport class AccountError extends PlanVortexError {}\n/** 800-810 — ficheros: formato no admitido, demasiado grande, conversión fallida. */\nexport class FileError extends PlanVortexError {}\n/** 900-996 — publicaciones, incluidos los límites por red (caracteres, imágenes, duración), los\n * dos frenos de ritmo —978 (demasiado rápido en esta cuenta) y 979 (tope diario de esa red)—, los\n * de Slack (980-986), que empiezan por el más común: 980, la app no está en el canal, y los de\n * Pinterest (987-996), que empiezan igual: 987, la publicación no dice en qué tablero va. Y uno\n * de ellos no es un fallo: el 991 es Pinterest frenando a la aplicación, sale 429 con\n * `Retry-After` y la respuesta es esperar. */\nexport class PublicationError extends PlanVortexError {}\n/** 1100-1111 — organizaciones, y el token temporal atado a una sola de ellas (1101). */\nexport class OrganizationError extends PlanVortexError {}\n/**\n * 1300-1308 y 1400-1408 — el cupo del plan, del cliente o de la organización.\n *\n * Es el error que un integrador **sí** quiere distinguir: no se arregla reintentando, se arregla\n * cambiando de plan. Por eso los dos rangos comparten clase.\n */\nexport class PlanLimitError extends PlanVortexError {}\n/** 1500-1517 — conversaciones, mensajes, plantillas y sus archivos. Exige plan de pago. */\nexport class MessagingError extends PlanVortexError {}\n/** 1600-1601 — contactos. */\nexport class ContactError extends PlanVortexError {}\n/** 2000-2099 — catálogos y productos (sólo Facebook e Instagram). */\nexport class ProductError extends PlanVortexError {}\n/** 2100-2199 — planes de publicaciones generados con IA. */\nexport class AiPlanError extends PlanVortexError {}\n/** 2200-2299 — integraciones: Google Drive, RSS. */\nexport class IntegrationError extends PlanVortexError {}\n\n/**\n * La petición no llegó a tener respuesta: DNS, conexión rechazada, socket cortado o timeout.\n *\n * No lleva código del catálogo porque el servidor nunca llegó a opinar.\n */\nexport class PlanVortexConnectionError extends PlanVortexError {\n /** `true` si lo que se agotó fue nuestro propio timeout, no la red. */\n readonly timeout: boolean;\n\n constructor(message: string, options: PlanVortexErrorOptions & { timeout?: boolean } = {}) {\n super(NO_ERROR_CODE, message, { ...options, family: \"connection\" });\n this.timeout = options.timeout ?? false;\n }\n}\n\n/**\n * `POST /oauth/token` rechazó las credenciales.\n *\n * Es el ÚNICO sitio del API con forma de error distinta: `{error, error_description}` de OAuth2, no\n * el `{code, message, data}` de todo lo demás. Y por eso el `code` es {@link NO_ERROR_CODE}: el\n * servidor tiene códigos para esto (538-541) pero **no los manda en el cuerpo**, así que ponerlos\n * aquí sería inventarse algo que nadie dijo. Lo que sí viaja es `oauthError`.\n */\nexport class PlanVortexAuthenticationError extends PlanVortexError {\n /** `invalid_client`, `invalid_request`, `unsupported_grant_type`, `slow_down` o `server_error`. */\n readonly oauthError: string;\n\n constructor(oauthError: string, description: string, options: PlanVortexErrorOptions = {}) {\n super(NO_ERROR_CODE, description, { ...options, family: \"oauth\" });\n this.oauthError = oauthError;\n }\n}\n\n/**\n * La librería está mal configurada y no ha llegado a salir de casa: sin credenciales, o instanciada\n * en un navegador (§ trampa 9 del roadmap).\n */\nexport class PlanVortexConfigError extends PlanVortexError {\n constructor(message: string) {\n super(NO_ERROR_CODE, message, { family: \"config\" });\n }\n}\n\n/** La familia a la que pertenece un código, o `undefined` si cae fuera del catálogo conocido. */\nexport function errorFamilyForCode(code: number): string | undefined {\n return PLANVORTEX_ERROR_RANGES.find((range) => code >= range.from && code <= range.to)?.family;\n}\n\n/**\n * Familia -> clase. Las que faltan —`general`, `role`, `payment` y cualquier rango nuevo— caen a\n * propósito en la clase base: existen en el servidor pero no son superficie de integración, y darles\n * clase propia sería prometer un `instanceof` que luego habría que mantener.\n */\nconst FAMILY_CLASSES: Record<string, typeof PlanVortexError> = {\n auth: AuthError,\n user: UserError,\n account: AccountError,\n file: FileError,\n publication: PublicationError,\n organization: OrganizationError,\n plan_limit: PlanLimitError,\n messaging: MessagingError,\n contact: ContactError,\n product: ProductError,\n ai_plan: AiPlanError,\n integration: IntegrationError,\n};\n\n/** El cuerpo de error del API: `{code, message, data}`. */\nexport interface ApiErrorBody {\n code: number;\n message?: string;\n data?: Record<string, unknown>;\n}\n\nfunction isApiErrorBody(body: unknown): body is ApiErrorBody {\n return typeof body === \"object\" && body !== null && typeof (body as ApiErrorBody).code === \"number\";\n}\n\n/**\n * Convierte una respuesta de error en la clase que le toca.\n *\n * Un cuerpo sin `code` —un 502 de un proxy, la página HTML de un balanceador— no es un error de\n * dominio: sale como clase base con `family: \"http\"` y el cuerpo entero en `data`, que es además lo\n * que necesita `auth.ts` para reconocer el `{error, error_description}` de OAuth2.\n */\nexport function createErrorFromResponse(input: {\n body: unknown;\n status: number;\n requestId?: string | undefined;\n retryAfter?: number | undefined;\n}): PlanVortexError {\n const options: PlanVortexErrorOptions = {\n status: input.status,\n ...(input.requestId === undefined ? {} : { requestId: input.requestId }),\n ...(input.retryAfter === undefined ? {} : { retryAfter: input.retryAfter }),\n };\n\n if (isApiErrorBody(input.body)) {\n const family = errorFamilyForCode(input.body.code);\n const ErrorClass = (family === undefined ? undefined : FAMILY_CLASSES[family]) ?? PlanVortexError;\n return new ErrorClass(input.body.code, input.body.message ?? \"PlanVortex error\", {\n ...options,\n data: input.body.data ?? {},\n });\n }\n\n return new PlanVortexError(NO_ERROR_CODE, `HTTP ${input.status}`, {\n ...options,\n family: \"http\",\n data:\n typeof input.body === \"object\" && input.body !== null\n ? (input.body as Record<string, unknown>)\n : { body: input.body },\n });\n}\n\n/** ¿Es un error de esta librería? Útil en un `catch` donde no apetece importar la clase. */\nexport function isPlanVortexError(error: unknown): error is PlanVortexError {\n return error instanceof PlanVortexError;\n}\n\n/**\n * ¿Dice este error que el token ya no sirve? (los códigos 501 y 522, los dos dentro de un 400).\n *\n * Es lo que dispara el único reintento con token nuevo del cliente.\n */\nexport function isTokenError(error: unknown): boolean {\n return isPlanVortexError(error) && TOKEN_ERROR_CODES.includes(error.code);\n}\n"]}