@garuhq/node 0.1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/http.ts","../src/errors.ts","../src/idempotency.ts","../src/types.ts","../src/resources/charges.ts","../src/resources/meta.ts","../src/webhooks.ts","../src/client.ts"],"names":[],"mappings":";AAAA,OAAO,kBAAkB;;;ACmBlB,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnB;AAAA,EAEhB,YAAY,MAAqB,SAAiB;AAChD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,sBAAN,cAAkC,UAAU;AAAA,EACjC;AAAA,EAChB,YAAY,SAAiB,iBAA2B;AACtD,UAAM,oBAAoB,OAAO;AACjC,SAAK,OAAO;AACZ,SAAK,kBAAkB;AAAA,EACzB;AACF;AAEO,IAAM,iCAAN,cAA6C,UAAU;AAAA,EAC5D,YAAY,SAAiB;AAC3B,UAAM,iCAAiC,OAAO;AAC9C,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,eAAN,cAA2B,UAAU;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EAEhB,YACE,MACA,SACA,QACA,WACA,MACA;AACA,UAAM,MAAM,OAAO;AACnB,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,YAAY;AACjB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,0BAAN,cAAsC,aAAa;AAAA,EACxD,YAAY,SAAiB,QAAgB,WAA0B,MAAe;AACpF,UAAM,wBAAwB,SAAS,QAAQ,WAAW,IAAI;AAC9D,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,sBAAN,cAAkC,aAAa;AAAA,EACpD,YAAY,SAAiB,QAAgB,WAA0B,MAAe;AACpF,UAAM,oBAAoB,SAAS,QAAQ,WAAW,IAAI;AAC1D,SAAK,OAAO;AAAA,EACd;AACF;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AAK,MAAM,GAAG,GAAG,EAAE,KAAK;AACpC,UAAM,QAAQ,KAAK,MAAM,MAAM,CAAC,EAAE,KAAK;AACvC,QAAI,CAAC,OAAO,CAAC;AAAO,aAAO;AAC3B,WAAO,GAAG,IAAI;AAAA,EAChB;AACA,QAAM,IAAI,OAAO;AACjB,QAAM,KAAK,OAAO;AAClB,MAAI,CAAC,KAAK,CAAC;AAAI,WAAO;AACtB,QAAM,YAAY,OAAO,CAAC;AAC1B,MAAI,CAAC,OAAO,SAAS,SAAS,KAAK,CAAC,eAAe,KAAK,EAAE;AAAG,WAAO;AACpE,SAAO,EAAE,WAAW,GAAG;AACzB;;;ACvFA,IAAM,mBAAmB;AACzB,IAAM,qBAAqB;AAC3B,IAAM,sBAAsB;AAC5B,IAAM,cAAc;AAqBb,IAAM,OAAN,MAAW;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMhB,OAAuB,WAAW;AAAA,EAClB,WAAW;AAAA,EAE3B,YAAY,UAAuB,CAAC,GAAG;AACrC,UAAM,OAAO,IAAI,WAAW;AAAA,MAC1B,SAAS,QAAQ,WAAW;AAAA,MAC5B,QAAQ,QAAQ;AAAA,MAChB,WAAW,QAAQ,aAAa;AAAA,MAChC,YAAY,QAAQ,cAAc;AAAA,MAClC,WAAW,aAAa,WAAW;AAAA,MACnC,OAAO,QAAQ;AAAA,IACjB,CAAC;AACD,SAAK,UAAU,IAAI,QAAQ,IAAI;AAC/B,SAAK,OAAO,IAAI,KAAK,IAAI;AAAA,EAC3B;AACF","sourcesContent":["import createClient from 'openapi-fetch';\n\nimport { GaruConnectionError, mapApiError, type GaruAPIError } from './errors.js';\nimport type { paths } from './generated/schema.js';\n\nexport interface HttpClientConfig {\n baseUrl: string;\n apiKey?: string;\n timeoutMs: number;\n maxRetries: number;\n userAgent: string;\n /** Injectable for tests. Defaults to `globalThis.fetch`. */\n fetch?: typeof fetch;\n}\n\nconst RETRYABLE_STATUSES = new Set([408, 429, 500, 502, 503, 504]);\n\n/** Typed openapi-fetch client keyed to the backend's OpenAPI paths. */\nexport type GaruOpenapiClient = ReturnType<typeof createClient<paths>>;\n\n/** Arg type for `HttpClient.call` — a thunk that issues one openapi-fetch request. */\nexport type OpenapiCallResult<T> = Promise<{\n data?: T;\n error?: unknown;\n response: Response;\n}>;\n\n/**\n * HttpClient wraps the generated `openapi-fetch` client with:\n * - retries (exponential backoff, full jitter, honors `Retry-After`)\n * - typed error mapping (non-2xx → {@link GaruAPIError} subclass)\n * - connection error wrapping\n * - Authorization + User-Agent injection\n *\n * Resources call {@link call} with a thunk that returns an openapi-fetch\n * `{ data, error, response }` tuple; the wrapper either returns `data` or\n * throws the mapped error.\n */\nexport class HttpClient {\n public readonly client: GaruOpenapiClient;\n private readonly cfg: HttpClientConfig;\n\n constructor(cfg: HttpClientConfig) {\n this.cfg = cfg;\n const fetchImpl = cfg.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new GaruConnectionError(\n 'No fetch implementation available. Node.js >= 18 is required.'\n );\n }\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'User-Agent': cfg.userAgent\n };\n if (cfg.apiKey) headers.Authorization = `Bearer ${cfg.apiKey}`;\n\n this.client = createClient<paths>({\n baseUrl: cfg.baseUrl.replace(/\\/+$/, ''),\n fetch: fetchImpl,\n headers\n });\n }\n\n /**\n * Issue one HTTP call against the typed client, with retries + error mapping.\n *\n * `fn` is invoked up to `maxRetries + 1` times. The timeout in `cfg.timeoutMs`\n * is enforced via `AbortController`.\n */\n async call<T>(fn: (signal: AbortSignal) => OpenapiCallResult<T>): Promise<T> {\n let lastError: GaruAPIError | GaruConnectionError | null = null;\n\n for (let attempt = 0; attempt <= this.cfg.maxRetries; attempt++) {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.cfg.timeoutMs);\n\n try {\n const { data, error, response } = await fn(controller.signal);\n clearTimeout(timer);\n\n if (response.ok) {\n return data as T;\n }\n\n const requestId = response.headers.get('x-request-id');\n const retryAfterSec = parseRetryAfter(response.headers.get('retry-after'));\n const apiError = mapApiError(response.status, error ?? null, requestId, retryAfterSec);\n lastError = apiError;\n\n if (!RETRYABLE_STATUSES.has(response.status) || attempt === this.cfg.maxRetries) {\n throw apiError;\n }\n\n await sleep(backoffDelay(attempt, retryAfterSec));\n continue;\n } catch (err) {\n clearTimeout(timer);\n\n if (isGaruApiError(err)) throw err;\n\n const connErr =\n err instanceof Error && err.name === 'AbortError'\n ? new GaruConnectionError(`Request timed out after ${this.cfg.timeoutMs}ms`, err)\n : new GaruConnectionError(err instanceof Error ? err.message : 'Network error', err);\n lastError = connErr;\n\n if (attempt === this.cfg.maxRetries) throw connErr;\n await sleep(backoffDelay(attempt, null));\n continue;\n }\n }\n\n // Unreachable — the loop always throws or returns on the final attempt.\n throw lastError ?? new GaruConnectionError('Request failed with no error captured');\n }\n}\n\nfunction isGaruApiError(err: unknown): boolean {\n return err instanceof Error && err.name.startsWith('Garu') && err.name.endsWith('Error');\n}\n\nfunction parseRetryAfter(value: string | null): number | null {\n if (!value) return null;\n const n = Number(value);\n return Number.isFinite(n) && n >= 0 ? n : null;\n}\n\n/**\n * Exponential backoff with full jitter. If the server returned `Retry-After`,\n * we honor it (with a small jitter).\n */\nfunction backoffDelay(attempt: number, retryAfterSec: number | null): number {\n if (retryAfterSec !== null) {\n return retryAfterSec * 1000 + Math.random() * 250;\n }\n const base = 500 * 2 ** attempt;\n const cap = 8000;\n return Math.min(cap, base) * Math.random();\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * Error hierarchy for the Garu SDK.\n *\n * Every error has a stable `code` string so agents and typed clients can switch on it\n * without parsing messages. Non-2xx API responses are mapped to the most specific\n * subclass of `GaruAPIError` by {@link mapApiError}.\n */\n\nexport type GaruErrorCode =\n | 'authentication_error'\n | 'permission_error'\n | 'not_found'\n | 'validation_error'\n | 'rate_limited'\n | 'server_error'\n | 'api_error'\n | 'connection_error'\n | 'signature_verification_failed';\n\nexport class GaruError extends Error {\n public readonly code: GaruErrorCode;\n\n constructor(code: GaruErrorCode, message: string) {\n super(message);\n this.name = 'GaruError';\n this.code = code;\n }\n}\n\nexport class GaruConnectionError extends GaruError {\n public readonly connectionCause: unknown;\n constructor(message: string, connectionCause?: unknown) {\n super('connection_error', message);\n this.name = 'GaruConnectionError';\n this.connectionCause = connectionCause;\n }\n}\n\nexport class GaruSignatureVerificationError extends GaruError {\n constructor(message: string) {\n super('signature_verification_failed', message);\n this.name = 'GaruSignatureVerificationError';\n }\n}\n\nexport class GaruAPIError extends GaruError {\n public readonly status: number;\n public readonly requestId: string | null;\n public readonly body: unknown;\n\n constructor(\n code: GaruErrorCode,\n message: string,\n status: number,\n requestId: string | null,\n body: unknown\n ) {\n super(code, message);\n this.name = 'GaruAPIError';\n this.status = status;\n this.requestId = requestId;\n this.body = body;\n }\n}\n\nexport class GaruAuthenticationError extends GaruAPIError {\n constructor(message: string, status: number, requestId: string | null, body: unknown) {\n super('authentication_error', message, status, requestId, body);\n this.name = 'GaruAuthenticationError';\n }\n}\n\nexport class GaruPermissionError extends GaruAPIError {\n constructor(message: string, status: number, requestId: string | null, body: unknown) {\n super('permission_error', message, status, requestId, body);\n this.name = 'GaruPermissionError';\n }\n}\n\nexport class GaruNotFoundError extends GaruAPIError {\n constructor(message: string, status: number, requestId: string | null, body: unknown) {\n super('not_found', message, status, requestId, body);\n this.name = 'GaruNotFoundError';\n }\n}\n\nexport class GaruValidationError extends GaruAPIError {\n constructor(message: string, status: number, requestId: string | null, body: unknown) {\n super('validation_error', message, status, requestId, body);\n this.name = 'GaruValidationError';\n }\n}\n\nexport class GaruRateLimitError extends GaruAPIError {\n public readonly retryAfterSec: number | null;\n constructor(\n message: string,\n status: number,\n requestId: string | null,\n body: unknown,\n retryAfterSec: number | null\n ) {\n super('rate_limited', message, status, requestId, body);\n this.name = 'GaruRateLimitError';\n this.retryAfterSec = retryAfterSec;\n }\n}\n\nexport class GaruServerError extends GaruAPIError {\n constructor(message: string, status: number, requestId: string | null, body: unknown) {\n super('server_error', message, status, requestId, body);\n this.name = 'GaruServerError';\n }\n}\n\n/**\n * Map a non-2xx HTTP response to the most specific {@link GaruAPIError} subclass.\n */\nexport function mapApiError(\n status: number,\n body: unknown,\n requestId: string | null,\n retryAfterSec: number | null\n): GaruAPIError {\n const message = extractMessage(body) ?? `Garu API returned HTTP ${status}`;\n\n if (status === 401) return new GaruAuthenticationError(message, status, requestId, body);\n if (status === 403) return new GaruPermissionError(message, status, requestId, body);\n if (status === 404) return new GaruNotFoundError(message, status, requestId, body);\n if (status === 400 || status === 422) {\n return new GaruValidationError(message, status, requestId, body);\n }\n if (status === 429) {\n return new GaruRateLimitError(message, status, requestId, body, retryAfterSec);\n }\n if (status >= 500) return new GaruServerError(message, status, requestId, body);\n return new GaruAPIError('api_error', message, status, requestId, body);\n}\n\nfunction extractMessage(body: unknown): string | null {\n if (typeof body === 'string') return body;\n if (body && typeof body === 'object') {\n const m = (body as { message?: unknown }).message;\n if (typeof m === 'string') return m;\n if (Array.isArray(m) && m.every((x) => typeof x === 'string')) return m.join('; ');\n }\n return null;\n}\n","import { randomUUID } from 'node:crypto';\n\n/**\n * Generate a UUIDv4 suitable for use as an `X-Idempotency-Key` header value.\n *\n * @example\n * const key = generateIdempotencyKey();\n * // '3b241101-e2bb-4255-8caf-4136c566a962'\n */\nexport function generateIdempotencyKey(): string {\n return randomUUID();\n}\n","/**\n * Public types for the Garu SDK.\n *\n * The wire-level types (`WireCreateTransactionRequest`, `WireMetaResponse`, ...)\n * are generated from the backend's OpenAPI spec and live in\n * `src/generated/schema.d.ts`. The friendly types in this file\n * (`CreateChargeParams`, `Customer`, `Charge`, ...) are hand-curated for\n * ergonomics — they rename `transactions` to `charges`, collapse wire enums\n * into readable unions, and mark only truly required fields as required.\n * The resource layer maps friendly → wire at the edge.\n */\n\nimport type { components } from './generated/schema.js';\n\nexport type WireCreateTransactionRequest = components['schemas']['CreateTransactionRequest'];\nexport type WireCustomerDto = components['schemas']['CustomerDto'];\nexport type WireCardInfoDto = components['schemas']['CardInfoDto'];\nexport type WireMetaResponse = components['schemas']['MetaResponse'];\n\nexport type PaymentMethod = 'pix' | 'credit_card' | 'boleto';\n\n/** Payment-method identifier as sent to the backend over the wire. */\nexport type WirePaymentMethodId = 'pix' | 'creditcard' | 'boleto';\n\nexport type ChargeStatus =\n | 'pending'\n | 'authorized'\n | 'paid'\n | 'failed'\n | 'refunded'\n | 'cancelled'\n | 'expired';\n\nexport interface Customer {\n /** Full legal name. 3–255 chars. */\n name: string;\n email: string;\n /** CPF (11 digits) or CNPJ (14 digits), digits only. */\n document: string;\n /** 10 or 11 digits with area code, no formatting. */\n phone: string;\n /** 8 digits, no hyphen. Optional. */\n zipCode?: string;\n street?: string;\n number?: string;\n complement?: string;\n neighborhood?: string;\n city?: string;\n /** 2-letter uppercase state code, e.g. `SP`. */\n state?: string;\n}\n\nexport interface CardInfo {\n /** 13–19 digits, no spaces or hyphens. */\n cardNumber: string;\n /** 3 or 4 digits. */\n cvv: string;\n /** `YYYY-MM`. */\n expirationDate: string;\n /** As printed on the card. */\n holderName: string;\n /** 1–12. */\n installments: number;\n}\n\nexport interface CreateChargeParams {\n /** Customer buying the product. */\n customer: Customer;\n /** UUID of the product being charged. */\n productId: string;\n /** Payment method. */\n paymentMethod: PaymentMethod;\n /** Required when `paymentMethod` is `credit_card`. */\n cardInfo?: CardInfo;\n /** Free-form metadata attached to the charge. */\n additionalInfo?: string;\n /** Original checkout link, if any. */\n link?: string | null;\n /** Associated affiliate ID, if any. */\n affiliateId?: number | null;\n /** Subscription price ID (`price_*`), for subscription charges only. */\n priceId?: string | null;\n /** Optional pre-created checkout session token. */\n checkoutSessionToken?: string;\n /**\n * Idempotency key. If omitted, the SDK generates a UUIDv4.\n * Keys are valid for 24h on the backend.\n */\n idempotencyKey?: string;\n}\n\nexport interface Charge {\n id: number;\n status: ChargeStatus;\n amount: number;\n paymentMethodId: WirePaymentMethodId;\n /** ISO-8601. */\n date: string;\n /** ISO-8601. */\n deadline?: string;\n /** Product this charge belongs to. */\n product?: { id: number; uuid?: string; name?: string };\n [key: string]: unknown;\n}\n\nexport interface RefundChargeParams {\n /** Partial refund in centavos. Omit for full refund. */\n amount?: number;\n /** Free-form reason stored on the refund. */\n reason?: string;\n idempotencyKey?: string;\n}\n\nexport interface MetaFeatures {\n subscriptions: boolean;\n checkout_sessions: boolean;\n idempotency_keys: boolean;\n test_mode: boolean;\n webhooks: boolean;\n}\n\nexport interface MetaResponse {\n name: string;\n version: string;\n environment: 'production' | 'staging' | 'development' | string;\n api_version: string;\n payment_methods: string[];\n currencies: string[];\n billing_intervals: string[];\n webhook_events: string[];\n features: MetaFeatures;\n docs_url: string;\n dashboard_url: string;\n support_email: string;\n}\n\n/** Map the SDK's friendly `PaymentMethod` to the backend's wire value. */\nexport function toWirePaymentMethod(pm: PaymentMethod): WirePaymentMethodId {\n return pm === 'credit_card' ? 'creditcard' : pm;\n}\n","import type { HttpClient } from '../http.js';\nimport type { components } from '../generated/schema.js';\nimport { generateIdempotencyKey } from '../idempotency.js';\nimport {\n toWirePaymentMethod,\n type Charge,\n type CreateChargeParams,\n type RefundChargeParams\n} from '../types.js';\n\ntype CreateTransactionBody = components['schemas']['CreateTransactionRequest'];\n\n/**\n * Charges — the core of the Garu API.\n *\n * A charge represents a single payment attempt against a product. The SDK\n * surfaces charges under `garu.charges` even though the backend route is\n * `/api/transactions` — this matches Stripe convention and is the name every\n * other Garu surface (MCP, CLI, docs) uses.\n */\nexport class Charges {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Create a charge (PIX, credit card, or boleto).\n *\n * Automatically attaches an `X-Idempotency-Key` header — if you don't pass\n * `idempotencyKey`, the SDK generates a UUIDv4. Safe to retry: the backend\n * caches the first response for 24h.\n *\n * @example\n * // PIX charge\n * const charge = await garu.charges.create({\n * productId: 'b3f2c1e8-6e4a-4b9f-9d1c-2a1f6c3d4e5f',\n * paymentMethod: 'pix',\n * customer: {\n * name: 'Maria Silva',\n * email: 'maria@exemplo.com.br',\n * document: '12345678909',\n * phone: '11987654321'\n * }\n * });\n * console.log(charge.id, charge.status);\n *\n * @example\n * // Credit card charge, 3 installments\n * const charge = await garu.charges.create({\n * productId: 'b3f2c1e8-6e4a-4b9f-9d1c-2a1f6c3d4e5f',\n * paymentMethod: 'credit_card',\n * customer: { name: 'Maria Silva', email: 'maria@exemplo.com.br', document: '12345678909', phone: '11987654321' },\n * cardInfo: {\n * cardNumber: '4111111111111111',\n * cvv: '123',\n * expirationDate: '2030-12',\n * holderName: 'MARIA SILVA',\n * installments: 3\n * }\n * });\n */\n async create(params: CreateChargeParams): Promise<Charge> {\n const idempotencyKey = params.idempotencyKey ?? generateIdempotencyKey();\n const body = this.buildCreateBody(params);\n\n return this.http.call<Charge>(\n (signal) =>\n this.http.client.POST('/api/transactions', {\n body,\n headers: { 'X-Idempotency-Key': idempotencyKey },\n signal\n }) as Promise<{ data?: Charge; error?: unknown; response: Response }>\n );\n }\n\n /**\n * Fetch a single charge by numeric ID.\n *\n * @example\n * const charge = await garu.charges.get(4472);\n * if (charge.status === 'paid') { ... }\n */\n async get(id: number): Promise<Charge> {\n return this.http.call<Charge>(\n (signal) =>\n this.http.client.GET('/api/transactions/{id}', {\n params: { path: { id } },\n signal\n }) as Promise<{ data?: Charge; error?: unknown; response: Response }>\n );\n }\n\n /**\n * Refund a charge — fully, or partially by passing `amount` in centavos.\n *\n * @example\n * // Full refund\n * await garu.charges.refund(4472);\n *\n * @example\n * // Partial refund of R$ 10,00\n * await garu.charges.refund(4472, { amount: 1000, reason: 'customer_request' });\n */\n async refund(id: number, params: RefundChargeParams = {}): Promise<Charge> {\n const idempotencyKey = params.idempotencyKey ?? generateIdempotencyKey();\n const body: Record<string, unknown> = {};\n if (params.amount !== undefined) body.amount = params.amount;\n if (params.reason !== undefined) body.reason = params.reason;\n\n return this.http.call<Charge>(\n (signal) =>\n this.http.client.POST('/api/transactions/{id}/refund', {\n params: { path: { id } },\n body: body as never,\n headers: { 'X-Idempotency-Key': idempotencyKey },\n signal\n }) as Promise<{ data?: Charge; error?: unknown; response: Response }>\n );\n }\n\n private buildCreateBody(params: CreateChargeParams): CreateTransactionBody {\n const body: Record<string, unknown> = {\n customer: params.customer,\n productId: params.productId,\n paymentMethodId: toWirePaymentMethod(params.paymentMethod),\n link: params.link ?? null,\n affiliateId: params.affiliateId ?? null\n };\n if (params.additionalInfo !== undefined) body.additionalInfo = params.additionalInfo;\n if (params.priceId !== undefined) body.priceId = params.priceId;\n if (params.checkoutSessionToken !== undefined) {\n body.checkoutSessionToken = params.checkoutSessionToken;\n }\n if (params.cardInfo) body.CardInfo = params.cardInfo;\n return body as unknown as CreateTransactionBody;\n }\n}\n","import type { HttpClient } from '../http.js';\nimport type { MetaResponse } from '../types.js';\n\n/**\n * Meta — capability introspection.\n *\n * Unauthenticated. Used by `garu doctor`, MCP tool `doctor`, and by SDK\n * consumers that want to know which payment methods and webhook events are\n * currently supported.\n */\nexport class Meta {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Fetch the API's current capability payload.\n *\n * @example\n * const meta = await garu.meta.get();\n * console.log(meta.version, meta.payment_methods);\n * if (meta.features.subscriptions) { ... }\n */\n async get(): Promise<MetaResponse> {\n return this.http.call<MetaResponse>(\n (signal) =>\n this.http.client.GET('/api/meta', { signal }) as Promise<{\n data?: MetaResponse;\n error?: unknown;\n response: Response;\n }>\n );\n }\n}\n","import { createHmac, timingSafeEqual } from 'node:crypto';\n\nimport { GaruSignatureVerificationError } from './errors.js';\n\nexport interface VerifyWebhookParams {\n /** Raw request body as received — do NOT re-serialize parsed JSON. */\n payload: string | Buffer;\n /** Value of the `X-Garu-Signature` header. Format: `t=<ts>,v1=<hex>`. */\n signature: string;\n /** The webhook endpoint's signing secret. */\n secret: string;\n /** Reject signatures older than this many seconds. Default: 300 (5 min). */\n toleranceSec?: number;\n /** Injectable for tests. Defaults to `Date.now()`. */\n now?: () => number;\n}\n\nexport interface VerifiedWebhook {\n /** Timestamp from the signature header, in seconds since epoch. */\n timestamp: number;\n /** Parsed JSON body. Throws {@link GaruSignatureVerificationError} if invalid JSON. */\n event: unknown;\n}\n\n/**\n * Webhook helpers.\n *\n * Garu signs outgoing webhooks with HMAC-SHA256 over `${timestamp}.${payload}`\n * and delivers the signature in the `X-Garu-Signature` header as `t=<ts>,v1=<hex>`.\n * This matches the format in the backend's `webhook-delivery.service.ts`.\n *\n * @example\n * // Express example\n * app.post('/webhooks/garu', express.raw({ type: 'application/json' }), (req, res) => {\n * try {\n * const { event } = Garu.webhooks.verify({\n * payload: req.body,\n * signature: req.header('x-garu-signature') ?? '',\n * secret: process.env.GARU_WEBHOOK_SECRET!\n * });\n * // handle event\n * res.sendStatus(200);\n * } catch (err) {\n * res.sendStatus(400);\n * }\n * });\n */\nexport const webhooks = {\n verify(params: VerifyWebhookParams): VerifiedWebhook {\n const { signature, secret, payload } = params;\n const toleranceSec = params.toleranceSec ?? 300;\n const now = params.now ?? Date.now;\n\n if (!signature || typeof signature !== 'string') {\n throw new GaruSignatureVerificationError('Missing or malformed X-Garu-Signature header');\n }\n\n const parts = parseSignatureHeader(signature);\n if (parts === null) {\n throw new GaruSignatureVerificationError(\n 'X-Garu-Signature header does not match expected format t=<ts>,v1=<hex>'\n );\n }\n\n const payloadStr = typeof payload === 'string' ? payload : payload.toString('utf8');\n const signedPayload = `${parts.timestamp}.${payloadStr}`;\n const expected = createHmac('sha256', secret).update(signedPayload).digest('hex');\n\n const expectedBuf = Buffer.from(expected, 'hex');\n const providedBuf = Buffer.from(parts.v1, 'hex');\n if (expectedBuf.length !== providedBuf.length || !timingSafeEqual(expectedBuf, providedBuf)) {\n throw new GaruSignatureVerificationError('Signature does not match computed HMAC');\n }\n\n const nowSec = Math.floor(now() / 1000);\n if (Math.abs(nowSec - parts.timestamp) > toleranceSec) {\n throw new GaruSignatureVerificationError(\n `Signature timestamp outside tolerance window (${toleranceSec}s)`\n );\n }\n\n let event: unknown;\n try {\n event = JSON.parse(payloadStr);\n } catch {\n throw new GaruSignatureVerificationError('Webhook payload is not valid JSON');\n }\n\n return { timestamp: parts.timestamp, event };\n }\n};\n\nfunction parseSignatureHeader(header: string): { timestamp: number; v1: string } | null {\n const fields: Record<string, string> = {};\n for (const part of header.split(',')) {\n const idx = part.indexOf('=');\n if (idx === -1) return null;\n const key = part.slice(0, idx).trim();\n const value = part.slice(idx + 1).trim();\n if (!key || !value) return null;\n fields[key] = value;\n }\n const t = fields.t;\n const v1 = fields.v1;\n if (!t || !v1) return null;\n const timestamp = Number(t);\n if (!Number.isFinite(timestamp) || !/^[a-f0-9]+$/i.test(v1)) return null;\n return { timestamp, v1 };\n}\n","import { HttpClient } from './http.js';\nimport { Charges } from './resources/charges.js';\nimport { Meta } from './resources/meta.js';\nimport { webhooks } from './webhooks.js';\n\nexport interface GaruOptions {\n /**\n * Your Garu API key. `sk_live_…` for production, `sk_test_…` for test mode.\n * Optional — public endpoints (`meta.get`, public charge creation) work without one.\n */\n apiKey?: string;\n /** Override the API base URL. Default: `https://garu.com.br/api`. */\n baseUrl?: string;\n /** Per-request timeout in ms. Default: 30000. */\n timeoutMs?: number;\n /** Max retries on retryable errors (connection, 408, 429, 5xx). Default: 2. */\n maxRetries?: number;\n /** Injectable for tests. Defaults to `globalThis.fetch`. */\n fetch?: typeof fetch;\n}\n\nconst DEFAULT_BASE_URL = 'https://garu.com.br';\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_MAX_RETRIES = 2;\nconst SDK_VERSION = '0.1.0';\n\n/**\n * The Garu SDK client.\n *\n * @example\n * import { Garu } from '@garuhq/node';\n *\n * const garu = new Garu({ apiKey: process.env.GARU_API_KEY });\n *\n * const charge = await garu.charges.create({\n * productId: 'b3f2c1e8-6e4a-4b9f-9d1c-2a1f6c3d4e5f',\n * paymentMethod: 'pix',\n * customer: {\n * name: 'Maria Silva',\n * email: 'maria@exemplo.com.br',\n * document: '12345678909',\n * phone: '11987654321'\n * }\n * });\n */\nexport class Garu {\n public readonly charges: Charges;\n public readonly meta: Meta;\n\n /**\n * Webhook helpers. Available both as an instance member and as a static —\n * `Garu.webhooks.verify(...)` works without constructing a client.\n */\n public static readonly webhooks = webhooks;\n public readonly webhooks = webhooks;\n\n constructor(options: GaruOptions = {}) {\n const http = new HttpClient({\n baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,\n apiKey: options.apiKey,\n timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES,\n userAgent: `garu-node/${SDK_VERSION}`,\n fetch: options.fetch\n });\n this.charges = new Charges(http);\n this.meta = new Meta(http);\n }\n}\n"]}
@@ -0,0 +1,393 @@
1
+ import createClient from 'openapi-fetch';
2
+
3
+ interface VerifyWebhookParams {
4
+ /** Raw request body as received — do NOT re-serialize parsed JSON. */
5
+ payload: string | Buffer;
6
+ /** Value of the `X-Garu-Signature` header. Format: `t=<ts>,v1=<hex>`. */
7
+ signature: string;
8
+ /** The webhook endpoint's signing secret. */
9
+ secret: string;
10
+ /** Reject signatures older than this many seconds. Default: 300 (5 min). */
11
+ toleranceSec?: number;
12
+ /** Injectable for tests. Defaults to `Date.now()`. */
13
+ now?: () => number;
14
+ }
15
+ interface VerifiedWebhook {
16
+ /** Timestamp from the signature header, in seconds since epoch. */
17
+ timestamp: number;
18
+ /** Parsed JSON body. Throws {@link GaruSignatureVerificationError} if invalid JSON. */
19
+ event: unknown;
20
+ }
21
+ /**
22
+ * Webhook helpers.
23
+ *
24
+ * Garu signs outgoing webhooks with HMAC-SHA256 over `${timestamp}.${payload}`
25
+ * and delivers the signature in the `X-Garu-Signature` header as `t=<ts>,v1=<hex>`.
26
+ * This matches the format in the backend's `webhook-delivery.service.ts`.
27
+ *
28
+ * @example
29
+ * // Express example
30
+ * app.post('/webhooks/garu', express.raw({ type: 'application/json' }), (req, res) => {
31
+ * try {
32
+ * const { event } = Garu.webhooks.verify({
33
+ * payload: req.body,
34
+ * signature: req.header('x-garu-signature') ?? '',
35
+ * secret: process.env.GARU_WEBHOOK_SECRET!
36
+ * });
37
+ * // handle event
38
+ * res.sendStatus(200);
39
+ * } catch (err) {
40
+ * res.sendStatus(400);
41
+ * }
42
+ * });
43
+ */
44
+ declare const webhooks: {
45
+ verify(params: VerifyWebhookParams): VerifiedWebhook;
46
+ };
47
+
48
+ interface HttpClientConfig {
49
+ baseUrl: string;
50
+ apiKey?: string;
51
+ timeoutMs: number;
52
+ maxRetries: number;
53
+ userAgent: string;
54
+ /** Injectable for tests. Defaults to `globalThis.fetch`. */
55
+ fetch?: typeof fetch;
56
+ }
57
+ /** Typed openapi-fetch client keyed to the backend's OpenAPI paths. */
58
+ type GaruOpenapiClient = ReturnType<typeof createClient<paths>>;
59
+ /** Arg type for `HttpClient.call` — a thunk that issues one openapi-fetch request. */
60
+ type OpenapiCallResult<T> = Promise<{
61
+ data?: T;
62
+ error?: unknown;
63
+ response: Response;
64
+ }>;
65
+ /**
66
+ * HttpClient wraps the generated `openapi-fetch` client with:
67
+ * - retries (exponential backoff, full jitter, honors `Retry-After`)
68
+ * - typed error mapping (non-2xx → {@link GaruAPIError} subclass)
69
+ * - connection error wrapping
70
+ * - Authorization + User-Agent injection
71
+ *
72
+ * Resources call {@link call} with a thunk that returns an openapi-fetch
73
+ * `{ data, error, response }` tuple; the wrapper either returns `data` or
74
+ * throws the mapped error.
75
+ */
76
+ declare class HttpClient {
77
+ readonly client: GaruOpenapiClient;
78
+ private readonly cfg;
79
+ constructor(cfg: HttpClientConfig);
80
+ /**
81
+ * Issue one HTTP call against the typed client, with retries + error mapping.
82
+ *
83
+ * `fn` is invoked up to `maxRetries + 1` times. The timeout in `cfg.timeoutMs`
84
+ * is enforced via `AbortController`.
85
+ */
86
+ call<T>(fn: (signal: AbortSignal) => OpenapiCallResult<T>): Promise<T>;
87
+ }
88
+
89
+ /**
90
+ * Public types for the Garu SDK.
91
+ *
92
+ * The wire-level types (`WireCreateTransactionRequest`, `WireMetaResponse`, ...)
93
+ * are generated from the backend's OpenAPI spec and live in
94
+ * `src/generated/schema.d.ts`. The friendly types in this file
95
+ * (`CreateChargeParams`, `Customer`, `Charge`, ...) are hand-curated for
96
+ * ergonomics — they rename `transactions` to `charges`, collapse wire enums
97
+ * into readable unions, and mark only truly required fields as required.
98
+ * The resource layer maps friendly → wire at the edge.
99
+ */
100
+
101
+ type PaymentMethod = 'pix' | 'credit_card' | 'boleto';
102
+ /** Payment-method identifier as sent to the backend over the wire. */
103
+ type WirePaymentMethodId = 'pix' | 'creditcard' | 'boleto';
104
+ type ChargeStatus = 'pending' | 'authorized' | 'paid' | 'failed' | 'refunded' | 'cancelled' | 'expired';
105
+ interface Customer {
106
+ /** Full legal name. 3–255 chars. */
107
+ name: string;
108
+ email: string;
109
+ /** CPF (11 digits) or CNPJ (14 digits), digits only. */
110
+ document: string;
111
+ /** 10 or 11 digits with area code, no formatting. */
112
+ phone: string;
113
+ /** 8 digits, no hyphen. Optional. */
114
+ zipCode?: string;
115
+ street?: string;
116
+ number?: string;
117
+ complement?: string;
118
+ neighborhood?: string;
119
+ city?: string;
120
+ /** 2-letter uppercase state code, e.g. `SP`. */
121
+ state?: string;
122
+ }
123
+ interface CardInfo {
124
+ /** 13–19 digits, no spaces or hyphens. */
125
+ cardNumber: string;
126
+ /** 3 or 4 digits. */
127
+ cvv: string;
128
+ /** `YYYY-MM`. */
129
+ expirationDate: string;
130
+ /** As printed on the card. */
131
+ holderName: string;
132
+ /** 1–12. */
133
+ installments: number;
134
+ }
135
+ interface CreateChargeParams {
136
+ /** Customer buying the product. */
137
+ customer: Customer;
138
+ /** UUID of the product being charged. */
139
+ productId: string;
140
+ /** Payment method. */
141
+ paymentMethod: PaymentMethod;
142
+ /** Required when `paymentMethod` is `credit_card`. */
143
+ cardInfo?: CardInfo;
144
+ /** Free-form metadata attached to the charge. */
145
+ additionalInfo?: string;
146
+ /** Original checkout link, if any. */
147
+ link?: string | null;
148
+ /** Associated affiliate ID, if any. */
149
+ affiliateId?: number | null;
150
+ /** Subscription price ID (`price_*`), for subscription charges only. */
151
+ priceId?: string | null;
152
+ /** Optional pre-created checkout session token. */
153
+ checkoutSessionToken?: string;
154
+ /**
155
+ * Idempotency key. If omitted, the SDK generates a UUIDv4.
156
+ * Keys are valid for 24h on the backend.
157
+ */
158
+ idempotencyKey?: string;
159
+ }
160
+ interface Charge {
161
+ id: number;
162
+ status: ChargeStatus;
163
+ amount: number;
164
+ paymentMethodId: WirePaymentMethodId;
165
+ /** ISO-8601. */
166
+ date: string;
167
+ /** ISO-8601. */
168
+ deadline?: string;
169
+ /** Product this charge belongs to. */
170
+ product?: {
171
+ id: number;
172
+ uuid?: string;
173
+ name?: string;
174
+ };
175
+ [key: string]: unknown;
176
+ }
177
+ interface RefundChargeParams {
178
+ /** Partial refund in centavos. Omit for full refund. */
179
+ amount?: number;
180
+ /** Free-form reason stored on the refund. */
181
+ reason?: string;
182
+ idempotencyKey?: string;
183
+ }
184
+ interface MetaFeatures {
185
+ subscriptions: boolean;
186
+ checkout_sessions: boolean;
187
+ idempotency_keys: boolean;
188
+ test_mode: boolean;
189
+ webhooks: boolean;
190
+ }
191
+ interface MetaResponse {
192
+ name: string;
193
+ version: string;
194
+ environment: 'production' | 'staging' | 'development' | string;
195
+ api_version: string;
196
+ payment_methods: string[];
197
+ currencies: string[];
198
+ billing_intervals: string[];
199
+ webhook_events: string[];
200
+ features: MetaFeatures;
201
+ docs_url: string;
202
+ dashboard_url: string;
203
+ support_email: string;
204
+ }
205
+
206
+ /**
207
+ * Charges — the core of the Garu API.
208
+ *
209
+ * A charge represents a single payment attempt against a product. The SDK
210
+ * surfaces charges under `garu.charges` even though the backend route is
211
+ * `/api/transactions` — this matches Stripe convention and is the name every
212
+ * other Garu surface (MCP, CLI, docs) uses.
213
+ */
214
+ declare class Charges {
215
+ private readonly http;
216
+ constructor(http: HttpClient);
217
+ /**
218
+ * Create a charge (PIX, credit card, or boleto).
219
+ *
220
+ * Automatically attaches an `X-Idempotency-Key` header — if you don't pass
221
+ * `idempotencyKey`, the SDK generates a UUIDv4. Safe to retry: the backend
222
+ * caches the first response for 24h.
223
+ *
224
+ * @example
225
+ * // PIX charge
226
+ * const charge = await garu.charges.create({
227
+ * productId: 'b3f2c1e8-6e4a-4b9f-9d1c-2a1f6c3d4e5f',
228
+ * paymentMethod: 'pix',
229
+ * customer: {
230
+ * name: 'Maria Silva',
231
+ * email: 'maria@exemplo.com.br',
232
+ * document: '12345678909',
233
+ * phone: '11987654321'
234
+ * }
235
+ * });
236
+ * console.log(charge.id, charge.status);
237
+ *
238
+ * @example
239
+ * // Credit card charge, 3 installments
240
+ * const charge = await garu.charges.create({
241
+ * productId: 'b3f2c1e8-6e4a-4b9f-9d1c-2a1f6c3d4e5f',
242
+ * paymentMethod: 'credit_card',
243
+ * customer: { name: 'Maria Silva', email: 'maria@exemplo.com.br', document: '12345678909', phone: '11987654321' },
244
+ * cardInfo: {
245
+ * cardNumber: '4111111111111111',
246
+ * cvv: '123',
247
+ * expirationDate: '2030-12',
248
+ * holderName: 'MARIA SILVA',
249
+ * installments: 3
250
+ * }
251
+ * });
252
+ */
253
+ create(params: CreateChargeParams): Promise<Charge>;
254
+ /**
255
+ * Fetch a single charge by numeric ID.
256
+ *
257
+ * @example
258
+ * const charge = await garu.charges.get(4472);
259
+ * if (charge.status === 'paid') { ... }
260
+ */
261
+ get(id: number): Promise<Charge>;
262
+ /**
263
+ * Refund a charge — fully, or partially by passing `amount` in centavos.
264
+ *
265
+ * @example
266
+ * // Full refund
267
+ * await garu.charges.refund(4472);
268
+ *
269
+ * @example
270
+ * // Partial refund of R$ 10,00
271
+ * await garu.charges.refund(4472, { amount: 1000, reason: 'customer_request' });
272
+ */
273
+ refund(id: number, params?: RefundChargeParams): Promise<Charge>;
274
+ private buildCreateBody;
275
+ }
276
+
277
+ /**
278
+ * Meta — capability introspection.
279
+ *
280
+ * Unauthenticated. Used by `garu doctor`, MCP tool `doctor`, and by SDK
281
+ * consumers that want to know which payment methods and webhook events are
282
+ * currently supported.
283
+ */
284
+ declare class Meta {
285
+ private readonly http;
286
+ constructor(http: HttpClient);
287
+ /**
288
+ * Fetch the API's current capability payload.
289
+ *
290
+ * @example
291
+ * const meta = await garu.meta.get();
292
+ * console.log(meta.version, meta.payment_methods);
293
+ * if (meta.features.subscriptions) { ... }
294
+ */
295
+ get(): Promise<MetaResponse>;
296
+ }
297
+
298
+ interface GaruOptions {
299
+ /**
300
+ * Your Garu API key. `sk_live_…` for production, `sk_test_…` for test mode.
301
+ * Optional — public endpoints (`meta.get`, public charge creation) work without one.
302
+ */
303
+ apiKey?: string;
304
+ /** Override the API base URL. Default: `https://garu.com.br/api`. */
305
+ baseUrl?: string;
306
+ /** Per-request timeout in ms. Default: 30000. */
307
+ timeoutMs?: number;
308
+ /** Max retries on retryable errors (connection, 408, 429, 5xx). Default: 2. */
309
+ maxRetries?: number;
310
+ /** Injectable for tests. Defaults to `globalThis.fetch`. */
311
+ fetch?: typeof fetch;
312
+ }
313
+ /**
314
+ * The Garu SDK client.
315
+ *
316
+ * @example
317
+ * import { Garu } from '@garuhq/node';
318
+ *
319
+ * const garu = new Garu({ apiKey: process.env.GARU_API_KEY });
320
+ *
321
+ * const charge = await garu.charges.create({
322
+ * productId: 'b3f2c1e8-6e4a-4b9f-9d1c-2a1f6c3d4e5f',
323
+ * paymentMethod: 'pix',
324
+ * customer: {
325
+ * name: 'Maria Silva',
326
+ * email: 'maria@exemplo.com.br',
327
+ * document: '12345678909',
328
+ * phone: '11987654321'
329
+ * }
330
+ * });
331
+ */
332
+ declare class Garu {
333
+ readonly charges: Charges;
334
+ readonly meta: Meta;
335
+ /**
336
+ * Webhook helpers. Available both as an instance member and as a static —
337
+ * `Garu.webhooks.verify(...)` works without constructing a client.
338
+ */
339
+ static readonly webhooks: {
340
+ verify(params: VerifyWebhookParams): VerifiedWebhook;
341
+ };
342
+ readonly webhooks: {
343
+ verify(params: VerifyWebhookParams): VerifiedWebhook;
344
+ };
345
+ constructor(options?: GaruOptions);
346
+ }
347
+
348
+ /**
349
+ * Error hierarchy for the Garu SDK.
350
+ *
351
+ * Every error has a stable `code` string so agents and typed clients can switch on it
352
+ * without parsing messages. Non-2xx API responses are mapped to the most specific
353
+ * subclass of `GaruAPIError` by {@link mapApiError}.
354
+ */
355
+ type GaruErrorCode = 'authentication_error' | 'permission_error' | 'not_found' | 'validation_error' | 'rate_limited' | 'server_error' | 'api_error' | 'connection_error' | 'signature_verification_failed';
356
+ declare class GaruError extends Error {
357
+ readonly code: GaruErrorCode;
358
+ constructor(code: GaruErrorCode, message: string);
359
+ }
360
+ declare class GaruConnectionError extends GaruError {
361
+ readonly connectionCause: unknown;
362
+ constructor(message: string, connectionCause?: unknown);
363
+ }
364
+ declare class GaruSignatureVerificationError extends GaruError {
365
+ constructor(message: string);
366
+ }
367
+ declare class GaruAPIError extends GaruError {
368
+ readonly status: number;
369
+ readonly requestId: string | null;
370
+ readonly body: unknown;
371
+ constructor(code: GaruErrorCode, message: string, status: number, requestId: string | null, body: unknown);
372
+ }
373
+ declare class GaruAuthenticationError extends GaruAPIError {
374
+ constructor(message: string, status: number, requestId: string | null, body: unknown);
375
+ }
376
+ declare class GaruPermissionError extends GaruAPIError {
377
+ constructor(message: string, status: number, requestId: string | null, body: unknown);
378
+ }
379
+ declare class GaruNotFoundError extends GaruAPIError {
380
+ constructor(message: string, status: number, requestId: string | null, body: unknown);
381
+ }
382
+ declare class GaruValidationError extends GaruAPIError {
383
+ constructor(message: string, status: number, requestId: string | null, body: unknown);
384
+ }
385
+ declare class GaruRateLimitError extends GaruAPIError {
386
+ readonly retryAfterSec: number | null;
387
+ constructor(message: string, status: number, requestId: string | null, body: unknown, retryAfterSec: number | null);
388
+ }
389
+ declare class GaruServerError extends GaruAPIError {
390
+ constructor(message: string, status: number, requestId: string | null, body: unknown);
391
+ }
392
+
393
+ export { type CardInfo, type Charge, type ChargeStatus, type CreateChargeParams, type Customer, Garu, GaruAPIError, GaruAuthenticationError, GaruConnectionError, GaruError, type GaruErrorCode, GaruNotFoundError, type GaruOptions, GaruPermissionError, GaruRateLimitError, GaruServerError, GaruSignatureVerificationError, GaruValidationError, type MetaFeatures, type MetaResponse, type PaymentMethod, type RefundChargeParams, type VerifiedWebhook, type VerifyWebhookParams, type WirePaymentMethodId, webhooks };