@vitrindigital/node 0.3.0 → 0.4.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
@@ -140,14 +140,18 @@ Toda chamada lança subclasses de `VitrinError`:
140
140
 
141
141
  ```ts
142
142
  import {
143
- VitrinError, VitrinAuthError, VitrinValidationError,
143
+ VitrinError, VitrinAuthError, VitrinValidationError, VitrinRefusedError,
144
144
  VitrinRateLimitError, VitrinNotFoundError, VitrinServerError,
145
145
  } from '@vitrindigital/node';
146
146
 
147
147
  try {
148
148
  await vitrin.charges.create({ /* ... */ });
149
149
  } catch (err) {
150
- if (err instanceof VitrinValidationError) {
150
+ if (err instanceof VitrinRefusedError) {
151
+ // A cobrança CHEGOU ao emissor e ele negou.
152
+ console.log('Recusado:', err.code, err.customerMessage);
153
+ } else if (err instanceof VitrinValidationError) {
154
+ // A cobrança NÃO saiu daqui — o payload foi rejeitado.
151
155
  console.log('Campos inválidos:', err.fieldErrors);
152
156
  } else if (err instanceof VitrinAuthError) {
153
157
  console.log('Chave inválida ou sem permissão');
@@ -164,12 +168,46 @@ try {
164
168
  O cliente faz **retry automático** em `429` e `5xx` com backoff exponencial
165
169
  (default: 3 tentativas). Erros 4xx (exceto 429) não são retentados.
166
170
 
171
+ ### Recusa não é erro de validação
172
+
173
+ A API usa `422` para duas situações opostas, e o SDK as separa em classes
174
+ diferentes:
175
+
176
+ | Classe | O que aconteceu | O que fazer |
177
+ |---|---|---|
178
+ | `VitrinValidationError` | O payload foi rejeitado. **Nada foi enviado ao banco.** | Corrigir os campos (`fieldErrors`) e repetir. |
179
+ | `VitrinRefusedError` | A cobrança **chegou ao emissor** e ele negou. | Exibir `customerMessage`; oferecer retry só se `retryable`. |
180
+
181
+ O discriminador é o código de retorno no corpo (`return_code` / `abecs_code`):
182
+ ele só existe porque houve resposta de autorização.
183
+
184
+ ```ts
185
+ if (err instanceof VitrinRefusedError) {
186
+ showError(err.customerMessage); // texto pronto, em PT-BR
187
+ err.retryable
188
+ ? showRetryButton() // ex.: 51 saldo, 91 emissor fora do ar
189
+ : showCardSwitcher(); // ex.: 82 negada — o mesmo cartão vai negar de novo
190
+ console.log(err.code, err.transactionId); // pra log/suporte
191
+ }
192
+ ```
193
+
194
+ `transactionId` aponta para a Transaction `failed` que registra a tentativa —
195
+ ela também aparece em `GET /transactions/?status=failed` e no painel.
196
+
167
197
  ## Idempotência
168
198
 
169
199
  Inclua `idempotencyKey` em POSTs sensíveis. Se o request chegar duas vezes
170
200
  (retry de rede, deploy etc), a Vitrin reconhece pela chave e devolve a mesma
171
201
  resposta — sem cobrar duas vezes.
172
202
 
203
+ Vale em `charges.create()` e `charges.createWithSavedCard()`. A chave é escopada
204
+ por organização (a sua nunca colide com a de outro lojista) e aceita até 128
205
+ caracteres.
206
+
207
+ Use um identificador **seu** e estável — número do pedido, id do carrinho. A
208
+ proteção vem de a chave se repetir no retry; um UUID novo a cada tentativa não
209
+ protege de nada.
210
+
173
211
  ```ts
