@ar-agents/mercadopago 0.9.0 → 0.11.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/CHANGELOG.md +42 -0
- package/MIGRATION.md +176 -0
- package/dist/audit-B9Nhj3PH.d.cts +294 -0
- package/dist/audit-B9Nhj3PH.d.ts +294 -0
- package/dist/index.cjs +1362 -49
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +792 -6
- package/dist/index.d.ts +792 -6
- package/dist/index.js +1337 -50
- package/dist/index.js.map +1 -1
- package/dist/otel.cjs +102 -0
- package/dist/otel.cjs.map +1 -0
- package/dist/otel.d.cts +90 -0
- package/dist/otel.d.ts +90 -0
- package/dist/otel.js +100 -0
- package/dist/otel.js.map +1 -0
- package/dist/vercel-kv.cjs +81 -0
- package/dist/vercel-kv.cjs.map +1 -1
- package/dist/vercel-kv.d.cts +38 -2
- package/dist/vercel-kv.d.ts +38 -2
- package/dist/vercel-kv.js +81 -1
- package/dist/vercel-kv.js.map +1 -1
- package/package.json +22 -3
- package/tools.manifest.json +1 -1
- package/dist/state-C6Wzb_XX.d.cts +0 -106
- package/dist/state-C6Wzb_XX.d.ts +0 -106
package/dist/index.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
import { I as IdempotencyCache, S as SubscriptionStateAdapter, A as AuditLogger, a as AuditOperation } from './audit-B9Nhj3PH.cjs';
|
|
3
|
+
export { b as AuditEntry, c as AuditLogAdapter, d as InMemoryAuditLog, e as InMemoryIdempotencyCache, f as InMemoryOAuthTokenStore, g as InMemoryStateAdapter, O as OAuthTokenRecord, h as OAuthTokenStore, i as SubscriptionStateRecord } from './audit-B9Nhj3PH.cjs';
|
|
4
|
+
import { ToolSet, Tool } from 'ai';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Circuit breaker — protects your app from cascading failures when MP
|
|
@@ -463,15 +463,86 @@ interface CreatePaymentParams {
|
|
|
463
463
|
};
|
|
464
464
|
/** Webhook override URL. Falls back to dashboard config if omitted. */
|
|
465
465
|
notificationUrl?: string;
|
|
466
|
-
/**
|
|
466
|
+
/**
|
|
467
|
+
* Additional information passed to MP for fraud scoring + receipt details.
|
|
468
|
+
*
|
|
469
|
+
* **Critical for fraud scoring**: every field you fill in here improves
|
|
470
|
+
* MP's risk model's confidence and reduces false-positive rejections.
|
|
471
|
+
* For card payments above ~$50k ARS, ALWAYS include `payer` + `ip_address`
|
|
472
|
+
* + `shipments` (when applicable) — payments without enrichment have a
|
|
473
|
+
* 3-5x higher rejection rate per MP's published guidance (RG 5286/2023).
|
|
474
|
+
*/
|
|
467
475
|
additionalInfo?: {
|
|
476
|
+
/** Items in the cart — used for receipt + fraud scoring. */
|
|
468
477
|
items?: Array<{
|
|
469
478
|
id?: string;
|
|
470
479
|
title: string;
|
|
471
480
|
quantity: number;
|
|
472
481
|
unit_price: number;
|
|
473
482
|
description?: string;
|
|
483
|
+
picture_url?: string;
|
|
484
|
+
category_id?: string;
|
|
474
485
|
}>;
|
|
486
|
+
/**
|
|
487
|
+
* Buyer profile fields. The more fields populated, the better MP's
|
|
488
|
+
* risk engine can assess the transaction. `registration_date` is
|
|
489
|
+
* particularly impactful (newer accounts = higher risk).
|
|
490
|
+
*/
|
|
491
|
+
payer?: {
|
|
492
|
+
first_name?: string;
|
|
493
|
+
last_name?: string;
|
|
494
|
+
phone?: {
|
|
495
|
+
area_code?: string;
|
|
496
|
+
number?: string;
|
|
497
|
+
};
|
|
498
|
+
address?: {
|
|
499
|
+
zip_code?: string;
|
|
500
|
+
street_name?: string;
|
|
501
|
+
street_number?: number;
|
|
502
|
+
};
|
|
503
|
+
/** ISO 8601 date — when the buyer registered on YOUR platform. */
|
|
504
|
+
registration_date?: string;
|
|
505
|
+
/**
|
|
506
|
+
* Whether the buyer is a returning customer. Strong fraud-scoring
|
|
507
|
+
* signal — repeat buyers are lower risk.
|
|
508
|
+
*/
|
|
509
|
+
authentication_type?: "Cellphone" | "Email" | "Facebook" | "Gmail" | "Native app" | string;
|
|
510
|
+
/** Whether the buyer has set up 2FA on YOUR platform. */
|
|
511
|
+
is_prime_user?: boolean;
|
|
512
|
+
/** Whether the buyer has paid you successfully before. */
|
|
513
|
+
is_first_purchase_online?: boolean;
|
|
514
|
+
/** ISO 8601 — last successful purchase on your platform. */
|
|
515
|
+
last_purchase?: string;
|
|
516
|
+
};
|
|
517
|
+
/**
|
|
518
|
+
* Shipping info. Used by fraud engine to compare against payer address.
|
|
519
|
+
* Mismatch (different city/province) = higher risk score.
|
|
520
|
+
*/
|
|
521
|
+
shipments?: {
|
|
522
|
+
receiver_address?: {
|
|
523
|
+
zip_code?: string;
|
|
524
|
+
street_name?: string;
|
|
525
|
+
street_number?: number;
|
|
526
|
+
floor?: string;
|
|
527
|
+
apartment?: string;
|
|
528
|
+
city_name?: string;
|
|
529
|
+
state_name?: string;
|
|
530
|
+
country_name?: string;
|
|
531
|
+
};
|
|
532
|
+
/** Express shipment flag — fraud engine treats high-value+express as suspicious. */
|
|
533
|
+
express_shipment?: boolean;
|
|
534
|
+
/** True if the buyer picks up at a store (no shipment). Reduces fraud risk. */
|
|
535
|
+
local_pickup?: boolean;
|
|
536
|
+
};
|
|
537
|
+
/**
|
|
538
|
+
* Buyer's IP address (from your X-Forwarded-For / req.headers).
|
|
539
|
+
* **Strongly recommended** for any card payment — MP's fraud engine
|
|
540
|
+
* checks IP geolocation, ASN reputation, proxy/VPN detection.
|
|
541
|
+
* Without IP, MP defaults to "unknown" which raises risk score.
|
|
542
|
+
*/
|
|
543
|
+
ip_address?: string;
|
|
544
|
+
/** Referrer URL — useful for affiliate / channel attribution + fraud signal. */
|
|
545
|
+
referral_url?: string;
|
|
475
546
|
};
|
|
476
547
|
/** Statement descriptor — what shows on the buyer's card statement. Max 13 chars. */
|
|
477
548
|
statementDescriptor?: string;
|
|
@@ -1876,6 +1947,150 @@ declare class MercadoPagoClient {
|
|
|
1876
1947
|
}>;
|
|
1877
1948
|
}
|
|
1878
1949
|
|
|
1950
|
+
/**
|
|
1951
|
+
* Webhook idempotency / dedup — short-circuits duplicate webhook deliveries
|
|
1952
|
+
* from MP to prevent double-processing.
|
|
1953
|
+
*
|
|
1954
|
+
* # The problem
|
|
1955
|
+
*
|
|
1956
|
+
* MP retries webhook deliveries on 5xx responses. The retry policy is
|
|
1957
|
+
* exponential backoff: 5min, 15min, 30min, 1h, 6h, 24h, 48h, 96h, 192h
|
|
1958
|
+
* (~12 attempts over 8 days). If your handler temporarily 5xx'd (DB
|
|
1959
|
+
* down, deploy in progress, etc.) and then recovered, you'll receive
|
|
1960
|
+
* the SAME webhook 5+ times. Without dedup:
|
|
1961
|
+
*
|
|
1962
|
+
* - You double-charge (if the webhook triggers a charge)
|
|
1963
|
+
* - You double-send notifications (5 emails to the buyer instead of 1)
|
|
1964
|
+
* - You double-create downstream resources
|
|
1965
|
+
*
|
|
1966
|
+
* # The fix
|
|
1967
|
+
*
|
|
1968
|
+
* Cache the unique "delivery key" of every webhook you've successfully
|
|
1969
|
+
* processed. On retry, recognize the key, return 200 immediately, skip
|
|
1970
|
+
* processing.
|
|
1971
|
+
*
|
|
1972
|
+
* # The "delivery key"
|
|
1973
|
+
*
|
|
1974
|
+
* MP doesn't ship a single canonical id per delivery, but the tuple
|
|
1975
|
+
* `${topic}:${dataId}:${requestId}` is stable for retries (same delivery
|
|
1976
|
+
* attempt → same x-request-id) and unique enough to dedupe.
|
|
1977
|
+
*
|
|
1978
|
+
* # Storage
|
|
1979
|
+
*
|
|
1980
|
+
* Reuse `IdempotencyCache` from `state.ts`. Default TTL: 7 days (matches
|
|
1981
|
+
* MP's webhook retry window). Override per-deployment.
|
|
1982
|
+
*/
|
|
1983
|
+
|
|
1984
|
+
interface WebhookDedupOptions {
|
|
1985
|
+
/**
|
|
1986
|
+
* Storage for processed webhook ids. Plug in `VercelKVIdempotencyCache`
|
|
1987
|
+
* for production or `InMemoryIdempotencyCache` for tests.
|
|
1988
|
+
*/
|
|
1989
|
+
cache: IdempotencyCache;
|
|
1990
|
+
/**
|
|
1991
|
+
* Time-to-live for dedup entries (seconds). Default 7 days — covers MP's
|
|
1992
|
+
* full retry window (~8 days) with a safety margin.
|
|
1993
|
+
*/
|
|
1994
|
+
ttlSeconds?: number;
|
|
1995
|
+
/**
|
|
1996
|
+
* Optional callback fired when a duplicate is detected. Useful for
|
|
1997
|
+
* metrics ("webhooks deduped" counter).
|
|
1998
|
+
*/
|
|
1999
|
+
onDuplicate?: (deliveryKey: string) => void;
|
|
2000
|
+
}
|
|
2001
|
+
interface DedupResult {
|
|
2002
|
+
/**
|
|
2003
|
+
* `true` if this is the first time we've seen this delivery — caller
|
|
2004
|
+
* should process it.
|
|
2005
|
+
* `false` if it's a retry of a previously-seen delivery — caller should
|
|
2006
|
+
* acknowledge with 200 and skip processing.
|
|
2007
|
+
*/
|
|
2008
|
+
shouldProcess: boolean;
|
|
2009
|
+
/** The deduplication key derived from the webhook. */
|
|
2010
|
+
deliveryKey: string;
|
|
2011
|
+
}
|
|
2012
|
+
/**
|
|
2013
|
+
* Dedup helper. Use this BEFORE processing a webhook to short-circuit retries.
|
|
2014
|
+
*
|
|
2015
|
+
* @example
|
|
2016
|
+
* ```ts
|
|
2017
|
+
* import { WebhookDedup, VercelKVIdempotencyCache } from "@ar-agents/mercadopago";
|
|
2018
|
+
*
|
|
2019
|
+
* const dedup = new WebhookDedup({
|
|
2020
|
+
* cache: new VercelKVIdempotencyCache(),
|
|
2021
|
+
* onDuplicate: (key) => metrics.increment("mp.webhook.duplicate"),
|
|
2022
|
+
* });
|
|
2023
|
+
*
|
|
2024
|
+
* export async function POST(req: Request) {
|
|
2025
|
+
* const event = parseWebhookEvent(...);
|
|
2026
|
+
* if (!event) return new Response("bad request", { status: 400 });
|
|
2027
|
+
*
|
|
2028
|
+
* const requestId = req.headers.get("x-request-id");
|
|
2029
|
+
* const { shouldProcess } = await dedup.check({
|
|
2030
|
+
* topic: event.topic,
|
|
2031
|
+
* dataId: event.dataId,
|
|
2032
|
+
* requestId,
|
|
2033
|
+
* });
|
|
2034
|
+
* if (!shouldProcess) return new Response("ok (duplicate)", { status: 200 });
|
|
2035
|
+
*
|
|
2036
|
+
* // ... process the webhook ...
|
|
2037
|
+
*
|
|
2038
|
+
* return new Response("ok", { status: 200 });
|
|
2039
|
+
* }
|
|
2040
|
+
* ```
|
|
2041
|
+
*/
|
|
2042
|
+
declare class WebhookDedup {
|
|
2043
|
+
private readonly cache;
|
|
2044
|
+
private readonly ttlSeconds;
|
|
2045
|
+
private readonly onDuplicate;
|
|
2046
|
+
constructor(opts: WebhookDedupOptions);
|
|
2047
|
+
/**
|
|
2048
|
+
* Check whether a webhook delivery has been seen before. If new, mark it
|
|
2049
|
+
* as seen (so subsequent retries return shouldProcess=false). If seen,
|
|
2050
|
+
* return shouldProcess=false WITHOUT marking again.
|
|
2051
|
+
*
|
|
2052
|
+
* **Important**: this method is not atomic across concurrent calls — two
|
|
2053
|
+
* simultaneous deliveries with the same key may both pass shouldProcess=true.
|
|
2054
|
+
* For strict at-most-once processing, follow with a transaction or use a
|
|
2055
|
+
* cache that supports `setNX`-style semantics (Redis, Cloudflare KV with
|
|
2056
|
+
* conditional writes).
|
|
2057
|
+
*
|
|
2058
|
+
* For most webhook handlers this race is acceptable: even if two get
|
|
2059
|
+
* through, the downstream business logic (e.g., "charge if not already
|
|
2060
|
+
* charged") will be idempotent on its own.
|
|
2061
|
+
*/
|
|
2062
|
+
check(args: {
|
|
2063
|
+
topic: string;
|
|
2064
|
+
dataId: string;
|
|
2065
|
+
requestId: string | null;
|
|
2066
|
+
}): Promise<DedupResult>;
|
|
2067
|
+
/**
|
|
2068
|
+
* Manually mark a delivery as processed. Call this AFTER your business
|
|
2069
|
+
* logic succeeds — useful when you want to control when the dedup
|
|
2070
|
+
* marker is written (e.g., only on success).
|
|
2071
|
+
*
|
|
2072
|
+
* Combined with calling `check()` BEFORE the work, this gives "at-least-once"
|
|
2073
|
+
* semantics: failed processing → no marker → retry will be processed again.
|
|
2074
|
+
*/
|
|
2075
|
+
markProcessed(args: {
|
|
2076
|
+
topic: string;
|
|
2077
|
+
dataId: string;
|
|
2078
|
+
requestId: string | null;
|
|
2079
|
+
}): Promise<void>;
|
|
2080
|
+
/**
|
|
2081
|
+
* Variant of `check` that doesn't mark on first sight — caller must
|
|
2082
|
+
* explicitly `markProcessed` when their business logic succeeds.
|
|
2083
|
+
* Use this for at-least-once semantics (each delivery processed at
|
|
2084
|
+
* least once, possibly more if processing fails before mark).
|
|
2085
|
+
*/
|
|
2086
|
+
peekIsDuplicate(args: {
|
|
2087
|
+
topic: string;
|
|
2088
|
+
dataId: string;
|
|
2089
|
+
requestId: string | null;
|
|
2090
|
+
}): Promise<DedupResult>;
|
|
2091
|
+
private deriveKey;
|
|
2092
|
+
}
|
|
2093
|
+
|
|
1879
2094
|
interface MercadoPagoToolsOptions {
|
|
1880
2095
|
/** State adapter for persisting subscription records. */
|
|
1881
2096
|
state: SubscriptionStateAdapter;
|
|
@@ -1913,8 +2128,26 @@ interface MercadoPagoToolsOptions {
|
|
|
1913
2128
|
clientId: string;
|
|
1914
2129
|
clientSecret: string;
|
|
1915
2130
|
};
|
|
2131
|
+
/**
|
|
2132
|
+
* v0.10 — Audit logger. When passed, every state-mutating tool call
|
|
2133
|
+
* automatically emits an audit entry with operation/actor/inputHash/
|
|
2134
|
+
* resourceId/outcome/duration. Read-only tools (get/search/list) skip
|
|
2135
|
+
* audit logging.
|
|
2136
|
+
*/
|
|
2137
|
+
audit?: AuditLogger;
|
|
2138
|
+
/**
|
|
2139
|
+
* v0.10 — Logical actor for audit entries (e.g., "agent:billing-bot",
|
|
2140
|
+
* "user:42"). Defaults to the AuditLogger's defaultActor.
|
|
2141
|
+
*/
|
|
2142
|
+
auditActor?: string;
|
|
2143
|
+
/**
|
|
2144
|
+
* v0.10 — Webhook deduplication for handle_webhook tool. Caches
|
|
2145
|
+
* processed (topic, dataId, requestId) tuples to short-circuit MP's
|
|
2146
|
+
* retries (which fire on 5xx and can deliver the same event 5+ times).
|
|
2147
|
+
*/
|
|
2148
|
+
webhookDedup?: WebhookDedup;
|
|
1916
2149
|
}
|
|
1917
|
-
type ToolName = "create_subscription" | "get_subscription_status" | "cancel_subscription" | "pause_subscription" | "resume_subscription" | "create_payment" | "get_payment" | "search_payments" | "cancel_payment" | "capture_payment" | "refund_payment" | "list_refunds" | "create_payment_preference" | "get_payment_preference" | "create_customer" | "find_customer_by_email" | "list_customer_cards" | "delete_customer_card" | "list_payment_methods" | "calculate_installments" | "get_account_info" | "charge_saved_card" | "create_qr_payment" | "cancel_qr_payment" | "create_subscription_plan" | "list_subscription_plans" | "update_subscription_plan" | "subscribe_to_plan" | "list_subscription_payments" | "create_store" | "list_stores" | "create_pos" | "list_pos" | "list_payment_disputes" | "get_dispute" | "list_identification_types" | "list_issuers" | "list_webhooks" | "create_webhook" | "update_webhook" | "delete_webhook" | "handle_webhook" | "oauth_authorize_url" | "oauth_exchange_code" | "oauth_refresh_token" | "create_order" | "get_order" | "update_order" | "capture_order" | "cancel_order" | "get_account_balance" | "list_account_movements" | "list_settlements" | "get_settlement" | "analyze_payment_3ds" | "get_test_cards" | "get_customer" | "update_customer" | "create_customer_card" | "get_customer_card" | "get_subscription_plan" | "update_subscription" | "search_subscriptions" | "get_refund" | "update_payment_preference" | "get_merchant_order" | "search_merchant_orders" | "update_merchant_order" | "get_store" | "update_store" | "delete_store" | "get_pos" | "update_pos" | "delete_pos" | "list_bank_accounts" | "register_bank_account" | "list_point_devices" | "update_point_device_mode" | "create_point_payment_intent" | "get_point_payment_intent" | "cancel_point_payment_intent" | "compute_marketplace_fee" | "explain_payment_status" | "mp_health_check";
|
|
2150
|
+
type ToolName = "create_subscription" | "get_subscription_status" | "cancel_subscription" | "pause_subscription" | "resume_subscription" | "create_payment" | "get_payment" | "search_payments" | "cancel_payment" | "capture_payment" | "refund_payment" | "list_refunds" | "create_payment_preference" | "get_payment_preference" | "create_customer" | "find_customer_by_email" | "list_customer_cards" | "delete_customer_card" | "list_payment_methods" | "calculate_installments" | "get_account_info" | "charge_saved_card" | "create_qr_payment" | "cancel_qr_payment" | "create_subscription_plan" | "list_subscription_plans" | "update_subscription_plan" | "subscribe_to_plan" | "list_subscription_payments" | "create_store" | "list_stores" | "create_pos" | "list_pos" | "list_payment_disputes" | "get_dispute" | "list_identification_types" | "list_issuers" | "list_webhooks" | "create_webhook" | "update_webhook" | "delete_webhook" | "handle_webhook" | "oauth_authorize_url" | "oauth_exchange_code" | "oauth_refresh_token" | "create_order" | "get_order" | "update_order" | "capture_order" | "cancel_order" | "get_account_balance" | "list_account_movements" | "list_settlements" | "get_settlement" | "analyze_payment_3ds" | "get_test_cards" | "get_customer" | "update_customer" | "create_customer_card" | "get_customer_card" | "get_subscription_plan" | "update_subscription" | "search_subscriptions" | "get_refund" | "update_payment_preference" | "get_merchant_order" | "search_merchant_orders" | "update_merchant_order" | "get_store" | "update_store" | "delete_store" | "get_pos" | "update_pos" | "delete_pos" | "list_bank_accounts" | "register_bank_account" | "list_point_devices" | "update_point_device_mode" | "create_point_payment_intent" | "get_point_payment_intent" | "cancel_point_payment_intent" | "compute_marketplace_fee" | "explain_payment_status" | "mp_health_check" | "find_applicable_promos" | "confirm_3ds_challenge" | "search_payments_all" | "list_settlements_all" | "validate_tax_id";
|
|
1918
2151
|
/**
|
|
1919
2152
|
* Build a tool set for the Vercel AI SDK that exposes Mercado Pago to an
|
|
1920
2153
|
* agent. Pass directly to `Experimental_Agent`'s `tools` option, or merge with
|
|
@@ -2241,6 +2474,559 @@ declare function buildTestCardScenario(cardKey: keyof typeof TEST_CARDS_AR, scen
|
|
|
2241
2474
|
* Analyze a Payment's 3DS state. Pure function, no I/O.
|
|
2242
2475
|
*/
|
|
2243
2476
|
declare function analyze3DS(payment: Payment): ThreeDSInfo;
|
|
2477
|
+
/**
|
|
2478
|
+
* Submit the 3DS challenge result back to MP after the buyer completes the
|
|
2479
|
+
* issuer challenge. Used as the FINAL step in the 3DS challenge flow:
|
|
2480
|
+
*
|
|
2481
|
+
* 1. `createPayment` returns `pending` + `pending_challenge` status_detail
|
|
2482
|
+
* 2. `analyze3DS(payment)` extracts the `challengeUrl`
|
|
2483
|
+
* 3. Buyer is redirected to `challengeUrl` and completes the challenge
|
|
2484
|
+
* 4. The issuer redirects to your `back_url` with a `challenge_complete=true`
|
|
2485
|
+
* (or similar query — depends on issuer / browser flow)
|
|
2486
|
+
* 5. **You call this method** to confirm the challenge and finalize the payment
|
|
2487
|
+
*
|
|
2488
|
+
* # Why this is separate
|
|
2489
|
+
*
|
|
2490
|
+
* Step 5 isn't documented as a SINGLE endpoint in MP's public docs — different
|
|
2491
|
+
* 3DS providers (Mastercard, Visa, Cabal) handle the challenge resolution
|
|
2492
|
+
* differently. This method tries the documented path: re-fetching the payment
|
|
2493
|
+
* via `getPayment` after the challenge — MP updates the status server-side
|
|
2494
|
+
* once the issuer reports the challenge result via their backchannel.
|
|
2495
|
+
*
|
|
2496
|
+
* # When to call
|
|
2497
|
+
*
|
|
2498
|
+
* - **Before** showing the user a final "approved/rejected" screen
|
|
2499
|
+
* - **After** the buyer is redirected back from the challenge URL
|
|
2500
|
+
* - **With backoff**: MP sometimes lags by a few seconds — recommended to
|
|
2501
|
+
* poll `getPayment` 3-5 times with 1s spacing if the first call still
|
|
2502
|
+
* returns `pending_challenge`.
|
|
2503
|
+
*/
|
|
2504
|
+
declare function confirmChallengeAndPoll(client: MercadoPagoClient, paymentId: string, options?: {
|
|
2505
|
+
/** Maximum number of polls. Default 5. */
|
|
2506
|
+
maxAttempts?: number;
|
|
2507
|
+
/** Sleep between polls in ms. Default 1000ms. */
|
|
2508
|
+
pollIntervalMs?: number;
|
|
2509
|
+
/** Optional AbortSignal to cap the total wait. */
|
|
2510
|
+
signal?: AbortSignal;
|
|
2511
|
+
}): Promise<{
|
|
2512
|
+
payment: Payment;
|
|
2513
|
+
threeDs: ThreeDSInfo;
|
|
2514
|
+
resolved: boolean;
|
|
2515
|
+
attempts: number;
|
|
2516
|
+
}>;
|
|
2517
|
+
|
|
2518
|
+
/**
|
|
2519
|
+
* Pagination helpers — automatic pagination over MP's paginated endpoints
|
|
2520
|
+
* via AsyncIterable. Replaces the manual offset/limit loop.
|
|
2521
|
+
*
|
|
2522
|
+
* # Why
|
|
2523
|
+
*
|
|
2524
|
+
* MP's paginated endpoints (search_payments, search_subscriptions,
|
|
2525
|
+
* list_account_movements, list_settlements, search_merchant_orders, etc.)
|
|
2526
|
+
* cap responses at 100 items per page. Iterating "all matching X" without
|
|
2527
|
+
* helpers means writing the offset+limit loop in every caller — annoying
|
|
2528
|
+
* + error-prone (off-by-one bugs are common).
|
|
2529
|
+
*
|
|
2530
|
+
* # Usage
|
|
2531
|
+
*
|
|
2532
|
+
* ```ts
|
|
2533
|
+
* import { paginate } from "@ar-agents/mercadopago";
|
|
2534
|
+
*
|
|
2535
|
+
* for await (const payment of paginate(
|
|
2536
|
+
* (offset) => client.searchPayments({ offset, limit: 100, status: "approved" }),
|
|
2537
|
+
* { extractItems: (page) => page.results ?? [], extractTotal: (page) => page.paging?.total ?? 0 },
|
|
2538
|
+
* )) {
|
|
2539
|
+
* console.log(payment.id);
|
|
2540
|
+
* }
|
|
2541
|
+
* ```
|
|
2542
|
+
*
|
|
2543
|
+
* Or use the convenience wrappers below:
|
|
2544
|
+
*
|
|
2545
|
+
* ```ts
|
|
2546
|
+
* for await (const payment of paginatePayments(client, { status: "approved" })) {
|
|
2547
|
+
* console.log(payment.id);
|
|
2548
|
+
* }
|
|
2549
|
+
*
|
|
2550
|
+
* // Materialize all (only when sure it fits in memory):
|
|
2551
|
+
* const allPayments = await collect(paginatePayments(client, { status: "approved" }));
|
|
2552
|
+
* ```
|
|
2553
|
+
*
|
|
2554
|
+
* # Performance
|
|
2555
|
+
*
|
|
2556
|
+
* - **Streaming**: items are yielded as each page arrives — your downstream
|
|
2557
|
+
* work can start before all pages are fetched.
|
|
2558
|
+
* - **Bounded concurrency**: by default fetches one page at a time. Pass
|
|
2559
|
+
* `concurrency: 4` to prefetch up to 4 pages ahead (faster, more bandwidth).
|
|
2560
|
+
* - **Total cap**: pass `maxItems: 1000` to bail out early.
|
|
2561
|
+
*
|
|
2562
|
+
* # Edge cases handled
|
|
2563
|
+
*
|
|
2564
|
+
* - Empty pages (returns no items, terminates).
|
|
2565
|
+
* - Pages where total < expected (terminates correctly).
|
|
2566
|
+
* - Mid-iteration cancellation (caller breaks the for-await — no further fetches).
|
|
2567
|
+
* - Paging.total === 0 (terminates immediately).
|
|
2568
|
+
*/
|
|
2569
|
+
|
|
2570
|
+
interface PaginateOptions<TPage, TItem> {
|
|
2571
|
+
/** Extract the items array from a page. */
|
|
2572
|
+
extractItems: (page: TPage) => TItem[];
|
|
2573
|
+
/**
|
|
2574
|
+
* Extract the total count from a page. Used to know when to stop.
|
|
2575
|
+
* If not available, the iterator terminates when an empty page arrives.
|
|
2576
|
+
*/
|
|
2577
|
+
extractTotal?: (page: TPage) => number | undefined;
|
|
2578
|
+
/** Page size. Default 100 (MP's max for most endpoints). */
|
|
2579
|
+
pageSize?: number;
|
|
2580
|
+
/**
|
|
2581
|
+
* Stop after yielding `maxItems` total. Useful for "first N matching"
|
|
2582
|
+
* queries that would otherwise iterate the full result set.
|
|
2583
|
+
*/
|
|
2584
|
+
maxItems?: number;
|
|
2585
|
+
/**
|
|
2586
|
+
* Number of pages to prefetch concurrently. Default 1 (no prefetch).
|
|
2587
|
+
* Higher = lower wall-clock time but more concurrent MP requests.
|
|
2588
|
+
*/
|
|
2589
|
+
concurrency?: number;
|
|
2590
|
+
}
|
|
2591
|
+
/**
|
|
2592
|
+
* Generic paginator. Most callers use the typed convenience wrappers below.
|
|
2593
|
+
*
|
|
2594
|
+
* @param fetchPage Function that fetches page N given the offset.
|
|
2595
|
+
*/
|
|
2596
|
+
declare function paginate<TPage, TItem>(fetchPage: (offset: number, limit: number) => Promise<TPage>, opts: PaginateOptions<TPage, TItem>): AsyncGenerator<TItem, void, undefined>;
|
|
2597
|
+
/** Materialize an AsyncIterable into an array. Caller's responsibility to ensure it fits. */
|
|
2598
|
+
declare function collect<T>(iter: AsyncIterable<T>): Promise<T[]>;
|
|
2599
|
+
declare function paginatePayments(client: MercadoPagoClient, filter?: Parameters<MercadoPagoClient["searchPayments"]>[0], opts?: {
|
|
2600
|
+
pageSize?: number;
|
|
2601
|
+
maxItems?: number;
|
|
2602
|
+
concurrency?: number;
|
|
2603
|
+
}): AsyncGenerator<Payment, void, undefined>;
|
|
2604
|
+
declare function paginateSubscriptions(client: MercadoPagoClient, filter?: Parameters<MercadoPagoClient["searchPreapprovals"]>[0], opts?: {
|
|
2605
|
+
pageSize?: number;
|
|
2606
|
+
maxItems?: number;
|
|
2607
|
+
concurrency?: number;
|
|
2608
|
+
}): AsyncGenerator<Preapproval, void, undefined>;
|
|
2609
|
+
declare function paginateAccountMovements(client: MercadoPagoClient, filter?: {
|
|
2610
|
+
from?: string;
|
|
2611
|
+
to?: string;
|
|
2612
|
+
}, opts?: {
|
|
2613
|
+
pageSize?: number;
|
|
2614
|
+
maxItems?: number;
|
|
2615
|
+
concurrency?: number;
|
|
2616
|
+
}): AsyncGenerator<AccountMovement, void, undefined>;
|
|
2617
|
+
declare function paginateSettlements(client: MercadoPagoClient, filter?: {
|
|
2618
|
+
from?: string;
|
|
2619
|
+
to?: string;
|
|
2620
|
+
status?: string;
|
|
2621
|
+
}, opts?: {
|
|
2622
|
+
pageSize?: number;
|
|
2623
|
+
maxItems?: number;
|
|
2624
|
+
concurrency?: number;
|
|
2625
|
+
}): AsyncGenerator<Settlement, void, undefined>;
|
|
2626
|
+
declare function paginateMerchantOrders(client: MercadoPagoClient, filter?: Parameters<MercadoPagoClient["searchMerchantOrders"]>[0], opts?: {
|
|
2627
|
+
pageSize?: number;
|
|
2628
|
+
maxItems?: number;
|
|
2629
|
+
concurrency?: number;
|
|
2630
|
+
}): AsyncGenerator<MerchantOrder, void, undefined>;
|
|
2631
|
+
declare function paginateSubscriptionPlans(client: MercadoPagoClient, filter?: {
|
|
2632
|
+
status?: string;
|
|
2633
|
+
}, opts?: {
|
|
2634
|
+
pageSize?: number;
|
|
2635
|
+
maxItems?: number;
|
|
2636
|
+
concurrency?: number;
|
|
2637
|
+
}): AsyncGenerator<SubscriptionPlan, void, undefined>;
|
|
2638
|
+
declare function paginateSubscriptionPayments(client: MercadoPagoClient, preapprovalId: string, opts?: {
|
|
2639
|
+
pageSize?: number;
|
|
2640
|
+
maxItems?: number;
|
|
2641
|
+
concurrency?: number;
|
|
2642
|
+
}): AsyncGenerator<SubscriptionPayment, void, undefined>;
|
|
2643
|
+
|
|
2644
|
+
/**
|
|
2645
|
+
* Token bucket rate limiter — proactive client-side rate limiting.
|
|
2646
|
+
*
|
|
2647
|
+
* # Why proactive
|
|
2648
|
+
*
|
|
2649
|
+
* The current client honors `Retry-After` after a 429 (reactive). That's
|
|
2650
|
+
* good but suboptimal: every 429 still costs you a network round-trip, an
|
|
2651
|
+
* error log, and adds latency to the retry. Proactive rate limiting reads
|
|
2652
|
+
* MP's `x-rate-limit-remaining` header and slows down BEFORE the next 429.
|
|
2653
|
+
*
|
|
2654
|
+
* # The token bucket model
|
|
2655
|
+
*
|
|
2656
|
+
* - The bucket holds N tokens (the burst capacity).
|
|
2657
|
+
* - Tokens refill at R tokens/second (the steady-state rate).
|
|
2658
|
+
* - Each request consumes 1 token.
|
|
2659
|
+
* - When the bucket is empty, requests wait until a token is available.
|
|
2660
|
+
*
|
|
2661
|
+
* Example: capacity=20, refill=10/s means "burst 20 requests, then 10/s
|
|
2662
|
+
* sustained". Matches MP's typical limits (precise numbers vary by endpoint
|
|
2663
|
+
* and aren't publicly documented).
|
|
2664
|
+
*
|
|
2665
|
+
* # Per-host vs global
|
|
2666
|
+
*
|
|
2667
|
+
* Default: one bucket per `MercadoPagoClient`. Pass a SHARED bucket to
|
|
2668
|
+
* multiple clients in marketplace setups so they share the rate limit
|
|
2669
|
+
* (otherwise each per-seller client would think it has its own quota).
|
|
2670
|
+
*
|
|
2671
|
+
* # Adaptive learning
|
|
2672
|
+
*
|
|
2673
|
+
* The bucket auto-tunes from response headers: if MP says
|
|
2674
|
+
* `x-rate-limit-remaining: 5` and the bucket has 50 tokens, the bucket
|
|
2675
|
+
* is over-spending. The `learnFromHeaders` method updates the available
|
|
2676
|
+
* count to the lower of (current, MP's stated remaining).
|
|
2677
|
+
*/
|
|
2678
|
+
interface RateLimiterOptions {
|
|
2679
|
+
/** Bucket capacity (max burst). Default 50. */
|
|
2680
|
+
capacity?: number;
|
|
2681
|
+
/** Refill rate in tokens per second. Default 25. */
|
|
2682
|
+
refillPerSecond?: number;
|
|
2683
|
+
/**
|
|
2684
|
+
* If true, the limiter calls `learnFromHeaders` after every successful
|
|
2685
|
+
* request to keep its bucket in sync with MP's actual quota. Default true.
|
|
2686
|
+
*/
|
|
2687
|
+
adaptive?: boolean;
|
|
2688
|
+
/**
|
|
2689
|
+
* Hard cap on how long `acquire()` will wait. If the bucket can't refill
|
|
2690
|
+
* in this time, `acquire()` rejects with `RateLimitTimeoutError`.
|
|
2691
|
+
* Default 30s — anything longer is probably better handled as an error.
|
|
2692
|
+
*/
|
|
2693
|
+
acquireTimeoutMs?: number;
|
|
2694
|
+
/** Time provider (testing). Defaults to Date.now. */
|
|
2695
|
+
now?: () => number;
|
|
2696
|
+
}
|
|
2697
|
+
declare class RateLimitTimeoutError extends Error {
|
|
2698
|
+
readonly waitedMs: number;
|
|
2699
|
+
constructor(waitedMs: number);
|
|
2700
|
+
}
|
|
2701
|
+
declare class TokenBucketRateLimiter {
|
|
2702
|
+
private tokens;
|
|
2703
|
+
private lastRefill;
|
|
2704
|
+
private readonly capacity;
|
|
2705
|
+
private readonly refillPerSecond;
|
|
2706
|
+
private readonly adaptive;
|
|
2707
|
+
private readonly acquireTimeoutMs;
|
|
2708
|
+
private readonly now;
|
|
2709
|
+
constructor(opts?: RateLimiterOptions);
|
|
2710
|
+
/**
|
|
2711
|
+
* Acquire a token. Resolves immediately if tokens are available;
|
|
2712
|
+
* otherwise waits until one is. Rejects with `RateLimitTimeoutError`
|
|
2713
|
+
* if the wait exceeds `acquireTimeoutMs`.
|
|
2714
|
+
*/
|
|
2715
|
+
acquire(): Promise<void>;
|
|
2716
|
+
/**
|
|
2717
|
+
* Best-effort acquire: returns true if a token was available, false
|
|
2718
|
+
* otherwise. Doesn't wait. Useful for "non-blocking" code paths that
|
|
2719
|
+
* want to fall back to a cached response or queue the request elsewhere.
|
|
2720
|
+
*/
|
|
2721
|
+
tryAcquire(): boolean;
|
|
2722
|
+
/**
|
|
2723
|
+
* Adaptive learning hook — call after every API response with MP's
|
|
2724
|
+
* rate-limit headers to keep the bucket in sync with reality.
|
|
2725
|
+
*/
|
|
2726
|
+
learnFromHeaders(headers: {
|
|
2727
|
+
remaining: number | null;
|
|
2728
|
+
resetSeconds: number | null;
|
|
2729
|
+
}): void;
|
|
2730
|
+
/** Inspect the current bucket state. */
|
|
2731
|
+
getStats(): {
|
|
2732
|
+
tokens: number;
|
|
2733
|
+
capacity: number;
|
|
2734
|
+
refillPerSecond: number;
|
|
2735
|
+
};
|
|
2736
|
+
private refill;
|
|
2737
|
+
}
|
|
2738
|
+
|
|
2739
|
+
/**
|
|
2740
|
+
* Argentine issuer cuotas promotional catalog — embedded knowledge of which
|
|
2741
|
+
* banks/cards have "cuotas sin interés" (interest-free installment) deals
|
|
2742
|
+
* with which sellers, on which days.
|
|
2743
|
+
*
|
|
2744
|
+
* # Why embed this
|
|
2745
|
+
*
|
|
2746
|
+
* MP's `calculate_installments` API returns the CURRENT cuotas options for
|
|
2747
|
+
* a given (payment_method, amount, bin) tuple — but it doesn't tell the
|
|
2748
|
+
* agent which deals are GENERALLY available (e.g., "Naranja con Galicia, 6
|
|
2749
|
+
* cuotas sin interés todos los martes"). Devs surface that information to
|
|
2750
|
+
* buyers BEFORE checkout to drive conversion.
|
|
2751
|
+
*
|
|
2752
|
+
* This catalog is the AR-specific knowledge that turns the toolkit from
|
|
2753
|
+
* "MP API wrapper" into "MP integration with retail context".
|
|
2754
|
+
*
|
|
2755
|
+
* # Sources
|
|
2756
|
+
*
|
|
2757
|
+
* - Each issuer's published "Cuotas Simples" / "Ahora 12" page
|
|
2758
|
+
* - BCRA Comunicación A 7825 (financiamiento al consumo)
|
|
2759
|
+
* - Manually verified against Naranja, Galicia, Santander, Macro, BBVA, ICBC
|
|
2760
|
+
* Patagonia, Banco Nación, Banco Provincia, Banco Ciudad, Comafi, HSBC
|
|
2761
|
+
* public landing pages
|
|
2762
|
+
*
|
|
2763
|
+
* # Maintenance
|
|
2764
|
+
*
|
|
2765
|
+
* The promos schedule changes seasonally. Update this file quarterly + when
|
|
2766
|
+
* BCRA publishes a new "Ahora N" program. PRs welcomed.
|
|
2767
|
+
*
|
|
2768
|
+
* Last sync: 2026-Q2.
|
|
2769
|
+
*/
|
|
2770
|
+
interface CuotasPromo {
|
|
2771
|
+
/** Issuer name (matches `list_issuers` response). */
|
|
2772
|
+
issuer: string;
|
|
2773
|
+
/** Card brand (visa, master, amex, naranja, cabal, etc.). */
|
|
2774
|
+
paymentMethodId: string;
|
|
2775
|
+
/** Number of interest-free installments. */
|
|
2776
|
+
installments: number;
|
|
2777
|
+
/** Days of the week the promo applies. Empty = always. */
|
|
2778
|
+
daysOfWeek?: Array<"mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun">;
|
|
2779
|
+
/** ISO date when the promo starts (inclusive). */
|
|
2780
|
+
startDate?: string;
|
|
2781
|
+
/** ISO date when the promo expires (inclusive). */
|
|
2782
|
+
endDate?: string;
|
|
2783
|
+
/** Minimum purchase amount in ARS for the promo to apply. */
|
|
2784
|
+
minAmountArs?: number;
|
|
2785
|
+
/** Maximum monthly cap on the promo per cardholder. Optional. */
|
|
2786
|
+
maxAmountArs?: number;
|
|
2787
|
+
/** Free-form description shown to the buyer. ALWAYS surface verbatim. */
|
|
2788
|
+
description: string;
|
|
2789
|
+
/** Categories where the promo applies (per BCRA codes). Empty = any. */
|
|
2790
|
+
categories?: Array<"electronics" | "appliances" | "clothing" | "supermarket" | "travel" | "education" | "health" | "general">;
|
|
2791
|
+
}
|
|
2792
|
+
/**
|
|
2793
|
+
* The "Ahora 12 / 18 / 24 / 30" national program — recurring federal scheme
|
|
2794
|
+
* that subsidizes interest-free installments on essential categories.
|
|
2795
|
+
*
|
|
2796
|
+
* As of 2026-Q2: 3, 6, 12, 18, 24, 30 installment options on appliances,
|
|
2797
|
+
* electronics, clothing, books, school supplies, tires, eyewear, motorcycles,
|
|
2798
|
+
* national-tourism services. Not all categories qualify for all tiers.
|
|
2799
|
+
*/
|
|
2800
|
+
declare const AHORA_PROGRAM_PROMOS: CuotasPromo[];
|
|
2801
|
+
/**
|
|
2802
|
+
* Issuer-specific promos (running in addition to the Ahora program).
|
|
2803
|
+
*
|
|
2804
|
+
* Note: these change frequently. Check `lastVerified` before relying.
|
|
2805
|
+
*/
|
|
2806
|
+
declare const AR_ISSUER_PROMOS: CuotasPromo[];
|
|
2807
|
+
/**
|
|
2808
|
+
* Find applicable promos for a given context.
|
|
2809
|
+
*
|
|
2810
|
+
* Pure function — no I/O. Use to surface "cuotas sin interés" hints to the
|
|
2811
|
+
* buyer BEFORE they call `calculate_installments` (the API only returns
|
|
2812
|
+
* what's offered for the EXACT card, which the buyer hasn't entered yet).
|
|
2813
|
+
*
|
|
2814
|
+
* @example
|
|
2815
|
+
* ```ts
|
|
2816
|
+
* import { findApplicablePromos } from "@ar-agents/mercadopago";
|
|
2817
|
+
*
|
|
2818
|
+
* const promos = findApplicablePromos({
|
|
2819
|
+
* issuer: "Banco Galicia",
|
|
2820
|
+
* paymentMethodId: "visa",
|
|
2821
|
+
* amountArs: 50_000,
|
|
2822
|
+
* category: "supermarket",
|
|
2823
|
+
* date: new Date(), // optional, defaults to now
|
|
2824
|
+
* });
|
|
2825
|
+
* // → [{ installments: 12, description: "Galicia ... 12 cuotas sin interés ...", ... }]
|
|
2826
|
+
* ```
|
|
2827
|
+
*/
|
|
2828
|
+
declare function findApplicablePromos(args: {
|
|
2829
|
+
issuer?: string;
|
|
2830
|
+
paymentMethodId?: string;
|
|
2831
|
+
amountArs?: number;
|
|
2832
|
+
category?: NonNullable<CuotasPromo["categories"]>[number];
|
|
2833
|
+
date?: Date;
|
|
2834
|
+
/** Include the Ahora program in addition to issuer-specific. Default true. */
|
|
2835
|
+
includeAhoraProgram?: boolean;
|
|
2836
|
+
}): CuotasPromo[];
|
|
2837
|
+
|
|
2838
|
+
/**
|
|
2839
|
+
* Tool middleware — composable wrappers around any Vercel AI SDK tool.
|
|
2840
|
+
*
|
|
2841
|
+
* # The pattern
|
|
2842
|
+
*
|
|
2843
|
+
* Vercel AI SDK tools have a uniform shape: `{ description, inputSchema, execute }`.
|
|
2844
|
+
* Middleware wraps a tool's `execute()` with cross-cutting concerns (logging,
|
|
2845
|
+
* rate limiting, retries, metrics) WITHOUT modifying the tool itself.
|
|
2846
|
+
*
|
|
2847
|
+
* Compose middleware to layer behaviors:
|
|
2848
|
+
*
|
|
2849
|
+
* ```ts
|
|
2850
|
+
* import { withAuditLog, withRateLimit, withMetrics, compose } from "@ar-agents/mercadopago";
|
|
2851
|
+
*
|
|
2852
|
+
* const baseTools = mercadoPagoTools(client, { state, backUrl });
|
|
2853
|
+
*
|
|
2854
|
+
* const tools = Object.fromEntries(
|
|
2855
|
+
* Object.entries(baseTools).map(([name, tool]) => [
|
|
2856
|
+
* name,
|
|
2857
|
+
* compose(
|
|
2858
|
+
* withMetrics(name, { onMetric: (m) => statsd.increment(...) }),
|
|
2859
|
+
* withRateLimit(rateLimiter),
|
|
2860
|
+
* withAuditLog(auditLogger, name),
|
|
2861
|
+
* )(tool),
|
|
2862
|
+
* ])
|
|
2863
|
+
* );
|
|
2864
|
+
* ```
|
|
2865
|
+
*
|
|
2866
|
+
* # Why this matters
|
|
2867
|
+
*
|
|
2868
|
+
* Without middleware, every cross-cutting concern (audit, rate limit, retry)
|
|
2869
|
+
* has to be wired INTO the tool implementation OR repeated at every call
|
|
2870
|
+
* site. Middleware lets you add/remove/swap concerns from a single config
|
|
2871
|
+
* point — clean separation of concerns + testable in isolation.
|
|
2872
|
+
*/
|
|
2873
|
+
|
|
2874
|
+
/**
|
|
2875
|
+
* A tool middleware — takes a tool, returns a wrapped tool with the same
|
|
2876
|
+
* shape but enhanced behavior in `execute()`.
|
|
2877
|
+
*/
|
|
2878
|
+
type ToolMiddleware = <T extends Tool<unknown, unknown>>(tool: T) => T;
|
|
2879
|
+
/**
|
|
2880
|
+
* Compose multiple middleware functions. The LAST middleware in the list
|
|
2881
|
+
* runs INNERMOST (closest to the original tool's execute):
|
|
2882
|
+
*
|
|
2883
|
+
* ```
|
|
2884
|
+
* compose(a, b, c)(tool) == a(b(c(tool)))
|
|
2885
|
+
* ```
|
|
2886
|
+
*
|
|
2887
|
+
* Reasoning: the most "core" concerns (e.g. audit log) typically wrap the
|
|
2888
|
+
* actual call closely (innermost), while observability layers (e.g. metrics,
|
|
2889
|
+
* tracing) sit outside.
|
|
2890
|
+
*
|
|
2891
|
+
* @example
|
|
2892
|
+
* ```ts
|
|
2893
|
+
* const enhance = compose(
|
|
2894
|
+
* withMetrics("create_payment"), // outer (records duration of everything below)
|
|
2895
|
+
* withRateLimit(limiter), // middle (rate-limits before the call)
|
|
2896
|
+
* withAuditLog(audit, "create_payment"), // inner (records the call result)
|
|
2897
|
+
* );
|
|
2898
|
+
* const enhanced = enhance(originalTool);
|
|
2899
|
+
* ```
|
|
2900
|
+
*/
|
|
2901
|
+
declare function compose(...middlewares: ToolMiddleware[]): ToolMiddleware;
|
|
2902
|
+
/**
|
|
2903
|
+
* Wrap a tool's `execute()` with audit logging. Every call records an entry
|
|
2904
|
+
* with operation, actor, inputHash, outcome, and duration.
|
|
2905
|
+
*
|
|
2906
|
+
* @param logger The configured AuditLogger.
|
|
2907
|
+
* @param operation The operation name (matches AuditOperation union).
|
|
2908
|
+
* @param actor Optional actor override (defaults to logger's defaultActor).
|
|
2909
|
+
*/
|
|
2910
|
+
declare function withAuditLog(logger: AuditLogger, operation: AuditOperation, actor?: string): ToolMiddleware;
|
|
2911
|
+
/**
|
|
2912
|
+
* Wrap a tool's `execute()` with rate limiting. Acquires a token from the
|
|
2913
|
+
* bucket BEFORE the call; if the bucket is empty, awaits up to the bucket's
|
|
2914
|
+
* `acquireTimeoutMs`. Throws `RateLimitTimeoutError` if the wait exceeds it.
|
|
2915
|
+
*/
|
|
2916
|
+
declare function withRateLimit(limiter: TokenBucketRateLimiter): ToolMiddleware;
|
|
2917
|
+
interface MetricsHook {
|
|
2918
|
+
/**
|
|
2919
|
+
* Called after every tool invocation. Synchronous, fire-and-forget.
|
|
2920
|
+
* Compatible with Datadog, StatsD, Prometheus client, OTEL meter, etc.
|
|
2921
|
+
*/
|
|
2922
|
+
onMetric: (event: {
|
|
2923
|
+
toolName: string;
|
|
2924
|
+
durationMs: number;
|
|
2925
|
+
success: boolean;
|
|
2926
|
+
errorCode?: string;
|
|
2927
|
+
}) => void;
|
|
2928
|
+
}
|
|
2929
|
+
/**
|
|
2930
|
+
* Wrap a tool's `execute()` with metrics emission. Records duration + a
|
|
2931
|
+
* success/error counter for every call.
|
|
2932
|
+
*/
|
|
2933
|
+
declare function withMetrics(toolName: string, hook: MetricsHook): ToolMiddleware;
|
|
2934
|
+
interface RetryOptions {
|
|
2935
|
+
/** Max attempts including initial. Default 3. */
|
|
2936
|
+
maxAttempts?: number;
|
|
2937
|
+
/** Base backoff in ms (multiplied by 2^attempt). Default 250. */
|
|
2938
|
+
baseBackoffMs?: number;
|
|
2939
|
+
/**
|
|
2940
|
+
* Predicate: should this error trigger a retry? Default: retries on
|
|
2941
|
+
* any thrown Error EXCEPT MercadoPagoError 4xx (those are user errors).
|
|
2942
|
+
*/
|
|
2943
|
+
shouldRetry?: (err: unknown, attempt: number) => boolean;
|
|
2944
|
+
/** Optional hook fired on every retry attempt. */
|
|
2945
|
+
onRetry?: (event: {
|
|
2946
|
+
attempt: number;
|
|
2947
|
+
error: unknown;
|
|
2948
|
+
delayMs: number;
|
|
2949
|
+
}) => void;
|
|
2950
|
+
}
|
|
2951
|
+
/**
|
|
2952
|
+
* Wrap a tool's `execute()` with retry-with-backoff. Useful for tools that
|
|
2953
|
+
* call external APIs not protected by the underlying client's retry budget
|
|
2954
|
+
* (e.g., agent-side aggregation tools).
|
|
2955
|
+
*
|
|
2956
|
+
* The MercadoPagoClient already retries internally on 5xx/429, so layering
|
|
2957
|
+
* this on top of MP-backed tools usually means total retries = client × tool.
|
|
2958
|
+
* Use sparingly.
|
|
2959
|
+
*/
|
|
2960
|
+
declare function withRetry(opts?: RetryOptions): ToolMiddleware;
|
|
2961
|
+
/**
|
|
2962
|
+
* Apply a middleware to every tool in a ToolSet. Useful for blanket policies:
|
|
2963
|
+
* "all tools rate-limited", "all tools metrics-emitted".
|
|
2964
|
+
*
|
|
2965
|
+
* @example
|
|
2966
|
+
* ```ts
|
|
2967
|
+
* const baseTools = mercadoPagoTools(client, { state, backUrl });
|
|
2968
|
+
* const limited = applyToAllTools(baseTools, withRateLimit(limiter));
|
|
2969
|
+
* ```
|
|
2970
|
+
*/
|
|
2971
|
+
declare function applyToAllTools<T extends Record<string, Tool<unknown, unknown>>>(tools: T, middleware: ToolMiddleware): T;
|
|
2972
|
+
|
|
2973
|
+
/**
|
|
2974
|
+
* TaxID validation across LATAM — pure-algorithm validators for the major
|
|
2975
|
+
* jurisdictions where MP operates. NO network calls.
|
|
2976
|
+
*
|
|
2977
|
+
* # Why
|
|
2978
|
+
*
|
|
2979
|
+
* Marketplace-style apps that span multiple LATAM countries need to
|
|
2980
|
+
* validate buyer/seller tax IDs in their respective formats: AR (DNI/CUIT/CUIL),
|
|
2981
|
+
* BR (CPF/CNPJ), MX (RFC), CL (RUT), CO (NIT), UY (RUT), PE (RUC).
|
|
2982
|
+
*
|
|
2983
|
+
* Each country has its own checksum algorithm. Wiring this once per app
|
|
2984
|
+
* is annoying + error-prone. Embedding it here means the agent can
|
|
2985
|
+
* validate ANY LATAM tax ID with a single tool call.
|
|
2986
|
+
*
|
|
2987
|
+
* # Sources
|
|
2988
|
+
*
|
|
2989
|
+
* - AR DNI/CUIT/CUIL: AFIP RG 100/1998 (modulo-11 checksum)
|
|
2990
|
+
* - BR CPF: Receita Federal (two-step modulo-11)
|
|
2991
|
+
* - BR CNPJ: Receita Federal (two-step weighted modulo)
|
|
2992
|
+
* - MX RFC: SAT regex + 13-char structure
|
|
2993
|
+
* - CL RUT: SII modulo-11 + check digit "0-9, K"
|
|
2994
|
+
* - CO NIT: DIAN modulo-11
|
|
2995
|
+
* - UY RUT: 12-digit numeric + checksum
|
|
2996
|
+
* - PE RUC: SUNAT 11-digit + checksum
|
|
2997
|
+
*/
|
|
2998
|
+
type TaxIdCountry = "AR" | "BR" | "MX" | "CL" | "CO" | "UY" | "PE";
|
|
2999
|
+
type TaxIdType = "DNI" | "CUIT" | "CUIL" | "CPF" | "CNPJ" | "RFC" | "RUT_CL" | "NIT" | "RUT_UY" | "RUC";
|
|
3000
|
+
interface TaxIdValidationResult {
|
|
3001
|
+
valid: boolean;
|
|
3002
|
+
/** Bare digits/chars after normalization (no separators). */
|
|
3003
|
+
normalized: string;
|
|
3004
|
+
/** Pretty-formatted version with country-specific separators. */
|
|
3005
|
+
formatted: string | null;
|
|
3006
|
+
type: TaxIdType;
|
|
3007
|
+
country: TaxIdCountry;
|
|
3008
|
+
/** Spanish error message when invalid. Surface verbatim to users. */
|
|
3009
|
+
error: string | null;
|
|
3010
|
+
}
|
|
3011
|
+
/**
|
|
3012
|
+
* Validate a tax ID against the appropriate country algorithm.
|
|
3013
|
+
*
|
|
3014
|
+
* @example
|
|
3015
|
+
* validateTaxId("20-41758101-5", "CUIT")
|
|
3016
|
+
* // → { valid: true, normalized: "20417581015", formatted: "20-41758101-5", ... }
|
|
3017
|
+
*
|
|
3018
|
+
* @example
|
|
3019
|
+
* validateTaxId("123.456.789-09", "CPF")
|
|
3020
|
+
* // → { valid: true, normalized: "12345678909", ... }
|
|
3021
|
+
*/
|
|
3022
|
+
declare function validateTaxId(input: string, type: TaxIdType): TaxIdValidationResult;
|
|
3023
|
+
/**
|
|
3024
|
+
* Convenience: try to detect the type from the input shape + country, then
|
|
3025
|
+
* validate. Useful when the agent doesn't know if it's a CPF or a CNPJ.
|
|
3026
|
+
*
|
|
3027
|
+
* @returns null when the input doesn't match any known type for the country
|
|
3028
|
+
*/
|
|
3029
|
+
declare function detectAndValidate(input: string, country: TaxIdCountry): TaxIdValidationResult | null;
|
|
2244
3030
|
|
|
2245
3031
|
/**
|
|
2246
3032
|
* Pure helpers — no I/O, deterministic, fast. Importable directly from the
|
|
@@ -2307,4 +3093,4 @@ interface PaymentStatusExplanation {
|
|
|
2307
3093
|
*/
|
|
2308
3094
|
declare function explainPaymentStatus(payment: Payment): PaymentStatusExplanation;
|
|
2309
3095
|
|
|
2310
|
-
export { type AccountBalance, type AccountInfo, type AccountMovement, type AutoRecurring, type BankAccount, type CardToken, CircuitBreaker, type CircuitBreakerOptions, CircuitOpenError, type CircuitState, type CreateCardTokenParams, type CreateCustomerParams, type CreateOrderParams, type CreatePaymentParams, type CreatePointPaymentIntentParams, type CreatePosParams, type CreatePreapprovalParams, type CreatePreferenceParams, type CreateQrPaymentParams, type CreateRefundParams, type CreateStoreParams, type CreateSubscriptionPlanParams, type CreateWebhookParams, type CurrencyId, type Customer, type CustomerCard, type Dispute, type FrequencyType, type IdentificationType, type InstallmentOffer, type Issuer, type MarketplaceFeeRule, type MarketplaceParams, MercadoPagoAccountTypeMismatchError, MercadoPagoAuthError, MercadoPagoAuthorizeForbiddenError, MercadoPagoBackUrlInvalidError, MercadoPagoClient, type MercadoPagoClientOptions, MercadoPagoError, MercadoPagoOverloadedError, MercadoPagoPaymentRejectedError, MercadoPagoRateLimitError, MercadoPagoSelfPaymentError, MercadoPagoTimeoutError, type MercadoPagoToolsOptions, type MerchantOrder, type OAuthToken, type Order, type OrderItem, type OrderStatus, type ParsedWebhookEvent, type Payment, type PaymentMethod, type PaymentStatus, type PaymentStatusExplanation, type PaymentsSearchResult, type PointDevice, type PointPaymentIntent, type PointPaymentIntentState, type Pos, type Preapproval, type PreapprovalStatus, type Preference, type PreferenceItem, type QrOrder, type Refund, type SearchPaymentsParams, type Settlement, type SiteId, type Store, type SubscriptionPayment, type SubscriptionPlan, SubscriptionStateAdapter, TEST_CARDS_AR, TEST_PAYERS_AR, type TestCard, type ThreeDSInfo, type ThreeDSStatus, type WebhookBody, type WebhookConfig, type WebhookTopic, analyze3DS, buildAuthorizeUrl, buildTestCardScenario, classifyError, computeMarketplaceFee, exchangeCodeForToken, expirationTimeMs, explainPaymentStatus, isExpiringSoon, mercadoPagoTools, parseWebhookEvent, refreshAccessToken, verifyWebhookSignature };
|
|
3096
|
+
export { AHORA_PROGRAM_PROMOS, AR_ISSUER_PROMOS, type AccountBalance, type AccountInfo, type AccountMovement, AuditLogger, AuditOperation, type AutoRecurring, type BankAccount, type CardToken, CircuitBreaker, type CircuitBreakerOptions, CircuitOpenError, type CircuitState, type CreateCardTokenParams, type CreateCustomerParams, type CreateOrderParams, type CreatePaymentParams, type CreatePointPaymentIntentParams, type CreatePosParams, type CreatePreapprovalParams, type CreatePreferenceParams, type CreateQrPaymentParams, type CreateRefundParams, type CreateStoreParams, type CreateSubscriptionPlanParams, type CreateWebhookParams, type CuotasPromo, type CurrencyId, type Customer, type CustomerCard, type DedupResult, type Dispute, type FrequencyType, IdempotencyCache, type IdentificationType, type InstallmentOffer, type Issuer, type MarketplaceFeeRule, type MarketplaceParams, MercadoPagoAccountTypeMismatchError, MercadoPagoAuthError, MercadoPagoAuthorizeForbiddenError, MercadoPagoBackUrlInvalidError, MercadoPagoClient, type MercadoPagoClientOptions, MercadoPagoError, MercadoPagoOverloadedError, MercadoPagoPaymentRejectedError, MercadoPagoRateLimitError, MercadoPagoSelfPaymentError, MercadoPagoTimeoutError, type MercadoPagoToolsOptions, type MerchantOrder, type MetricsHook, type OAuthToken, type Order, type OrderItem, type OrderStatus, type PaginateOptions, type ParsedWebhookEvent, type Payment, type PaymentMethod, type PaymentStatus, type PaymentStatusExplanation, type PaymentsSearchResult, type PointDevice, type PointPaymentIntent, type PointPaymentIntentState, type Pos, type Preapproval, type PreapprovalStatus, type Preference, type PreferenceItem, type QrOrder, RateLimitTimeoutError, type RateLimiterOptions, type Refund, type RetryOptions, type SearchPaymentsParams, type Settlement, type SiteId, type Store, type SubscriptionPayment, type SubscriptionPlan, SubscriptionStateAdapter, TEST_CARDS_AR, TEST_PAYERS_AR, type TaxIdCountry, type TaxIdType, type TaxIdValidationResult, type TestCard, type ThreeDSInfo, type ThreeDSStatus, TokenBucketRateLimiter, type ToolMiddleware, type WebhookBody, type WebhookConfig, WebhookDedup, type WebhookDedupOptions, type WebhookTopic, analyze3DS, applyToAllTools, buildAuthorizeUrl, buildTestCardScenario, classifyError, collect, compose, computeMarketplaceFee, confirmChallengeAndPoll, detectAndValidate, exchangeCodeForToken, expirationTimeMs, explainPaymentStatus, findApplicablePromos, isExpiringSoon, mercadoPagoTools, paginate, paginateAccountMovements, paginateMerchantOrders, paginatePayments, paginateSettlements, paginateSubscriptionPayments, paginateSubscriptionPlans, paginateSubscriptions, parseWebhookEvent, refreshAccessToken, validateTaxId, verifyWebhookSignature, withAuditLog, withMetrics, withRateLimit, withRetry };
|