@garuhq/node 0.1.0 → 0.1.1
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 +9 -0
- package/dist/index.cjs +23 -41
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +23 -41
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,15 @@
|
|
|
3
3
|
All notable changes to `@garuhq/node` are documented in this file. Format:
|
|
4
4
|
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Versioning: [SemVer](https://semver.org/).
|
|
5
5
|
|
|
6
|
+
## [0.1.1] — 2026-04-08
|
|
7
|
+
|
|
8
|
+
### Security
|
|
9
|
+
|
|
10
|
+
- Upgrade dev dependencies to clear `npm audit` findings:
|
|
11
|
+
- `vitest` 1.5.0 → 4.1.3 (closes critical GHSA — vitest RCE in dev server)
|
|
12
|
+
- `tsup` 8.0.2 → 8.5.1 (closes moderate DOM clobbering advisory)
|
|
13
|
+
- All upgrades are dev-only; no runtime-code changes in `@garuhq/node` itself.
|
|
14
|
+
|
|
6
15
|
## [0.1.0] — 2026-04-08
|
|
7
16
|
|
|
8
17
|
### Added
|
package/dist/index.cjs
CHANGED
|
@@ -84,31 +84,24 @@ var GaruServerError = class extends GaruAPIError {
|
|
|
84
84
|
};
|
|
85
85
|
function mapApiError(status, body, requestId, retryAfterSec) {
|
|
86
86
|
const message = extractMessage(body) ?? `Garu API returned HTTP ${status}`;
|
|
87
|
-
if (status === 401)
|
|
88
|
-
|
|
89
|
-
if (status ===
|
|
90
|
-
return new GaruPermissionError(message, status, requestId, body);
|
|
91
|
-
if (status === 404)
|
|
92
|
-
return new GaruNotFoundError(message, status, requestId, body);
|
|
87
|
+
if (status === 401) return new GaruAuthenticationError(message, status, requestId, body);
|
|
88
|
+
if (status === 403) return new GaruPermissionError(message, status, requestId, body);
|
|
89
|
+
if (status === 404) return new GaruNotFoundError(message, status, requestId, body);
|
|
93
90
|
if (status === 400 || status === 422) {
|
|
94
91
|
return new GaruValidationError(message, status, requestId, body);
|
|
95
92
|
}
|
|
96
93
|
if (status === 429) {
|
|
97
94
|
return new GaruRateLimitError(message, status, requestId, body, retryAfterSec);
|
|
98
95
|
}
|
|
99
|
-
if (status >= 500)
|
|
100
|
-
return new GaruServerError(message, status, requestId, body);
|
|
96
|
+
if (status >= 500) return new GaruServerError(message, status, requestId, body);
|
|
101
97
|
return new GaruAPIError("api_error", message, status, requestId, body);
|
|
102
98
|
}
|
|
103
99
|
function extractMessage(body) {
|
|
104
|
-
if (typeof body === "string")
|
|
105
|
-
return body;
|
|
100
|
+
if (typeof body === "string") return body;
|
|
106
101
|
if (body && typeof body === "object") {
|
|
107
102
|
const m = body.message;
|
|
108
|
-
if (typeof m === "string")
|
|
109
|
-
|
|
110
|
-
if (Array.isArray(m) && m.every((x) => typeof x === "string"))
|
|
111
|
-
return m.join("; ");
|
|
103
|
+
if (typeof m === "string") return m;
|
|
104
|
+
if (Array.isArray(m) && m.every((x) => typeof x === "string")) return m.join("; ");
|
|
112
105
|
}
|
|
113
106
|
return null;
|
|
114
107
|
}
|
|
@@ -130,8 +123,7 @@ var HttpClient = class {
|
|
|
130
123
|
Accept: "application/json",
|
|
131
124
|
"User-Agent": cfg.userAgent
|
|
132
125
|
};
|
|
133
|
-
if (cfg.apiKey)
|
|
134
|
-
headers.Authorization = `Bearer ${cfg.apiKey}`;
|
|
126
|
+
if (cfg.apiKey) headers.Authorization = `Bearer ${cfg.apiKey}`;
|
|
135
127
|
this.client = createClient__default.default({
|
|
136
128
|
baseUrl: cfg.baseUrl.replace(/\/+$/, ""),
|
|
137
129
|
fetch: fetchImpl,
|
|
@@ -166,12 +158,10 @@ var HttpClient = class {
|
|
|
166
158
|
continue;
|
|
167
159
|
} catch (err) {
|
|
168
160
|
clearTimeout(timer);
|
|
169
|
-
if (isGaruApiError(err))
|
|
170
|
-
throw err;
|
|
161
|
+
if (isGaruApiError(err)) throw err;
|
|
171
162
|
const connErr = err instanceof Error && err.name === "AbortError" ? new GaruConnectionError(`Request timed out after ${this.cfg.timeoutMs}ms`, err) : new GaruConnectionError(err instanceof Error ? err.message : "Network error", err);
|
|
172
163
|
lastError = connErr;
|
|
173
|
-
if (attempt === this.cfg.maxRetries)
|
|
174
|
-
throw connErr;
|
|
164
|
+
if (attempt === this.cfg.maxRetries) throw connErr;
|
|
175
165
|
await sleep(backoffDelay(attempt, null));
|
|
176
166
|
continue;
|
|
177
167
|
}
|
|
@@ -183,8 +173,7 @@ function isGaruApiError(err) {
|
|
|
183
173
|
return err instanceof Error && err.name.startsWith("Garu") && err.name.endsWith("Error");
|
|
184
174
|
}
|
|
185
175
|
function parseRetryAfter(value) {
|
|
186
|
-
if (!value)
|
|
187
|
-
return null;
|
|
176
|
+
if (!value) return null;
|
|
188
177
|
const n = Number(value);
|
|
189
178
|
return Number.isFinite(n) && n >= 0 ? n : null;
|
|
190
179
|
}
|
|
@@ -213,6 +202,7 @@ var Charges = class {
|
|
|
213
202
|
constructor(http) {
|
|
214
203
|
this.http = http;
|
|
215
204
|
}
|
|
205
|
+
http;
|
|
216
206
|
/**
|
|
217
207
|
* Create a charge (PIX, credit card, or boleto).
|
|
218
208
|
*
|
|
@@ -289,10 +279,8 @@ var Charges = class {
|
|
|
289
279
|
async refund(id, params = {}) {
|
|
290
280
|
const idempotencyKey = params.idempotencyKey ?? generateIdempotencyKey();
|
|
291
281
|
const body = {};
|
|
292
|
-
if (params.amount !== void 0)
|
|
293
|
-
|
|
294
|
-
if (params.reason !== void 0)
|
|
295
|
-
body.reason = params.reason;
|
|
282
|
+
if (params.amount !== void 0) body.amount = params.amount;
|
|
283
|
+
if (params.reason !== void 0) body.reason = params.reason;
|
|
296
284
|
return this.http.call(
|
|
297
285
|
(signal) => this.http.client.POST("/api/transactions/{id}/refund", {
|
|
298
286
|
params: { path: { id } },
|
|
@@ -310,15 +298,12 @@ var Charges = class {
|
|
|
310
298
|
link: params.link ?? null,
|
|
311
299
|
affiliateId: params.affiliateId ?? null
|
|
312
300
|
};
|
|
313
|
-
if (params.additionalInfo !== void 0)
|
|
314
|
-
|
|
315
|
-
if (params.priceId !== void 0)
|
|
316
|
-
body.priceId = params.priceId;
|
|
301
|
+
if (params.additionalInfo !== void 0) body.additionalInfo = params.additionalInfo;
|
|
302
|
+
if (params.priceId !== void 0) body.priceId = params.priceId;
|
|
317
303
|
if (params.checkoutSessionToken !== void 0) {
|
|
318
304
|
body.checkoutSessionToken = params.checkoutSessionToken;
|
|
319
305
|
}
|
|
320
|
-
if (params.cardInfo)
|
|
321
|
-
body.CardInfo = params.cardInfo;
|
|
306
|
+
if (params.cardInfo) body.CardInfo = params.cardInfo;
|
|
322
307
|
return body;
|
|
323
308
|
}
|
|
324
309
|
};
|
|
@@ -328,6 +313,7 @@ var Meta = class {
|
|
|
328
313
|
constructor(http) {
|
|
329
314
|
this.http = http;
|
|
330
315
|
}
|
|
316
|
+
http;
|
|
331
317
|
/**
|
|
332
318
|
* Fetch the API's current capability payload.
|
|
333
319
|
*
|
|
@@ -383,21 +369,17 @@ function parseSignatureHeader(header) {
|
|
|
383
369
|
const fields = {};
|
|
384
370
|
for (const part of header.split(",")) {
|
|
385
371
|
const idx = part.indexOf("=");
|
|
386
|
-
if (idx === -1)
|
|
387
|
-
return null;
|
|
372
|
+
if (idx === -1) return null;
|
|
388
373
|
const key = part.slice(0, idx).trim();
|
|
389
374
|
const value = part.slice(idx + 1).trim();
|
|
390
|
-
if (!key || !value)
|
|
391
|
-
return null;
|
|
375
|
+
if (!key || !value) return null;
|
|
392
376
|
fields[key] = value;
|
|
393
377
|
}
|
|
394
378
|
const t = fields.t;
|
|
395
379
|
const v1 = fields.v1;
|
|
396
|
-
if (!t || !v1)
|
|
397
|
-
return null;
|
|
380
|
+
if (!t || !v1) return null;
|
|
398
381
|
const timestamp = Number(t);
|
|
399
|
-
if (!Number.isFinite(timestamp) || !/^[a-f0-9]+$/i.test(v1))
|
|
400
|
-
return null;
|
|
382
|
+
if (!Number.isFinite(timestamp) || !/^[a-f0-9]+$/i.test(v1)) return null;
|
|
401
383
|
return { timestamp, v1 };
|
|
402
384
|
}
|
|
403
385
|
|
|
@@ -441,5 +423,5 @@ exports.GaruServerError = GaruServerError;
|
|
|
441
423
|
exports.GaruSignatureVerificationError = GaruSignatureVerificationError;
|
|
442
424
|
exports.GaruValidationError = GaruValidationError;
|
|
443
425
|
exports.webhooks = webhooks;
|
|
444
|
-
//# sourceMappingURL=
|
|
426
|
+
//# sourceMappingURL=index.cjs.map
|
|
445
427
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +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;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/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"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/http.ts","../src/idempotency.ts","../src/types.ts","../src/resources/charges.ts","../src/resources/meta.ts","../src/webhooks.ts","../src/client.ts"],"names":["createClient","randomUUID","createHmac","timingSafeEqual"],"mappings":";;;;;;;;;;;;AAmBO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EACnB,IAAA;AAAA,EAEhB,WAAA,CAAY,MAAqB,OAAA,EAAiB;AAChD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAEO,IAAM,mBAAA,GAAN,cAAkC,SAAA,CAAU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AC1B,OAAA,EAAS,QAAQ,OAAA,IAAW,gBAAA;AAAA,MAC5B,QAAQ,OAAA,CAAQ,MAAA;AAAA,MAChB,SAAA,EAAW,QAAQ,SAAA,IAAa,kBAAA;AAAA,MAChC,UAAA,EAAY,QAAQ,UAAA,IAAc,mBAAA;AAAA,MAClC,SAAA,EAAW,aAAa,WAAW,CAAA,CAAA;AAAA,MACnC,OAAO,OAAA,CAAQ;AAAA,KAChB,CAAA;AACD,IAAA,IAAA,CAAK,OAAA,GAAU,IAAI,OAAA,CAAQ,IAAI,CAAA;AAC/B,IAAA,IAAA,CAAK,IAAA,GAAO,IAAI,IAAA,CAAK,IAAI,CAAA;AAAA,EAC3B;AACF","file":"index.cjs","sourcesContent":["/**\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 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","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"]}
|
package/dist/index.js
CHANGED
|
@@ -78,31 +78,24 @@ var GaruServerError = class extends GaruAPIError {
|
|
|
78
78
|
};
|
|
79
79
|
function mapApiError(status, body, requestId, retryAfterSec) {
|
|
80
80
|
const message = extractMessage(body) ?? `Garu API returned HTTP ${status}`;
|
|
81
|
-
if (status === 401)
|
|
82
|
-
|
|
83
|
-
if (status ===
|
|
84
|
-
return new GaruPermissionError(message, status, requestId, body);
|
|
85
|
-
if (status === 404)
|
|
86
|
-
return new GaruNotFoundError(message, status, requestId, body);
|
|
81
|
+
if (status === 401) return new GaruAuthenticationError(message, status, requestId, body);
|
|
82
|
+
if (status === 403) return new GaruPermissionError(message, status, requestId, body);
|
|
83
|
+
if (status === 404) return new GaruNotFoundError(message, status, requestId, body);
|
|
87
84
|
if (status === 400 || status === 422) {
|
|
88
85
|
return new GaruValidationError(message, status, requestId, body);
|
|
89
86
|
}
|
|
90
87
|
if (status === 429) {
|
|
91
88
|
return new GaruRateLimitError(message, status, requestId, body, retryAfterSec);
|
|
92
89
|
}
|
|
93
|
-
if (status >= 500)
|
|
94
|
-
return new GaruServerError(message, status, requestId, body);
|
|
90
|
+
if (status >= 500) return new GaruServerError(message, status, requestId, body);
|
|
95
91
|
return new GaruAPIError("api_error", message, status, requestId, body);
|
|
96
92
|
}
|
|
97
93
|
function extractMessage(body) {
|
|
98
|
-
if (typeof body === "string")
|
|
99
|
-
return body;
|
|
94
|
+
if (typeof body === "string") return body;
|
|
100
95
|
if (body && typeof body === "object") {
|
|
101
96
|
const m = body.message;
|
|
102
|
-
if (typeof m === "string")
|
|
103
|
-
|
|
104
|
-
if (Array.isArray(m) && m.every((x) => typeof x === "string"))
|
|
105
|
-
return m.join("; ");
|
|
97
|
+
if (typeof m === "string") return m;
|
|
98
|
+
if (Array.isArray(m) && m.every((x) => typeof x === "string")) return m.join("; ");
|
|
106
99
|
}
|
|
107
100
|
return null;
|
|
108
101
|
}
|
|
@@ -124,8 +117,7 @@ var HttpClient = class {
|
|
|
124
117
|
Accept: "application/json",
|
|
125
118
|
"User-Agent": cfg.userAgent
|
|
126
119
|
};
|
|
127
|
-
if (cfg.apiKey)
|
|
128
|
-
headers.Authorization = `Bearer ${cfg.apiKey}`;
|
|
120
|
+
if (cfg.apiKey) headers.Authorization = `Bearer ${cfg.apiKey}`;
|
|
129
121
|
this.client = createClient({
|
|
130
122
|
baseUrl: cfg.baseUrl.replace(/\/+$/, ""),
|
|
131
123
|
fetch: fetchImpl,
|
|
@@ -160,12 +152,10 @@ var HttpClient = class {
|
|
|
160
152
|
continue;
|
|
161
153
|
} catch (err) {
|
|
162
154
|
clearTimeout(timer);
|
|
163
|
-
if (isGaruApiError(err))
|
|
164
|
-
throw err;
|
|
155
|
+
if (isGaruApiError(err)) throw err;
|
|
165
156
|
const connErr = err instanceof Error && err.name === "AbortError" ? new GaruConnectionError(`Request timed out after ${this.cfg.timeoutMs}ms`, err) : new GaruConnectionError(err instanceof Error ? err.message : "Network error", err);
|
|
166
157
|
lastError = connErr;
|
|
167
|
-
if (attempt === this.cfg.maxRetries)
|
|
168
|
-
throw connErr;
|
|
158
|
+
if (attempt === this.cfg.maxRetries) throw connErr;
|
|
169
159
|
await sleep(backoffDelay(attempt, null));
|
|
170
160
|
continue;
|
|
171
161
|
}
|
|
@@ -177,8 +167,7 @@ function isGaruApiError(err) {
|
|
|
177
167
|
return err instanceof Error && err.name.startsWith("Garu") && err.name.endsWith("Error");
|
|
178
168
|
}
|
|
179
169
|
function parseRetryAfter(value) {
|
|
180
|
-
if (!value)
|
|
181
|
-
return null;
|
|
170
|
+
if (!value) return null;
|
|
182
171
|
const n = Number(value);
|
|
183
172
|
return Number.isFinite(n) && n >= 0 ? n : null;
|
|
184
173
|
}
|
|
@@ -207,6 +196,7 @@ var Charges = class {
|
|
|
207
196
|
constructor(http) {
|
|
208
197
|
this.http = http;
|
|
209
198
|
}
|
|
199
|
+
http;
|
|
210
200
|
/**
|
|
211
201
|
* Create a charge (PIX, credit card, or boleto).
|
|
212
202
|
*
|
|
@@ -283,10 +273,8 @@ var Charges = class {
|
|
|
283
273
|
async refund(id, params = {}) {
|
|
284
274
|
const idempotencyKey = params.idempotencyKey ?? generateIdempotencyKey();
|
|
285
275
|
const body = {};
|
|
286
|
-
if (params.amount !== void 0)
|
|
287
|
-
|
|
288
|
-
if (params.reason !== void 0)
|
|
289
|
-
body.reason = params.reason;
|
|
276
|
+
if (params.amount !== void 0) body.amount = params.amount;
|
|
277
|
+
if (params.reason !== void 0) body.reason = params.reason;
|
|
290
278
|
return this.http.call(
|
|
291
279
|
(signal) => this.http.client.POST("/api/transactions/{id}/refund", {
|
|
292
280
|
params: { path: { id } },
|
|
@@ -304,15 +292,12 @@ var Charges = class {
|
|
|
304
292
|
link: params.link ?? null,
|
|
305
293
|
affiliateId: params.affiliateId ?? null
|
|
306
294
|
};
|
|
307
|
-
if (params.additionalInfo !== void 0)
|
|
308
|
-
|
|
309
|
-
if (params.priceId !== void 0)
|
|
310
|
-
body.priceId = params.priceId;
|
|
295
|
+
if (params.additionalInfo !== void 0) body.additionalInfo = params.additionalInfo;
|
|
296
|
+
if (params.priceId !== void 0) body.priceId = params.priceId;
|
|
311
297
|
if (params.checkoutSessionToken !== void 0) {
|
|
312
298
|
body.checkoutSessionToken = params.checkoutSessionToken;
|
|
313
299
|
}
|
|
314
|
-
if (params.cardInfo)
|
|
315
|
-
body.CardInfo = params.cardInfo;
|
|
300
|
+
if (params.cardInfo) body.CardInfo = params.cardInfo;
|
|
316
301
|
return body;
|
|
317
302
|
}
|
|
318
303
|
};
|
|
@@ -322,6 +307,7 @@ var Meta = class {
|
|
|
322
307
|
constructor(http) {
|
|
323
308
|
this.http = http;
|
|
324
309
|
}
|
|
310
|
+
http;
|
|
325
311
|
/**
|
|
326
312
|
* Fetch the API's current capability payload.
|
|
327
313
|
*
|
|
@@ -377,21 +363,17 @@ function parseSignatureHeader(header) {
|
|
|
377
363
|
const fields = {};
|
|
378
364
|
for (const part of header.split(",")) {
|
|
379
365
|
const idx = part.indexOf("=");
|
|
380
|
-
if (idx === -1)
|
|
381
|
-
return null;
|
|
366
|
+
if (idx === -1) return null;
|
|
382
367
|
const key = part.slice(0, idx).trim();
|
|
383
368
|
const value = part.slice(idx + 1).trim();
|
|
384
|
-
if (!key || !value)
|
|
385
|
-
return null;
|
|
369
|
+
if (!key || !value) return null;
|
|
386
370
|
fields[key] = value;
|
|
387
371
|
}
|
|
388
372
|
const t = fields.t;
|
|
389
373
|
const v1 = fields.v1;
|
|
390
|
-
if (!t || !v1)
|
|
391
|
-
return null;
|
|
374
|
+
if (!t || !v1) return null;
|
|
392
375
|
const timestamp = Number(t);
|
|
393
|
-
if (!Number.isFinite(timestamp) || !/^[a-f0-9]+$/i.test(v1))
|
|
394
|
-
return null;
|
|
376
|
+
if (!Number.isFinite(timestamp) || !/^[a-f0-9]+$/i.test(v1)) return null;
|
|
395
377
|
return { timestamp, v1 };
|
|
396
378
|
}
|
|
397
379
|
|
|
@@ -424,5 +406,5 @@ var Garu = class {
|
|
|
424
406
|
};
|
|
425
407
|
|
|
426
408
|
export { Garu, GaruAPIError, GaruAuthenticationError, GaruConnectionError, GaruError, GaruNotFoundError, GaruPermissionError, GaruRateLimitError, GaruServerError, GaruSignatureVerificationError, GaruValidationError, webhooks };
|
|
427
|
-
//# sourceMappingURL=
|
|
409
|
+
//# sourceMappingURL=index.js.map
|
|
428
410
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +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,iBAA2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AqBb,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"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/http.ts","../src/idempotency.ts","../src/types.ts","../src/resources/charges.ts","../src/resources/meta.ts","../src/webhooks.ts","../src/client.ts"],"names":[],"mappings":";;;;;;AAmBO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EACnB,IAAA;AAAA,EAEhB,WAAA,CAAY,MAAqB,OAAA,EAAiB;AAChD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAEO,IAAM,mBAAA,GAAN,cAAkC,SAAA,CAAU;AAAA,EACjC,eAAA;AAAA,EAChB,WAAA,CAAY,SAAiB,eAAA,EAA2B;AACtD,IAAA,KAAA,CAAM,oBAAoB,OAAO,CAAA;AACjC,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AACZ,IAAA,IAAA,CAAK,eAAA,GAAkB,eAAA;AAAA,EACzB;AACF;AAEO,IAAM,8BAAA,GAAN,cAA6C,SAAA,CAAU;AAAA,EAC5D,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,iCAAiC,OAAO,CAAA;AAC9C,IAAA,IAAA,CAAK,IAAA,GAAO,gCAAA;AAAA,EACd;AACF;AAEO,IAAM,YAAA,GAAN,cAA2B,SAAA,CAAU;AAAA,EAC1B,MAAA;AAAA,EACA,SAAA;AAAA,EACA,IAAA;AAAA,EAEhB,WAAA,CACE,IAAA,EACA,OAAA,EACA,MAAA,EACA,WACA,IAAA,EACA;AACA,IAAA,KAAA,CAAM,MAAM,OAAO,CAAA;AACnB,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,SAAA,GAAY,SAAA;AACjB,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAEO,IAAM,uBAAA,GAAN,cAAsC,YAAA,CAAa;AAAA,EACxD,WAAA,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BAAA,GAAmB,qBAAA;AACzB,IAAM,kBAAA,GAAqB,GAAA;AAC3B,IAAM,mBAAA,GAAsB,CAAA;AAC5B,IAAM,WAAA,GAAc,OAAA;AAqBb,IAAM,OAAN,MAAW;AAAA,EACA,OAAA;AAAA,EACA,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMhB,OAAuB,QAAA,GAAW,QAAA;AAAA,EAClB,QAAA,GAAW,QAAA;AAAA,EAE3B,WAAA,CAAY,OAAA,GAAuB,EAAC,EAAG;AACrC,IAAA,MAAM,IAAA,GAAO,IAAI,UAAA,CAAW;AAAA,MAC1B,OAAA,EAAS,QAAQ,OAAA,IAAW,gBAAA;AAAA,MAC5B,QAAQ,OAAA,CAAQ,MAAA;AAAA,MAChB,SAAA,EAAW,QAAQ,SAAA,IAAa,kBAAA;AAAA,MAChC,UAAA,EAAY,QAAQ,UAAA,IAAc,mBAAA;AAAA,MAClC,SAAA,EAAW,aAAa,WAAW,CAAA,CAAA;AAAA,MACnC,OAAO,OAAA,CAAQ;AAAA,KAChB,CAAA;AACD,IAAA,IAAA,CAAK,OAAA,GAAU,IAAI,OAAA,CAAQ,IAAI,CAAA;AAC/B,IAAA,IAAA,CAAK,IAAA,GAAO,IAAI,IAAA,CAAK,IAAI,CAAA;AAAA,EAC3B;AACF","file":"index.js","sourcesContent":["/**\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 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","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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@garuhq/node",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "Official Node.js / TypeScript SDK for the Garu payment gateway.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://garu.com.br",
|
|
@@ -52,9 +52,9 @@
|
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"@types/node": "20.12.7",
|
|
54
54
|
"openapi-typescript": "7.4.2",
|
|
55
|
-
"tsup": "8.
|
|
55
|
+
"tsup": "8.5.1",
|
|
56
56
|
"typescript": "5.4.5",
|
|
57
|
-
"vitest": "
|
|
57
|
+
"vitest": "3.2.4"
|
|
58
58
|
},
|
|
59
59
|
"dependencies": {
|
|
60
60
|
"openapi-fetch": "0.9.7"
|