@ar-agents/mercadopago 0.18.5 → 0.18.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.18.7
4
+
5
+ ### Patch Changes
6
+
7
+ - [#155](https://github.com/ar-agents/ar-agents/pull/155) [`f0bbf80`](https://github.com/ar-agents/ar-agents/commit/f0bbf804c96461f642a72e774c9207ed88e19daa) Thanks [@naza00000](https://github.com/naza00000)! - OAuth token responses with a malformed (non-JSON) body now throw the typed
8
+ `MercadoPagoError` with a 300-char body snippet for context, instead of
9
+ leaking a raw `SyntaxError` from `JSON.parse`. Applies to
10
+ `exchangeCodeForToken()` and `refreshAccessToken()`.
11
+
12
+ ## 0.18.6
13
+
14
+ ### Patch Changes
15
+
16
+ - Updated dependencies [[`21e5c38`](https://github.com/ar-agents/ar-agents/commit/21e5c389ca5355567c89c125a53749e3e22a50bf)]:
17
+ - @ar-agents/core@0.4.0
18
+
3
19
  ## 0.18.5
4
20
 
5
21
  ### Patch Changes
@@ -71,7 +87,6 @@
71
87
  ### Patch Changes
72
88
 
73
89
  - [`9b8e83c`](https://github.com/ar-agents/ar-agents/commit/9b8e83ce6f291a24e00101830a49afceb0102920) - Add 2 cookbook recipes that demonstrate the cross-package thesis:
74
-
75
90
  - **16-acp-checkout-with-factura.ts** — the headline ACP-with-factura pattern. A ChatGPT Instant Checkout / Claude / Gemini agent POSTs an ACP `checkout_session`, the bridge mints a Mercado Pago preference, the buyer pays, and the bridge auto-emits an AFIP/ARCA Factura A/B/C/E via the `facturacionHook` — selecting the comprobante type based on the buyer's IVA condition. No other OSS implementation in LATAM ships this end-to-end.
76
91
  - **17-usa-llc-companion.ts** — pattern for a USA-LLC agent (ClawBank, doola Agentic, MIDAO) operating in Argentina via an AR-resident facade. The USA agent declares `@ar-agents/mcp` in its MCP host config; all 89+6+2+10+5+6+5 tools become available without the USA agent ever holding AR credentials. Walks through the operator-of-record split + sample agent prompt that drives charge → factura → WhatsApp confirmation.
77
92
 
@@ -82,7 +97,6 @@
82
97
  ### Patch Changes
83
98
 
84
99
  - [`687aa10`](https://github.com/ar-agents/ar-agents/commit/687aa1017a665ed9b3414b9f92db634a9329ac4e) - Add 3 production-grade cookbook recipes:
85
-
86
100
  - **13-anti-fraud-middleware.ts** — pre-charge heuristics chain: CUIT validity (algorithm-only), payer email history (searchPayments + status_detail flags for `cc_rejected_call_for_authorize` / `_high_risk` / `_blacklist`), 1-hour velocity tracker, AR issuer-promo stacking detector. Combined risk score (`approve` / `review` / `reject`), with high-value charges (>$100k) getting a 1.5x multiplier.
87
101
  - **14-marketplace-onboarding.ts** — end-to-end flow: CUIT validation → AFIP padron lookup (resolves legal name + IVA condition + monotributo category) → OAuth redirect with PKCE round-tripped via state → callback handler exchanging code for tokens → $1 ARS test charge → marketplace fee setup with `computeMarketplaceFee`.
88
102
  - **15-prorated-pause-resume.ts** — pause a subscription with prorated refund for the unused period (`createRefund` against the most recent charge), resume with an adjusted next-billing date so the customer doesn't double-pay. Uses `pausePreapproval` + `resumePreapproval` + a local `pauseStore` (Vercel KV in prod) to remember the credit.
@@ -101,7 +115,6 @@
101
115
  ```
102
116
 
103
117
  Reports:
104
-
105
118
  - Node version (must be ≥ 20)
106
119
  - `MP_ACCESS_TOKEN` presence + format + sandbox/prod prefix detection
107
120
  - Live token validation against `GET /users/me` (free, no charge)
@@ -130,7 +143,6 @@
130
143
  - Add `@ar-agents/mercadopago/testing` subpath: factories + a mock client for tests.
131
144
 
132
145
  What ships:
133
-
134
146
  - **Factories**: `mockPayment`, `mockPreapproval`, `mockSubscriptionPayment`, `mockPreference`, `mockRefund`, `mockCustomer`. Each takes a partial overrides object so test setup is one line.
135
147
  - **`MockMercadoPagoClient`**: in-memory client with the most-common create/get/cancel/refund paths. Read-only methods that don't fit a clean store model throw `MockNotImplementedError` to nudge users toward MSW or a real sandbox token rather than silently growing the mock.
136
148
  - **`mockSignedWebhook`**: produces a `{ headers, searchParams, body }` triple whose `x-signature` header is a real HMAC-SHA256 against the secret you pass. Drops directly into `verifyWebhookSignature` — test the full webhook stack without hand-rolling the signature manifest.
@@ -537,34 +549,28 @@ Architectural features for at-scale deployment.
537
549
  - MP v0.7: +25 new tools (81 total).
538
550
 
539
551
  **Cierre de gaps obvios (8 tools)**:
540
-
541
552
  - `get_customer`, `update_customer`, `create_customer_card`, `get_customer_card`
542
553
  - `get_subscription_plan`, `update_subscription`, `search_subscriptions`
543
554
  - `get_refund`, `update_payment_preference`
544
555
 
545
556
  **Merchant Orders (3 tools — categoría completa nueva)**:
546
-
547
557
  - `get_merchant_order`, `search_merchant_orders`, `update_merchant_order`
548
558
  - MerchantOrder agrupa Payments asociados a una Preference — clave para reconciliar webhooks con `topic='merchant_order'`.
549
559
 
550
560
  **Stores + POS CRUD completion (6 tools)**:
551
-
552
561
  - `get_store`, `update_store`, `delete_store`
553
562
  - `get_pos`, `update_pos`, `delete_pos`
554
563
 
555
564
  **Bank Accounts (2 tools)**:
556
-
557
565
  - `list_bank_accounts`, `register_bank_account`
558
566
 
559
567
  **Point Devices físicos (5 tools — categoría nueva)**:
560
-
561
568
  - `list_point_devices` (terminales físicas: Smart, Tap to Pay)
562
569
  - `update_point_device_mode` (PDV vs STANDALONE)
563
570
  - `create_point_payment_intent` (push payment al device — amount en CENTAVOS)
564
571
  - `get_point_payment_intent`, `cancel_point_payment_intent`
565
572
 
566
573
  **Pure helpers (2 tools, high-leverage)**:
567
-
568
574
  - `compute_marketplace_fee` — given amount + (% o flat ARS, con min/max), returns exact `marketplace_fee`
569
575
  - `explain_payment_status` — dado un Payment, traduce los 30+ status_detail codes a `{ summary, recommendedAction, final, paid, retryable }` en español
570
576
 
@@ -585,19 +591,16 @@ Architectural features for at-scale deployment.
585
591
  - MP v0.6: account/balance + settlements + 3DS analyzer + test cards. **+6 tools (56 total)**.
586
592
 
587
593
  **Account / Balance / Settlements (4 tools)**:
588
-
589
594
  - `get_account_balance` — current MP wallet `{ available, unavailable, total, currency_id }`. Per-seller in marketplace setups.
590
595
  - `list_account_movements({ from?, to?, limit?, offset? })` — wallet movement log (incoming payments, refunds, holdings, transfers).
591
596
  - `list_settlements({ from?, to?, status? })` — `release_money` transfers from MP wallet → registered CBU.
592
597
  - `get_settlement(id)` — single settlement detail with bank_account info.
593
598
 
594
599
  **3DS analyzer (1 tool + 1 helper)**:
595
-
596
600
  - `analyze_payment_3ds(payment_id)` — fetches the Payment, derives `{ status: 'not_required'|'frictionless'|'challenge_required'|'rejected'|'unknown', mode, challengeUrl, description }`. When `challengeUrl !== null`, MUST redirect the buyer to complete authentication.
597
601
  - `analyze3DS(payment)` exported as a pure helper for callers who already have a Payment object.
598
602
 
599
603
  **Test cards (1 tool + helpers)**:
600
-
601
604
  - `get_test_cards` — returns the official AR (MLA) sandbox cards: VISA/Mastercard/Amex credit + debit. Each has the "magic" holder names that route to specific status_detail (APRO, OTHE, CONT, FUND, CALL, SECU, EXPI, FORM).
602
605
  - `TEST_CARDS_AR`, `TEST_PAYERS_AR`, `buildTestCardScenario(card, scenario, amount)` exported for direct use in test files.
603
606
 
@@ -610,13 +613,11 @@ Architectural features for at-scale deployment.
610
613
  - MP v0.5: production hardening + marketplace flows. **+9 tools (50 total)**.
611
614
 
612
615
  **Webhook handler combo (1 tool)**:
613
-
614
616
  - `handle_webhook` — verifies HMAC-SHA256 signature, parses the event, and (optionally) auto-fetches the underlying resource (Payment, Subscription) in ONE call. Replaces the manual chain of verify_webhook_signature + parse_webhook_event + get_payment.
615
617
  - `mercadoPagoTools({ webhookSecret })` to enable.
616
618
  - Returns `{ verified, event, resource, resource_error }`. Reject with HTTP 401 when `verified: false`.
617
619
 
618
620
  **OAuth Marketplace flow (3 tools + 5 helper functions)**:
619
-
620
621
  - `oauth_authorize_url` — pure function, builds the URL the seller visits to authorize your marketplace app.
621
622
  - `oauth_exchange_code` — server-side exchange of the OAuth code for an `OAuthToken` (`access_token` + `refresh_token` + `user_id` + `expires_in`).
622
623
  - `oauth_refresh_token` — refresh a per-seller token before it expires (~6h).
@@ -624,12 +625,10 @@ Architectural features for at-scale deployment.
624
625
  - `mercadoPagoTools({ oauth: { clientId, clientSecret } })` to enable.
625
626
 
626
627
  **Order Management API (5 tools)**:
627
-
628
628
  - `create_order`, `get_order`, `update_order`, `capture_order`, `cancel_order` — MP's modern Order API. Distinct from Preference: explicit lifecycle, manual-capture support (auth-only flows for ride-share, hotels, marketplaces), multi-payment-per-order semantics.
629
629
  - `capture_mode: "manual"` enables the auth-only flow → `capture_order(id, amount?)` later.
630
630
 
631
631
  **Marketplace split payments**:
632
-
633
632
  - `marketplace`, `marketplace_fee` (in ARS), `collector_id` (seller MP user_id) supported on BOTH `create_order` AND `create_payment_preference`.
634
633
  - Funds route to the seller; `marketplace_fee` is split off to the marketplace's MP account.
635
634
 
@@ -648,7 +647,6 @@ Architectural features for at-scale deployment.
648
647
  # New: Subscription Plans (5 tools)
649
648
 
650
649
  For SaaS-style billing where you have fixed tiers (Básico/Pro/Enterprise), use plans instead of per-customer preapprovals.
651
-
652
650
  - `create_subscription_plan` — define reusable plan (price + frequency + optional free trial)
653
651
  - `list_subscription_plans` — list all plans
654
652
  - `update_subscription_plan` — change reason / amount / status / back_url (existing subs keep old amount)
@@ -658,42 +656,36 @@ Architectural features for at-scale deployment.
658
656
  # New: Stores + POS management (4 tools)
659
657
 
660
658
  Self-serve setup for in-store QR payments. Eliminates the previous one-time MP dashboard step.
661
-
662
659
  - `create_store` — create a store under the seller
663
660
  - `list_stores` — list configured stores
664
661
  - `create_pos` — create a POS under a store (the `external_id` is what `create_qr_payment` uses)
665
662
  - `list_pos` — list POSes (optionally filtered by store_id)
666
663
 
667
664
  # New: Disputes / Chargebacks (2 tools, read-only)
668
-
669
665
  - `list_payment_disputes` — list disputes raised against a payment (surfaces `dashboard_url`)
670
666
  - `get_dispute` — full dispute details (reason, amount, resolution status)
671
667
 
672
668
  Resolution remains dashboard-only; the lib surfaces the right URL.
673
669
 
674
670
  # New: Lookup helpers (2 tools)
675
-
676
671
  - `list_identification_types` — AR returns DNI/CI/LE/LC/Otro/Pasaporte/CUIT/CUIL with min/max length
677
672
  - `list_issuers` — banks issuing a card type. Pass `bin` (first 6-8 digits) for precise issuer detection — needed for issuer-specific cuotas promos like Naranja Galicia 6 cuotas sin interés
678
673
 
679
674
  # New: Webhooks management (4 tools)
680
675
 
681
676
  Programmatically configure webhook subscriptions instead of clicking around the MP dashboard.
682
-
683
677
  - `list_webhooks` — see what's configured
684
678
  - `create_webhook` — subscribe a URL to a topic (`payment`, `subscription_authorized_payment`, `merchant_order`, `point_integration_wh`, etc.)
685
679
  - `update_webhook` — change URL or topic
686
680
  - `delete_webhook` — unsubscribe
687
681
 
688
682
  # Quality
689
-
690
683
  - 81/81 tests pass (was 61 in v0.3) — added 20 tests for v0.4 endpoints
691
684
  - 21.72 KB ESM brotli'd (under 32 KB budget)
692
685
  - publint + arethetypeswrong all 🟢
693
686
  - Type-safe end-to-end; new types: SubscriptionPlan, Store, Pos, Dispute, IdentificationType, Issuer, WebhookConfig, SubscriptionPayment
694
687
 
695
688
  # Cumulative tool inventory (41 total)
696
-
697
689
  - Subscriptions: 5 (create, get, cancel, pause, resume)
698
690
  - Subscription Plans: 5 (create, list, update, subscribe, list_payments)
699
691
  - Payments: 5 (create, get, search, cancel, capture)
@@ -717,7 +709,6 @@ Architectural features for at-scale deployment.
717
709
  # `@ar-agents/mercadopago@0.3.0`
718
710
 
719
711
  **Robustness (Section 6 of v0.3 spec)**
720
-
721
712
  - Per-request timeout via `AbortSignal` (default 30s, configurable via `requestTimeoutMs`).
722
713
  - Auto-retry on 5xx + 429 with exponential backoff (default 1 retry, configurable via `maxRetries`). Honors `Retry-After` header on rate-limit. **Never retries on 4xx** (deterministic user/config errors).
723
714
  - New typed errors: `MercadoPagoTimeoutError`, `MercadoPagoOverloadedError` (HTML 503 detection — when MP returns HTML instead of JSON).
@@ -725,7 +716,6 @@ Architectural features for at-scale deployment.
725
716
  - **Deterministic idempotency keys** — `create_payment` and `refund_payment` now use `sha256(meaningful_fields)` instead of `Date.now()`. Retries dedupe correctly on MP's side.
726
717
 
727
718
  **New tools (3)**
728
-
729
719
  - **`charge_saved_card`** — server-side retokenize + charge for returning customers. Requires CVV (AR MP doesn't support CVV-less via public API). Idempotent on (card_id, amount, external_reference).
730
720
  - **`create_qr_payment`** — dynamic in-store QR via MP Point. Returns raw `qr_data` (EMVCo) + ready-to-display base64 PNG `qr_data_url`. Compatible with all AR wallets (Modo, BNA+, Cuenta DNI, Naranja X) via Transferencias 3.0 interop.
731
721
  - **`cancel_qr_payment`** — clear a pending QR order on a POS so the next `create_qr_payment` doesn't 409.
@@ -735,26 +725,22 @@ Architectural features for at-scale deployment.
735
725
  # `@ar-agents/identity-attest@0.2.0`
736
726
 
737
727
  **3 new adapters bringing total to 5**
738
-
739
728
  - **`Auth0Adapter`** (trust 0.7, or 0.85 with MFA) — OAuth2 Authorization Code flow with PKCE. Server-side `id_token` verification via `jose` JWKS. Optional MFA step-up via `acr_values` — when MFA is completed, `effective_trust_level` bumps to 0.85.
740
729
  - **`MagicLinkSdkAdapter`** (trust 0.7) — Magic.link DIDToken validation via `@magic-sdk/admin` (optional peer dep). Lazy-loaded so users without Magic don't pay cold-start cost. Returns DID + email/phone/wallet claims.
741
730
  - **`MercadoPagoIdentityAdapter`** (trust 0.5) — partial KYC via $1 micro-charge. MP doesn't expose a public KYC API, so we use payment-payer attestation: a successful payment proves MP validated the buyer's CUIT/DNI against their internal database. Auto-refunds the $1 by default. Returns `identification_type` + `identification_number` + email + name claims.
742
731
 
743
732
  **New client methods**
744
-
745
733
  - `submitOauthCode(requestId, code)` — for OAuth callbacks (Auth0)
746
734
  - `submitMagicDidToken(requestId, didToken)` — for Magic.link
747
735
  - `submitMercadoPagoPaymentId(requestId, paymentId)` — for MP webhook callbacks
748
736
 
749
737
  **Quality**
750
-
751
738
  - 28/28 tests pass (was 15 in v0.1)
752
739
  - 12.93 KB ESM brotli'd (jose is treeshakeable; was 4.44 KB without OAuth adapter)
753
740
  - publint + arethetypeswrong all 🟢
754
741
  - `jose` is a dep (used by Auth0Adapter); `@magic-sdk/admin` is optional peer dep
755
742
 
756
743
  **Trust levels reference (current)**
757
-
758
744
  - 0.3 — `WhatsAppOtpAdapter` (phone-owned)
759
745
  - 0.5 — `EmailMagicLinkAdapter` (email-owned), `MercadoPagoIdentityAdapter` (partial KYC)
760
746
  - 0.7 — `Auth0Adapter` (federated identity), `MagicLinkSdkAdapter` (Magic-managed)
@@ -788,7 +774,6 @@ Architectural features for at-scale deployment.
788
774
  Verified end-to-end against MP sandbox: account info, payment methods (21 AR methods returned), installments (81 visa offers with proper `recommended_message`), preference creation (returns real init_point + sandbox_init_point URLs).
789
775
 
790
776
  # Documentation
791
-
792
777
  - AGENTS.md updated with decision tree, status_detail recovery actions (top 12 values), AR-specific gotchas (statement_descriptor 13-char limit, sandbox cardholder name selects outcome, test cards reference, account_money instant settlement vs T+14 card hold, etc.).
793
778
  - tools.manifest.json updated to v0.2 with all 21 tools documented (purity, sideEffects, latency, input/output schemas, whenToUse, whenNotToUse).
794
779
 
@@ -797,7 +782,6 @@ Architectural features for at-scale deployment.
797
782
  8.07 KB ESM brotli'd (under 22 KB budget). Doubled tool count, still half the size limit.
798
783
 
799
784
  # What's NOT in v0.2 (deferred to v0.3+)
800
-
801
785
  - `charge_saved_card` (retokenize + charge in one call) — coming v0.3
802
786
  - `create_qr_payment` (in-store dynamic QR) — coming v0.3
803
787
  - Marketplace splits (OAuth, application_fee) — v0.4
package/dist/index.cjs CHANGED
@@ -1944,7 +1944,17 @@ async function parseTokenResponse(res) {
1944
1944
  `MP OAuth ${res.status}: ${text.slice(0, 300)}`
1945
1945
  );
1946
1946
  }
1947
- const json = JSON.parse(text);
1947
+ let json;
1948
+ try {
1949
+ json = JSON.parse(text);
1950
+ } catch {
1951
+ throw new MercadoPagoError(
1952
+ `MP OAuth ${res.status}: token response is not valid JSON: ${text.slice(0, 300)}`,
1953
+ res.status,
1954
+ "/oauth/token",
1955
+ text.slice(0, 300)
1956
+ );
1957
+ }
1948
1958
  return OAuthTokenSchema.parse(json);
1949
1959
  }
1950
1960
  function expirationTimeMs(issuedAtMs, expiresInSeconds) {