174
212
  await vitrin.charges.create({
175
213
  customer_id: 'cus_1',
package/dist/index.cjs CHANGED
@@ -26,6 +26,7 @@ __export(index_exports, {
26
26
  VitrinNetworkError: () => VitrinNetworkError,
27
27
  VitrinNotFoundError: () => VitrinNotFoundError,
28
28
  VitrinRateLimitError: () => VitrinRateLimitError,
29
+ VitrinRefusedError: () => VitrinRefusedError,
29
30
  VitrinServerError: () => VitrinServerError,
30
31
  VitrinValidationError: () => VitrinValidationError,
31
32
  Webhooks: () => Webhooks
@@ -54,6 +55,29 @@ var VitrinValidationError = class extends VitrinError {
54
55
  this.fieldErrors = opts.fieldErrors;
55
56
  }
56
57
  };
58
+ var VitrinRefusedError = class extends VitrinError {
59
+ /** Código ABECS do emissor (ex.: '82', 'GD') ou interno ('VITRIN_3DS_MISSING'). */
60
+ code;
61
+ /** Descrição interna do código. Pra log/suporte — não exibir ao pagador. */
62
+ codeDescription;
63
+ /** Texto pronto pra exibir ao cliente final, já adaptado ao motivo. */
64
+ customerMessage;
65
+ /**
66
+ * `true` → o emissor admite nova tentativa com o MESMO cartão.
67
+ * `false` → recusa definitiva; ofereça outro cartão.
68
+ */
69
+ retryable;
70
+ /** Id da Transaction `failed` que registra a tentativa, quando a API a devolve. */
71
+ transactionId;
72
+ constructor(message, opts = {}) {
73
+ super(message, opts);
74
+ this.code = opts.code;
75
+ this.codeDescription = opts.codeDescription;
76
+ this.customerMessage = opts.customerMessage;
77
+ this.retryable = opts.retryable ?? false;
78
+ this.transactionId = opts.transactionId;
79
+ }
80
+ };
57
81
  var VitrinRateLimitError = class extends VitrinError {
58
82
  };
59
83
  var VitrinNotFoundError = class extends VitrinError {
@@ -109,7 +133,7 @@ var VitrinClient = class {
109
133
  lastError = new VitrinNetworkError(
110
134
  netErr.name === "AbortError" ? `Timeout ap\xF3s ${this.timeout}ms` : netErr.message || "Falha de rede"
111
135
  );
112
- if (attempt < this.maxRetries) {
136
+ if (attempt < this.maxRetries && canRetryAfterNetworkError(method, idempotencyKey)) {
113
137
  await sleep(backoffMs(attempt));
114
138
  continue;
115
139
  }
@@ -159,12 +183,29 @@ function mapErrorResponse(status, body, requestId) {
159
183
  if (status === 404) return new VitrinNotFoundError(message, opts);
160
184
  if (status === 429) return new VitrinRateLimitError(message, opts);
161
185
  if (status >= 500) return new VitrinServerError(message, opts);
186
+ if (status === 422) {
187
+ const refusal = extractRefusal(body);
188
+ if (refusal) return new VitrinRefusedError(message, { ...opts, ...refusal });
189
+ }
162
190
  if (status === 400 || status === 422) {
163
191
  const fieldErrors = extractFieldErrors(body);
164
192
  return new VitrinValidationError(message, { ...opts, fieldErrors });
165
193
  }
166
194
  return new VitrinError(message, opts);
167
195
  }
196
+ function extractRefusal(body) {
197
+ if (!body || typeof body !== "object") return void 0;
198
+ const b = body;
199
+ const code = b.return_code ?? b.abecs_code;
200
+ if (typeof code !== "string" || !code) return void 0;
201
+ return {
202
+ code,
203
+ codeDescription: typeof b.return_code_description === "string" ? b.return_code_description : void 0,
204
+ customerMessage: typeof b.customer_message === "string" ? b.customer_message : void 0,
205
+ retryable: b.retryable === true,
206
+ transactionId: typeof b.transaction_id === "string" ? b.transaction_id : void 0
207
+ };
208
+ }
168
209
  function extractErrorMessage(body) {
169
210
  if (!body || typeof body !== "object") return void 0;
170
211
  const b = body;
@@ -191,6 +232,11 @@ function parseRetryAfter(header) {
191
232
  if (!Number.isNaN(seconds)) return seconds * 1e3;
192
233
  return null;
193
234
  }
235
+ var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);
236
+ function canRetryAfterNetworkError(method, idempotencyKey) {
237
+ if (IDEMPOTENT_METHODS.has(method.toUpperCase())) return true;
238
+ return Boolean(idempotencyKey);
239
+ }
194
240
  function backoffMs(attempt) {
195
241
  const base = 250 * Math.pow(2, attempt);
196
242
  return base + Math.floor(Math.random() * base * 0.5);
@@ -506,6 +552,7 @@ var Vitrin = class {
506
552
  VitrinNetworkError,
507
553
  VitrinNotFoundError,
508
554
  VitrinRateLimitError,
555
+ VitrinRefusedError,
509
556
  VitrinServerError,
510
557
  VitrinValidationError,
511
558
  Webhooks
package/dist/index.d.cts CHANGED
@@ -6,6 +6,10 @@
6
6
  * - Serializar/deserializar JSON
7
7
  * - Mapear erros HTTP pra `VitrinError`*
8
8
  * - Retry automático em 429 e 5xx (até 3 tentativas, backoff exponencial)
9
+ * - Retry em timeout/erro de rede SÓ quando é seguro: método idempotente
10
+ * (GET/HEAD/PUT/DELETE) ou POST/PATCH com Idempotency-Key. Sem isso o
11
+ * retry de um POST cria uma segunda cobrança — o timeout não diz que o
12
+ * servidor deixou de processar, só que a resposta se perdeu.
9
13
  * - Idempotency-Key opcional pra POSTs (evita duplo-débito quando o cliente
10
14
  * retenta uma chamada que já chegou no servidor)
11
15
  */
@@ -466,7 +470,10 @@ declare const Webhooks: {
466
470
  *
467
471
  * VitrinError — base, qualquer falha conhecida do SDK
468
472
  * ├─ VitrinAuthError — 401/403 (chave inválida ou sem permissão)
469
- * ├─ VitrinValidationError — 400/422 (DRF retornou field errors)
473
+ * ├─ VitrinValidationError — 400/422 sem código de retorno: o payload
474
+ * │ foi rejeitado e NADA foi enviado ao banco
475
+ * ├─ VitrinRefusedError — 422 com código de retorno: a cobrança
476
+ * │ CHEGOU ao emissor e ele negou
470
477
  * ├─ VitrinRateLimitError — 429
471
478
  * ├─ VitrinNotFoundError — 404
472
479
  * ├─ VitrinServerError — 5xx
@@ -496,6 +503,52 @@ declare class VitrinValidationError extends VitrinError {
496
503
  fieldErrors?: Record<string, string[]>;
497
504
  });
498
505
  }
506
+ /**
507
+ * O emissor (ou o antifraude) recusou a cobrança.
508
+ *
509
+ * Diferente de `VitrinValidationError`: aqui a autorização ACONTECEU — a
510
+ * cobrança saiu daqui, chegou ao banco do cliente e voltou negada. O
511
+ * `code` é o código ABECS que prova isso (ou um código interno `VITRIN_*`
512
+ * pra bloqueios de política nossos, como 3DS ausente).
513
+ *
514
+ * Trate pela `customerMessage` (texto pronto, em PT-BR) e pelo `retryable`:
515
+ *
516
+ * ```ts
517
+ * try {
518
+ * await vitrin.charges.create({ ... });
519
+ * } catch (err) {
520
+ * if (err instanceof VitrinRefusedError) {
521
+ * showError(err.customerMessage);
522
+ * err.retryable ? showRetryButton() : showCardSwitcher();
523
+ * }
524
+ * }
525
+ * ```
526
+ */
527
+ declare class VitrinRefusedError extends VitrinError {
528
+ /** Código ABECS do emissor (ex.: '82', 'GD') ou interno ('VITRIN_3DS_MISSING'). */
529
+ readonly code?: string;
530
+ /** Descrição interna do código. Pra log/suporte — não exibir ao pagador. */
531
+ readonly codeDescription?: string;
532
+ /** Texto pronto pra exibir ao cliente final, já adaptado ao motivo. */
533
+ readonly customerMessage?: string;
534
+ /**
535
+ * `true` → o emissor admite nova tentativa com o MESMO cartão.
536
+ * `false` → recusa definitiva; ofereça outro cartão.
537
+ */
538
+ readonly retryable: boolean;
539
+ /** Id da Transaction `failed` que registra a tentativa, quando a API a devolve. */
540
+ readonly transactionId?: string;
541
+ constructor(message: string, opts?: {
542
+ statusCode?: number;
543
+ body?: unknown;
544
+ requestId?: string;
545
+ code?: string;
546
+ codeDescription?: string;
547
+ customerMessage?: string;
548
+ retryable?: boolean;
549
+ transactionId?: string;
550
+ });
551
+ }
499
552
  declare class VitrinRateLimitError extends VitrinError {
500
553
  }
501
554
  declare class VitrinNotFoundError extends VitrinError {
@@ -545,4 +598,4 @@ declare class Vitrin {
545
598
  request<T = unknown>(path: string, options?: Parameters<VitrinClient['request']>[1]): Promise<T>;
546
599
  }
547
600
 
548
- export { type Balance, type ConstructEventOptions, type Currency, type Customer, type EntityType, type Organization, type PaginatedList, type PaymentMethod, type Plan, type Product, type RequestOptions, type ScheduledReceivable, type ScheduledReceivablesResponse, type Subscription, type Transaction, type TransactionStatus, Vitrin, VitrinAuthError, type VitrinClientOptions, VitrinError, VitrinNetworkError, VitrinNotFoundError, VitrinRateLimitError, VitrinServerError, VitrinValidationError, type WebhookEvent, Webhooks };
601
+ export { type Balance, type ConstructEventOptions, type Currency, type Customer, type EntityType, type Organization, type PaginatedList, type PaymentMethod, type Plan, type Product, type RequestOptions, type ScheduledReceivable, type ScheduledReceivablesResponse, type Subscription, type Transaction, type TransactionStatus, Vitrin, VitrinAuthError, type VitrinClientOptions, VitrinError, VitrinNetworkError, VitrinNotFoundError, VitrinRateLimitError, VitrinRefusedError, VitrinServerError, VitrinValidationError, type WebhookEvent, Webhooks };
package/dist/index.d.ts CHANGED
@@ -6,6 +6,10 @@
6
6
  * - Serializar/deserializar JSON
7
7
  * - Mapear erros HTTP pra `VitrinError`*
8
8
  * - Retry automático em 429 e 5xx (até 3 tentativas, backoff exponencial)
9
+ * - Retry em timeout/erro de rede SÓ quando é seguro: método idempotente
10
+ * (GET/HEAD/PUT/DELETE) ou POST/PATCH com Idempotency-Key. Sem isso o
11
+ * retry de um POST cria uma segunda cobrança — o timeout não diz que o
12
+ * servidor deixou de processar, só que a resposta se perdeu.
9
13
  * - Idempotency-Key opcional pra POSTs (evita duplo-débito quando o cliente
10
14
  * retenta uma chamada que já chegou no servidor)
11
15
  */
@@ -466,7 +470,10 @@ declare const Webhooks: {
466
470
  *
467
471
  * VitrinError — base, qualquer falha conhecida do SDK
468
472
  * ├─ VitrinAuthError — 401/403 (chave inválida ou sem permissão)
469
- * ├─ VitrinValidationError — 400/422 (DRF retornou field errors)
473
+ * ├─ VitrinValidationError — 400/422 sem código de retorno: o payload
474
+ * │ foi rejeitado e NADA foi enviado ao banco
475
+ * ├─ VitrinRefusedError — 422 com código de retorno: a cobrança
476
+ * │ CHEGOU ao emissor e ele negou
470
477
  * ├─ VitrinRateLimitError — 429
471
478
  * ├─ VitrinNotFoundError — 404
472
479
  * ├─ VitrinServerError — 5xx
@@ -496,6 +503,52 @@ declare class VitrinValidationError extends VitrinError {
496
503
  fieldErrors?: Record<string, string[]>;
497
504
  });
498
505
  }
506
+ /**
507
+ * O emissor (ou o antifraude) recusou a cobrança.
508
+ *
509
+ * Diferente de `VitrinValidationError`: aqui a autorização ACONTECEU — a
510
+ * cobrança saiu daqui, chegou ao banco do cliente e voltou negada. O
511
+ * `code` é o código ABECS que prova isso (ou um código interno `VITRIN_*`
512
+ * pra bloqueios de política nossos, como 3DS ausente).
513
+ *
514
+ * Trate pela `customerMessage` (texto pronto, em PT-BR) e pelo `retryable`:
515
+ *
516
+ * ```ts
517
+ * try {
518
+ * await vitrin.charges.create({ ... });
519
+ * } catch (err) {
520
+ * if (err instanceof VitrinRefusedError) {
521
+ * showError(err.customerMessage);
522
+ * err.retryable ? showRetryButton() : showCardSwitcher();
523
+ * }
524
+ * }
525
+ * ```
526
+ */
527
+ declare class VitrinRefusedError extends VitrinError {
528
+ /** Código ABECS do emissor (ex.: '82', 'GD') ou interno ('VITRIN_3DS_MISSING'). */
529
+ readonly code?: string;
530
+ /** Descrição interna do código. Pra log/suporte — não exibir ao pagador. */
531
+ readonly codeDescription?: string;
532
+ /** Texto pronto pra exibir ao cliente final, já adaptado ao motivo. */
533
+ readonly customerMessage?: string;
534
+ /**
535
+ * `true` → o emissor admite nova tentativa com o MESMO cartão.
536
+ * `false` → recusa definitiva; ofereça outro cartão.
537
+ */
538
+ readonly retryable: boolean;
539
+ /** Id da Transaction `failed` que registra a tentativa, quando a API a devolve. */
540
+ readonly transactionId?: string;
541
+ constructor(message: string, opts?: {
542
+ statusCode?: number;
543
+ body?: unknown;
544
+ requestId?: string;
545
+ code?: string;
546
+ codeDescription?: string;
547
+ customerMessage?: string;
548
+ retryable?: boolean;
549
+ transactionId?: string;
550
+ });
551
+ }
499
552
  declare class VitrinRateLimitError extends VitrinError {
500
553
  }
501
554
  declare class VitrinNotFoundError extends VitrinError {
@@ -545,4 +598,4 @@ declare class Vitrin {
545
598
  request<T = unknown>(path: string, options?: Parameters<VitrinClient['request']>[1]): Promise<T>;
546
599
  }
547
600
 
548
- export { type Balance, type ConstructEventOptions, type Currency, type Customer, type EntityType, type Organization, type PaginatedList, type PaymentMethod, type Plan, type Product, type RequestOptions, type ScheduledReceivable, type ScheduledReceivablesResponse, type Subscription, type Transaction, type TransactionStatus, Vitrin, VitrinAuthError, type VitrinClientOptions, VitrinError, VitrinNetworkError, VitrinNotFoundError, VitrinRateLimitError, VitrinServerError, VitrinValidationError, type WebhookEvent, Webhooks };
601
+ export { type Balance, type ConstructEventOptions, type Currency, type Customer, type EntityType, type Organization, type PaginatedList, type PaymentMethod, type Plan, type Product, type RequestOptions, type ScheduledReceivable, type ScheduledReceivablesResponse, type Subscription, type Transaction, type TransactionStatus, Vitrin, VitrinAuthError, type VitrinClientOptions, VitrinError, VitrinNetworkError, VitrinNotFoundError, VitrinRateLimitError, VitrinRefusedError, VitrinServerError, VitrinValidationError, type WebhookEvent, Webhooks };
package/dist/index.js CHANGED
@@ -20,6 +20,29 @@ var VitrinValidationError = class extends VitrinError {
20
20
  this.fieldErrors = opts.fieldErrors;
21
21
  }
22
22
  };
23
+ var VitrinRefusedError = class extends VitrinError {
24
+ /** Código ABECS do emissor (ex.: '82', 'GD') ou interno ('VITRIN_3DS_MISSING'). */
25
+ code;
26
+ /** Descrição interna do código. Pra log/suporte — não exibir ao pagador. */
27
+ codeDescription;
28
+ /** Texto pronto pra exibir ao cliente final, já adaptado ao motivo. */
29
+ customerMessage;
30
+ /**
31
+ * `true` → o emissor admite nova tentativa com o MESMO cartão.
32
+ * `false` → recusa definitiva; ofereça outro cartão.
33
+ */
34
+ retryable;
35
+ /** Id da Transaction `failed` que registra a tentativa, quando a API a devolve. */
36
+ transactionId;
37
+ constructor(message, opts = {}) {
38
+ super(message, opts);
39
+ this.code = opts.code;
40
+ this.codeDescription = opts.codeDescription;
41
+ this.customerMessage = opts.customerMessage;
42
+ this.retryable = opts.retryable ?? false;
43
+ this.transactionId = opts.transactionId;
44
+ }
45
+ };
23
46
  var VitrinRateLimitError = class extends VitrinError {
24
47
  };
25
48
  var VitrinNotFoundError = class extends VitrinError {
@@ -75,7 +98,7 @@ var VitrinClient = class {
75
98
  lastError = new VitrinNetworkError(
76
99
  netErr.name === "AbortError" ? `Timeout ap\xF3s ${this.timeout}ms` : netErr.message || "Falha de rede"
77
100
  );
78
- if (attempt < this.maxRetries) {
101
+ if (attempt < this.maxRetries && canRetryAfterNetworkError(method, idempotencyKey)) {
79
102
  await sleep(backoffMs(attempt));
80
103
  continue;
81
104
  }
@@ -125,12 +148,29 @@ function mapErrorResponse(status, body, requestId) {
125
148
  if (status === 404) return new VitrinNotFoundError(message, opts);
126
149
  if (status === 429) return new VitrinRateLimitError(message, opts);
127
150
  if (status >= 500) return new VitrinServerError(message, opts);
151
+ if (status === 422) {
152
+ const refusal = extractRefusal(body);
153
+ if (refusal) return new VitrinRefusedError(message, { ...opts, ...refusal });
154
+ }
128
155
  if (status === 400 || status === 422) {
129
156
  const fieldErrors = extractFieldErrors(body);
130
157
  return new VitrinValidationError(message, { ...opts, fieldErrors });
131
158
  }
132
159
  return new VitrinError(message, opts);
133
160
  }
161
+ function extractRefusal(body) {
162
+ if (!body || typeof body !== "object") return void 0;
163
+ const b = body;
164
+ const code = b.return_code ?? b.abecs_code;
165
+ if (typeof code !== "string" || !code) return void 0;
166
+ return {
167
+ code,
168
+ codeDescription: typeof b.return_code_description === "string" ? b.return_code_description : void 0,
169
+ customerMessage: typeof b.customer_message === "string" ? b.customer_message : void 0,
170
+ retryable: b.retryable === true,
171
+ transactionId: typeof b.transaction_id === "string" ? b.transaction_id : void 0
172
+ };
173
+ }
134
174
  function extractErrorMessage(body) {
135
175
  if (!body || typeof body !== "object") return void 0;
136
176
  const b = body;
@@ -157,6 +197,11 @@ function parseRetryAfter(header) {
157
197
  if (!Number.isNaN(seconds)) return seconds * 1e3;
158
198
  return null;
159
199
  }
200
+ var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);
201
+ function canRetryAfterNetworkError(method, idempotencyKey) {
202
+ if (IDEMPOTENT_METHODS.has(method.toUpperCase())) return true;
203
+ return Boolean(idempotencyKey);
204
+ }
160
205
  function backoffMs(attempt) {
161
206
  const base = 250 * Math.pow(2, attempt);
162
207
  return base + Math.floor(Math.random() * base * 0.5);
@@ -471,6 +516,7 @@ export {
471
516
  VitrinNetworkError,
472
517
  VitrinNotFoundError,
473
518
  VitrinRateLimitError,
519
+ VitrinRefusedError,
474
520
  VitrinServerError,
475
521
  VitrinValidationError,
476
522
  Webhooks
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitrindigital/node",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "SDK oficial Node.js para a API da Vitrin Digital",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",