@garuhq/node 0.1.0

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