barkapay 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +191 -0
- package/LICENSE +21 -0
- package/README.md +516 -2
- package/dist/index.cjs +1513 -0
- package/dist/index.d.cts +989 -0
- package/dist/index.d.ts +989 -0
- package/dist/index.mjs +1484 -0
- package/package.json +88 -4
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1513 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var node_crypto = require('node:crypto');
|
|
4
|
+
|
|
5
|
+
// src/apiClient.ts
|
|
6
|
+
|
|
7
|
+
// src/types.ts
|
|
8
|
+
var PAYMENT_STATUSES = [
|
|
9
|
+
"CREATED",
|
|
10
|
+
"AWAITING_OTP",
|
|
11
|
+
"QUEUED_FOR_PROCESSING",
|
|
12
|
+
"PROCESSING_OPERATOR",
|
|
13
|
+
"PROCESSING_SYSTEM",
|
|
14
|
+
"SUCCESSFUL",
|
|
15
|
+
"FAILED",
|
|
16
|
+
"EXPIRED",
|
|
17
|
+
"COMPLIANCE_FLAGGED",
|
|
18
|
+
"CANCELED"
|
|
19
|
+
];
|
|
20
|
+
var TRANSFER_STATUSES = [
|
|
21
|
+
"CREATED",
|
|
22
|
+
"PROCESSING_OPERATOR",
|
|
23
|
+
"PROCESSING_SYSTEM",
|
|
24
|
+
"SUCCESSFUL",
|
|
25
|
+
"FAILED",
|
|
26
|
+
"COMPLIANCE_FLAGGED",
|
|
27
|
+
"REFUNDED",
|
|
28
|
+
"UNRESOLVED",
|
|
29
|
+
"UNCERTAIN"
|
|
30
|
+
];
|
|
31
|
+
var PAYMENT_LINK_STATUSES = [
|
|
32
|
+
"active",
|
|
33
|
+
"paused",
|
|
34
|
+
"paid",
|
|
35
|
+
"expired",
|
|
36
|
+
"canceled",
|
|
37
|
+
"admin_blocked"
|
|
38
|
+
];
|
|
39
|
+
function isPaymentStatusFinal(status) {
|
|
40
|
+
return status === "SUCCESSFUL" || status === "FAILED" || status === "EXPIRED" || status === "CANCELED";
|
|
41
|
+
}
|
|
42
|
+
function isTransferStatusFinal(status) {
|
|
43
|
+
return status === "SUCCESSFUL" || status === "FAILED" || status === "REFUNDED";
|
|
44
|
+
}
|
|
45
|
+
var REASON_CODES = [
|
|
46
|
+
"payer_insufficient_funds",
|
|
47
|
+
"payer_refused",
|
|
48
|
+
"payer_unreachable",
|
|
49
|
+
"invalid_otp",
|
|
50
|
+
"otp_expired",
|
|
51
|
+
"expired",
|
|
52
|
+
"recipient_invalid",
|
|
53
|
+
"operator_unavailable",
|
|
54
|
+
"operator_timeout",
|
|
55
|
+
"unconfirmed_after_window",
|
|
56
|
+
"payment_not_completed",
|
|
57
|
+
"amount_out_of_bounds",
|
|
58
|
+
"duplicate",
|
|
59
|
+
"provider_float_insufficient",
|
|
60
|
+
"internal_error",
|
|
61
|
+
"unknown"
|
|
62
|
+
];
|
|
63
|
+
|
|
64
|
+
// src/util.ts
|
|
65
|
+
function isRecord(value) {
|
|
66
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
67
|
+
}
|
|
68
|
+
function coerceStr(data, key) {
|
|
69
|
+
const value = data[key];
|
|
70
|
+
return typeof value === "string" ? value : null;
|
|
71
|
+
}
|
|
72
|
+
function coerceInt(data, key) {
|
|
73
|
+
const value = data[key];
|
|
74
|
+
if (typeof value === "number" && Number.isInteger(value)) {
|
|
75
|
+
return value;
|
|
76
|
+
}
|
|
77
|
+
if (typeof value === "string" && /^\d+$/.test(value)) {
|
|
78
|
+
return Number.parseInt(value, 10);
|
|
79
|
+
}
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
function coerceBool(data, key) {
|
|
83
|
+
const value = data[key];
|
|
84
|
+
return typeof value === "boolean" ? value : null;
|
|
85
|
+
}
|
|
86
|
+
function coerceAmount(data, key) {
|
|
87
|
+
const value = data[key];
|
|
88
|
+
return typeof value === "number" || typeof value === "string" ? value : null;
|
|
89
|
+
}
|
|
90
|
+
function coerceDecimal(data, key) {
|
|
91
|
+
const value = data[key];
|
|
92
|
+
if (typeof value === "string") {
|
|
93
|
+
return value;
|
|
94
|
+
}
|
|
95
|
+
return typeof value === "number" && Number.isFinite(value) ? String(value) : null;
|
|
96
|
+
}
|
|
97
|
+
function coerceObject(data, key) {
|
|
98
|
+
const value = data[key];
|
|
99
|
+
return isRecord(value) ? value : null;
|
|
100
|
+
}
|
|
101
|
+
function coerceArray(data, key) {
|
|
102
|
+
const value = data[key];
|
|
103
|
+
return Array.isArray(value) ? value : null;
|
|
104
|
+
}
|
|
105
|
+
function coerceStrArray(data, key) {
|
|
106
|
+
const value = data[key];
|
|
107
|
+
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : null;
|
|
108
|
+
}
|
|
109
|
+
function decodeEnvelope(text) {
|
|
110
|
+
if (text.trim() === "") {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
try {
|
|
114
|
+
const decoded = JSON.parse(text);
|
|
115
|
+
return isRecord(decoded) ? decoded : null;
|
|
116
|
+
} catch {
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// src/dto.ts
|
|
122
|
+
function asPaymentStatus(value) {
|
|
123
|
+
return value !== null && PAYMENT_STATUSES.includes(value) ? value : null;
|
|
124
|
+
}
|
|
125
|
+
function asTransferStatus(value) {
|
|
126
|
+
return value !== null && TRANSFER_STATUSES.includes(value) ? value : null;
|
|
127
|
+
}
|
|
128
|
+
function asPaymentLinkStatus(value) {
|
|
129
|
+
return value !== null && PAYMENT_LINK_STATUSES.includes(value) ? value : null;
|
|
130
|
+
}
|
|
131
|
+
function hydratePayment(data) {
|
|
132
|
+
return {
|
|
133
|
+
object: "payment",
|
|
134
|
+
publicId: coerceStr(data, "public_id") ?? "",
|
|
135
|
+
amount: coerceAmount(data, "amount"),
|
|
136
|
+
fees: coerceDecimal(data, "fees"),
|
|
137
|
+
currency: coerceStr(data, "currency"),
|
|
138
|
+
phoneNumber: coerceStr(data, "phone_number"),
|
|
139
|
+
country: coerceStr(data, "country"),
|
|
140
|
+
operator: coerceStr(data, "operator"),
|
|
141
|
+
channel: coerceStr(data, "channel"),
|
|
142
|
+
status: asPaymentStatus(coerceStr(data, "status")),
|
|
143
|
+
orderId: coerceStr(data, "order_id"),
|
|
144
|
+
providerTransactionId: coerceStr(data, "provider_transaction_id"),
|
|
145
|
+
providerReference: coerceStr(data, "provider_reference"),
|
|
146
|
+
orderData: coerceObject(data, "order_data"),
|
|
147
|
+
linkPublicId: coerceStr(data, "link_public_id"),
|
|
148
|
+
reason: coerceStr(data, "reason"),
|
|
149
|
+
reasonCode: coerceStr(data, "reason_code"),
|
|
150
|
+
providerReason: coerceStr(data, "provider_reason"),
|
|
151
|
+
redirectUrl: coerceStr(data, "redirect_url"),
|
|
152
|
+
createdAt: coerceStr(data, "created_at"),
|
|
153
|
+
raw: data
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
function hydrateTransfer(data) {
|
|
157
|
+
return {
|
|
158
|
+
object: "transfer",
|
|
159
|
+
publicId: coerceStr(data, "public_id") ?? "",
|
|
160
|
+
amount: coerceAmount(data, "amount"),
|
|
161
|
+
fees: coerceDecimal(data, "fees"),
|
|
162
|
+
currency: coerceStr(data, "currency"),
|
|
163
|
+
phoneNumber: coerceStr(data, "phone_number"),
|
|
164
|
+
country: coerceStr(data, "country"),
|
|
165
|
+
operator: coerceStr(data, "operator"),
|
|
166
|
+
channel: coerceStr(data, "channel"),
|
|
167
|
+
status: asTransferStatus(coerceStr(data, "status")),
|
|
168
|
+
orderId: coerceStr(data, "order_id"),
|
|
169
|
+
providerTransactionId: coerceStr(data, "provider_transaction_id"),
|
|
170
|
+
providerReference: coerceStr(data, "provider_reference"),
|
|
171
|
+
orderData: coerceObject(data, "order_data"),
|
|
172
|
+
reason: coerceStr(data, "reason"),
|
|
173
|
+
reasonCode: coerceStr(data, "reason_code"),
|
|
174
|
+
providerReason: coerceStr(data, "provider_reason"),
|
|
175
|
+
createdAt: coerceStr(data, "created_at"),
|
|
176
|
+
raw: data
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
function hydrateBalance(data) {
|
|
180
|
+
const balancesRaw = coerceArray(data, "balances");
|
|
181
|
+
const balances = balancesRaw === null ? null : balancesRaw.filter(isRecord);
|
|
182
|
+
return {
|
|
183
|
+
country: coerceStr(data, "country"),
|
|
184
|
+
currency: coerceStr(data, "currency"),
|
|
185
|
+
available: coerceDecimal(data, "available"),
|
|
186
|
+
total: coerceDecimal(data, "total"),
|
|
187
|
+
holds: coerceDecimal(data, "holds"),
|
|
188
|
+
balances,
|
|
189
|
+
raw: data
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
function hydrateStats(stats) {
|
|
193
|
+
return {
|
|
194
|
+
paymentsCount: stats === null ? null : coerceInt(stats, "payments_count"),
|
|
195
|
+
totalCollected: stats === null ? null : coerceDecimal(stats, "total_collected")
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
function hydratePaymentLink(data) {
|
|
199
|
+
const amount = coerceObject(data, "amount") ?? {};
|
|
200
|
+
const redirect = coerceObject(data, "redirect");
|
|
201
|
+
const restrictions = coerceObject(data, "restrictions");
|
|
202
|
+
const payer = coerceObject(data, "payer");
|
|
203
|
+
const notify = coerceObject(data, "notify");
|
|
204
|
+
return {
|
|
205
|
+
object: "payment_link",
|
|
206
|
+
publicId: coerceStr(data, "public_id") ?? "",
|
|
207
|
+
slug: coerceStr(data, "slug"),
|
|
208
|
+
url: coerceStr(data, "url"),
|
|
209
|
+
status: asPaymentLinkStatus(coerceStr(data, "status")),
|
|
210
|
+
source: coerceStr(data, "source"),
|
|
211
|
+
usage: coerceStr(data, "usage"),
|
|
212
|
+
amount: {
|
|
213
|
+
type: coerceStr(amount, "type"),
|
|
214
|
+
value: coerceDecimal(amount, "value"),
|
|
215
|
+
min: coerceDecimal(amount, "min"),
|
|
216
|
+
max: coerceDecimal(amount, "max"),
|
|
217
|
+
currency: coerceStr(amount, "currency")
|
|
218
|
+
},
|
|
219
|
+
title: coerceStr(data, "title"),
|
|
220
|
+
description: coerceStr(data, "description"),
|
|
221
|
+
order: coerceObject(data, "order"),
|
|
222
|
+
redirect: redirect === null ? null : {
|
|
223
|
+
successUrl: coerceStr(redirect, "success_url"),
|
|
224
|
+
cancelUrl: coerceStr(redirect, "cancel_url")
|
|
225
|
+
},
|
|
226
|
+
restrictions: restrictions === null ? null : {
|
|
227
|
+
countries: coerceStrArray(restrictions, "countries"),
|
|
228
|
+
operators: coerceStrArray(restrictions, "operators")
|
|
229
|
+
},
|
|
230
|
+
payer: payer === null ? null : {
|
|
231
|
+
fullName: coerceStr(payer, "full_name"),
|
|
232
|
+
email: coerceStr(payer, "email"),
|
|
233
|
+
phone: coerceStr(payer, "phone"),
|
|
234
|
+
locale: coerceStr(payer, "locale")
|
|
235
|
+
},
|
|
236
|
+
collect: coerceObject(data, "collect") ?? {},
|
|
237
|
+
notifyEmailInvoice: notify === null ? null : coerceBool(notify, "email_invoice"),
|
|
238
|
+
expiresAt: coerceStr(data, "expires_at"),
|
|
239
|
+
stats: hydrateStats(coerceObject(data, "stats")),
|
|
240
|
+
paidByPaymentPublicId: coerceStr(data, "paid_by_payment_public_id"),
|
|
241
|
+
createdAt: coerceStr(data, "created_at"),
|
|
242
|
+
raw: data
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
function hydratePaymentLinkSummary(data) {
|
|
246
|
+
return {
|
|
247
|
+
publicId: coerceStr(data, "public_id") ?? "",
|
|
248
|
+
slug: coerceStr(data, "slug"),
|
|
249
|
+
status: asPaymentLinkStatus(coerceStr(data, "status")),
|
|
250
|
+
stats: hydrateStats(coerceObject(data, "stats"))
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
function hydratePagination(meta) {
|
|
254
|
+
return {
|
|
255
|
+
currentPage: coerceInt(meta, "current_page"),
|
|
256
|
+
lastPage: coerceInt(meta, "last_page"),
|
|
257
|
+
perPage: coerceInt(meta, "per_page"),
|
|
258
|
+
total: coerceInt(meta, "total")
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
function paginationOf(envelope) {
|
|
262
|
+
const meta = coerceObject(envelope, "meta");
|
|
263
|
+
return meta !== null ? hydratePagination(meta) : null;
|
|
264
|
+
}
|
|
265
|
+
function rowsOf(envelope, rowsKey) {
|
|
266
|
+
const data = coerceObject(envelope, "data") ?? {};
|
|
267
|
+
const rows = coerceArray(data, rowsKey) ?? [];
|
|
268
|
+
return rows.filter(isRecord);
|
|
269
|
+
}
|
|
270
|
+
function hydratePaymentList(envelope) {
|
|
271
|
+
return {
|
|
272
|
+
data: rowsOf(envelope, "payments").map(hydratePayment),
|
|
273
|
+
meta: paginationOf(envelope)
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
function hydrateTransferList(envelope) {
|
|
277
|
+
return {
|
|
278
|
+
data: rowsOf(envelope, "transfers").map(hydrateTransfer),
|
|
279
|
+
meta: paginationOf(envelope)
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
function hydratePaymentLinkList(envelope) {
|
|
283
|
+
return {
|
|
284
|
+
data: rowsOf(envelope, "payment_links").map(hydratePaymentLink),
|
|
285
|
+
meta: paginationOf(envelope)
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
function hydratePaymentLinkPaymentList(envelope) {
|
|
289
|
+
const data = coerceObject(envelope, "data") ?? {};
|
|
290
|
+
const link = coerceObject(data, "payment_link");
|
|
291
|
+
return {
|
|
292
|
+
data: rowsOf(envelope, "payments").map(hydratePayment),
|
|
293
|
+
meta: paginationOf(envelope),
|
|
294
|
+
paymentLink: link === null ? null : hydratePaymentLinkSummary(link)
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
function firstRow(envelope, rowsKey) {
|
|
298
|
+
return rowsOf(envelope, rowsKey)[0] ?? null;
|
|
299
|
+
}
|
|
300
|
+
function resourceOf(envelope, key) {
|
|
301
|
+
const data = coerceObject(envelope, "data") ?? {};
|
|
302
|
+
return coerceObject(data, key);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// src/errors.ts
|
|
306
|
+
var BarkaPayError = class extends Error {
|
|
307
|
+
constructor(message, options) {
|
|
308
|
+
super(message, options);
|
|
309
|
+
this.name = new.target.name;
|
|
310
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
311
|
+
}
|
|
312
|
+
};
|
|
313
|
+
var ConfigurationError = class extends BarkaPayError {
|
|
314
|
+
};
|
|
315
|
+
var NetworkError = class extends BarkaPayError {
|
|
316
|
+
constructor(message, options = {}) {
|
|
317
|
+
super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
|
|
318
|
+
this.timedOut = options.timedOut ?? false;
|
|
319
|
+
this.requestId = options.requestId ?? null;
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
var SignatureVerificationError = class extends BarkaPayError {
|
|
323
|
+
};
|
|
324
|
+
var ApiError = class extends BarkaPayError {
|
|
325
|
+
constructor(message, context = {}) {
|
|
326
|
+
super(message);
|
|
327
|
+
this.code = context.code ?? "";
|
|
328
|
+
this.httpStatus = context.httpStatus ?? 0;
|
|
329
|
+
this.requestId = context.requestId ?? null;
|
|
330
|
+
this.errors = context.errors ?? {};
|
|
331
|
+
this.data = context.data ?? null;
|
|
332
|
+
this.retryAfter = context.retryAfter ?? null;
|
|
333
|
+
this.headers = { ...context.headers ?? {} };
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* The payment snapshot carried by the error, if any. Present when a payment
|
|
337
|
+
* was created and then refused (`payment_failed`, `operator_unavailable`…):
|
|
338
|
+
* it holds the `publicId`, the `FAILED` status and the `reasonCode`.
|
|
339
|
+
*/
|
|
340
|
+
get payment() {
|
|
341
|
+
const row = this.data === null ? null : coerceObject(this.data, "payment");
|
|
342
|
+
return row === null ? null : hydratePayment(row);
|
|
343
|
+
}
|
|
344
|
+
/** The transfer snapshot carried by the error, if any (see {@link ApiError.payment}). */
|
|
345
|
+
get transfer() {
|
|
346
|
+
const row = this.data === null ? null : coerceObject(this.data, "transfer");
|
|
347
|
+
return row === null ? null : hydrateTransfer(row);
|
|
348
|
+
}
|
|
349
|
+
/** Build the most specific exception for an error envelope. */
|
|
350
|
+
static fromEnvelope(httpStatus, envelope, fallbackRequestId = null, retryAfter = null, headers = {}) {
|
|
351
|
+
const code = typeof envelope.code === "string" ? envelope.code : "";
|
|
352
|
+
const rawMessage = envelope.message;
|
|
353
|
+
const message = typeof rawMessage === "string" && rawMessage !== "" ? rawMessage : `barkapay API error (HTTP ${httpStatus}).`;
|
|
354
|
+
const requestId = typeof envelope.request_id === "string" && envelope.request_id !== "" ? envelope.request_id : fallbackRequestId;
|
|
355
|
+
const errors = isRecord(envelope.errors) ? envelope.errors : {};
|
|
356
|
+
const data = isRecord(envelope.data) ? envelope.data : null;
|
|
357
|
+
const Ctor = classFor(code, httpStatus);
|
|
358
|
+
return new Ctor(message, {
|
|
359
|
+
code,
|
|
360
|
+
httpStatus,
|
|
361
|
+
requestId,
|
|
362
|
+
errors,
|
|
363
|
+
data,
|
|
364
|
+
retryAfter,
|
|
365
|
+
headers
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
};
|
|
369
|
+
var AuthenticationError = class extends ApiError {
|
|
370
|
+
};
|
|
371
|
+
var AuthorizationError = class extends ApiError {
|
|
372
|
+
};
|
|
373
|
+
var ValidationError = class extends ApiError {
|
|
374
|
+
};
|
|
375
|
+
var NotFoundError = class extends ApiError {
|
|
376
|
+
};
|
|
377
|
+
var ConflictError = class extends ApiError {
|
|
378
|
+
};
|
|
379
|
+
var RateLimitError = class extends ApiError {
|
|
380
|
+
};
|
|
381
|
+
var InsufficientBalanceError = class extends ApiError {
|
|
382
|
+
};
|
|
383
|
+
var PaymentFailedError = class extends ApiError {
|
|
384
|
+
};
|
|
385
|
+
var TransferFailedError = class extends ApiError {
|
|
386
|
+
};
|
|
387
|
+
var ServiceUnavailableError = class extends ApiError {
|
|
388
|
+
};
|
|
389
|
+
var ServerError = class extends ApiError {
|
|
390
|
+
};
|
|
391
|
+
function classFor(code, httpStatus) {
|
|
392
|
+
switch (code) {
|
|
393
|
+
case "unauthenticated":
|
|
394
|
+
case "invalid_api_key":
|
|
395
|
+
case "incorrect_credentials":
|
|
396
|
+
return AuthenticationError;
|
|
397
|
+
case "unauthorized":
|
|
398
|
+
case "ip_not_allowed":
|
|
399
|
+
case "merchant_suspended":
|
|
400
|
+
case "merchant_closed":
|
|
401
|
+
return AuthorizationError;
|
|
402
|
+
case "validation_error":
|
|
403
|
+
case "invalid_input":
|
|
404
|
+
return ValidationError;
|
|
405
|
+
case "resource_not_found":
|
|
406
|
+
return NotFoundError;
|
|
407
|
+
case "duplicate_transaction":
|
|
408
|
+
case "resource_already_exists":
|
|
409
|
+
return ConflictError;
|
|
410
|
+
case "too_many_requests":
|
|
411
|
+
return RateLimitError;
|
|
412
|
+
case "insufficient_balance":
|
|
413
|
+
return InsufficientBalanceError;
|
|
414
|
+
case "payment_failed":
|
|
415
|
+
return PaymentFailedError;
|
|
416
|
+
case "transfer_failed":
|
|
417
|
+
return TransferFailedError;
|
|
418
|
+
case "service_unavailable":
|
|
419
|
+
case "operator_unavailable":
|
|
420
|
+
return ServiceUnavailableError;
|
|
421
|
+
}
|
|
422
|
+
if (httpStatus === 401) return AuthenticationError;
|
|
423
|
+
if (httpStatus === 403 || httpStatus === 410 || httpStatus === 451)
|
|
424
|
+
return AuthorizationError;
|
|
425
|
+
if (httpStatus === 404) return NotFoundError;
|
|
426
|
+
if (httpStatus === 409) return ConflictError;
|
|
427
|
+
if (httpStatus === 422) return ValidationError;
|
|
428
|
+
if (httpStatus === 429) return RateLimitError;
|
|
429
|
+
if (httpStatus === 503) return ServiceUnavailableError;
|
|
430
|
+
if (httpStatus >= 500) return ServerError;
|
|
431
|
+
return ApiError;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// src/path.ts
|
|
435
|
+
var COUNTRY_PATTERN = /^[a-z]{2}$/;
|
|
436
|
+
var MAX_SEGMENT_LENGTH = 512;
|
|
437
|
+
function normalizeCountry(value) {
|
|
438
|
+
if (typeof value !== "string") {
|
|
439
|
+
throw new ConfigurationError('The country code must be a string such as "bf".');
|
|
440
|
+
}
|
|
441
|
+
const country = value.trim().toLowerCase();
|
|
442
|
+
if (!COUNTRY_PATTERN.test(country)) {
|
|
443
|
+
throw new ConfigurationError(
|
|
444
|
+
'Invalid country code: expected two letters such as "bf", "bj" or "sn".'
|
|
445
|
+
);
|
|
446
|
+
}
|
|
447
|
+
return country;
|
|
448
|
+
}
|
|
449
|
+
function pathSegment(value, label) {
|
|
450
|
+
if (typeof value !== "string") {
|
|
451
|
+
throw new ConfigurationError(`The ${label} must be a string.`);
|
|
452
|
+
}
|
|
453
|
+
if (value.trim() === "") {
|
|
454
|
+
throw new ConfigurationError(`The ${label} must not be empty.`);
|
|
455
|
+
}
|
|
456
|
+
if (value.length > MAX_SEGMENT_LENGTH) {
|
|
457
|
+
throw new ConfigurationError(`The ${label} is too long.`);
|
|
458
|
+
}
|
|
459
|
+
if (value === "." || value === "..") {
|
|
460
|
+
throw new ConfigurationError(`The ${label} must not be a dot segment.`);
|
|
461
|
+
}
|
|
462
|
+
if (/[\u0000-\u001f\u007f]/.test(value)) {
|
|
463
|
+
throw new ConfigurationError(`The ${label} must not contain control characters.`);
|
|
464
|
+
}
|
|
465
|
+
if (value.includes("?") || value.includes("#")) {
|
|
466
|
+
throw new ConfigurationError(
|
|
467
|
+
`The ${label} must not contain "?" or "#": no barkapay identifier does.`
|
|
468
|
+
);
|
|
469
|
+
}
|
|
470
|
+
if (value.includes("/")) {
|
|
471
|
+
throw new ConfigurationError(
|
|
472
|
+
`The ${label} must not contain a slash: such a value cannot be looked up by path \u2014 filter a list call instead (for example \`list({ order_id })\`).`
|
|
473
|
+
);
|
|
474
|
+
}
|
|
475
|
+
try {
|
|
476
|
+
return encodeURIComponent(value);
|
|
477
|
+
} catch {
|
|
478
|
+
throw new ConfigurationError(`The ${label} is not valid Unicode text.`);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// src/apiClient.ts
|
|
483
|
+
var BASE_DELAY_MS = 500;
|
|
484
|
+
var MAX_DELAY_MS = 8e3;
|
|
485
|
+
var MAX_RETRY_AFTER_SECONDS = 10;
|
|
486
|
+
var KEPT_HEADERS = [
|
|
487
|
+
"retry-after",
|
|
488
|
+
"x-request-id",
|
|
489
|
+
"x-ratelimit-limit",
|
|
490
|
+
"x-ratelimit-remaining"
|
|
491
|
+
];
|
|
492
|
+
var REDACTED = "[redacted]";
|
|
493
|
+
var MAX_RESPONSE_BYTES = 10 * 1024 * 1024;
|
|
494
|
+
var TransportFailure = class extends Error {
|
|
495
|
+
constructor(reason, timedOut) {
|
|
496
|
+
super("transport failure");
|
|
497
|
+
this.reason = reason;
|
|
498
|
+
this.timedOut = timedOut;
|
|
499
|
+
}
|
|
500
|
+
};
|
|
501
|
+
var ApiClient = class {
|
|
502
|
+
#fetchFn;
|
|
503
|
+
#authorization;
|
|
504
|
+
#secrets;
|
|
505
|
+
#baseUrl;
|
|
506
|
+
#defaultCountry;
|
|
507
|
+
#maxRetries;
|
|
508
|
+
#timeoutMs;
|
|
509
|
+
#userAgent;
|
|
510
|
+
#sleep;
|
|
511
|
+
#random;
|
|
512
|
+
constructor(options) {
|
|
513
|
+
this.#fetchFn = options.fetchFn;
|
|
514
|
+
this.#authorization = options.authorization;
|
|
515
|
+
this.#secrets = secretsOf(options.authorization);
|
|
516
|
+
this.#baseUrl = options.baseUrl;
|
|
517
|
+
this.#defaultCountry = options.defaultCountry;
|
|
518
|
+
this.#maxRetries = options.maxRetries;
|
|
519
|
+
this.#timeoutMs = options.timeoutMs;
|
|
520
|
+
this.#userAgent = options.userAgent;
|
|
521
|
+
this.#sleep = options.sleep ?? defaultSleep;
|
|
522
|
+
this.#random = options.random ?? Math.random;
|
|
523
|
+
}
|
|
524
|
+
get baseUrl() {
|
|
525
|
+
return this.#baseUrl;
|
|
526
|
+
}
|
|
527
|
+
get defaultCountry() {
|
|
528
|
+
return this.#defaultCountry;
|
|
529
|
+
}
|
|
530
|
+
async request(method, path, { country, body, query, retry, allowEmpty = false } = {}) {
|
|
531
|
+
const cc = country === void 0 || country === null || country === "" ? this.#defaultCountry : normalizeCountry(country);
|
|
532
|
+
if (cc === "") {
|
|
533
|
+
throw new ConfigurationError(
|
|
534
|
+
"No country given for this call and no default set on the client."
|
|
535
|
+
);
|
|
536
|
+
}
|
|
537
|
+
let url = `${this.#baseUrl}/${cc}/v1/${path.replace(/^\/+/, "")}`;
|
|
538
|
+
const qs = buildQuery(query);
|
|
539
|
+
if (qs !== "") {
|
|
540
|
+
url += `?${qs}`;
|
|
541
|
+
}
|
|
542
|
+
const requestId = node_crypto.randomUUID();
|
|
543
|
+
const headers = {
|
|
544
|
+
Authorization: this.#authorization,
|
|
545
|
+
Accept: "application/json",
|
|
546
|
+
"User-Agent": this.#userAgent,
|
|
547
|
+
"X-Request-Id": requestId
|
|
548
|
+
};
|
|
549
|
+
let payload;
|
|
550
|
+
if (body !== void 0 && body !== null) {
|
|
551
|
+
try {
|
|
552
|
+
payload = JSON.stringify(body);
|
|
553
|
+
} catch {
|
|
554
|
+
throw new ConfigurationError("The request body cannot be serialised to JSON.");
|
|
555
|
+
}
|
|
556
|
+
headers["Content-Type"] = "application/json";
|
|
557
|
+
}
|
|
558
|
+
const mode = retry ?? (method === "GET" || method === "HEAD" ? "idempotent" : "rate-limit-only");
|
|
559
|
+
for (let attempt = 0; ; attempt++) {
|
|
560
|
+
const mayRetry = attempt < this.#maxRetries;
|
|
561
|
+
let response;
|
|
562
|
+
try {
|
|
563
|
+
response = await this.#send(url, method, headers, payload);
|
|
564
|
+
} catch (failure) {
|
|
565
|
+
if (!(failure instanceof TransportFailure)) {
|
|
566
|
+
throw failure;
|
|
567
|
+
}
|
|
568
|
+
if (mayRetry && mode === "idempotent") {
|
|
569
|
+
await this.#sleep(backoffMs(attempt, this.#random));
|
|
570
|
+
continue;
|
|
571
|
+
}
|
|
572
|
+
throw this.#networkError(failure, method, mode, requestId);
|
|
573
|
+
}
|
|
574
|
+
if (mayRetry && isRetryableStatus(response.status, mode)) {
|
|
575
|
+
const delay = retryDelayMs(attempt, response.retryAfter, this.#random);
|
|
576
|
+
if (delay !== null) {
|
|
577
|
+
await this.#sleep(delay);
|
|
578
|
+
continue;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
return handle(response, requestId, allowEmpty);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
/** One HTTP exchange, bounded by `timeoutMs` from the first byte sent to the last byte read. */
|
|
585
|
+
async #send(url, method, headers, payload) {
|
|
586
|
+
const controller = new AbortController();
|
|
587
|
+
let timedOut = false;
|
|
588
|
+
let timer;
|
|
589
|
+
const deadline = new Promise((_, reject) => {
|
|
590
|
+
timer = setTimeout(() => {
|
|
591
|
+
timedOut = true;
|
|
592
|
+
controller.abort();
|
|
593
|
+
reject(new TransportFailure(void 0, true));
|
|
594
|
+
}, this.#timeoutMs);
|
|
595
|
+
});
|
|
596
|
+
const init = {
|
|
597
|
+
method,
|
|
598
|
+
headers: { ...headers },
|
|
599
|
+
signal: controller.signal,
|
|
600
|
+
// Never follow a redirect: the Authorization header must not travel to
|
|
601
|
+
// whatever URL a 3xx points at.
|
|
602
|
+
redirect: "manual"
|
|
603
|
+
};
|
|
604
|
+
if (payload !== void 0) {
|
|
605
|
+
init.body = payload;
|
|
606
|
+
}
|
|
607
|
+
const fetchFn = this.#fetchFn;
|
|
608
|
+
const exchange = (async () => {
|
|
609
|
+
const response = await fetchFn(url, init);
|
|
610
|
+
const text = await readCapped(response);
|
|
611
|
+
const kept = {};
|
|
612
|
+
for (const name of KEPT_HEADERS) {
|
|
613
|
+
const value = readHeader(response, name);
|
|
614
|
+
if (value !== null) {
|
|
615
|
+
kept[name] = value;
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
return {
|
|
619
|
+
status: response.status,
|
|
620
|
+
text,
|
|
621
|
+
retryAfter: parseRetryAfter(kept["retry-after"] ?? null),
|
|
622
|
+
requestId: kept["x-request-id"] ?? null,
|
|
623
|
+
headers: kept
|
|
624
|
+
};
|
|
625
|
+
})();
|
|
626
|
+
exchange.catch(() => void 0);
|
|
627
|
+
try {
|
|
628
|
+
return await Promise.race([exchange, deadline]);
|
|
629
|
+
} catch (reason) {
|
|
630
|
+
if (reason instanceof TransportFailure) {
|
|
631
|
+
throw reason;
|
|
632
|
+
}
|
|
633
|
+
throw new TransportFailure(reason, timedOut);
|
|
634
|
+
} finally {
|
|
635
|
+
clearTimeout(timer);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
#networkError(failure, method, mode, requestId) {
|
|
639
|
+
const hint = mode === "idempotent" ? "" : " The API may still have processed it: check before sending it again.";
|
|
640
|
+
if (failure.timedOut) {
|
|
641
|
+
return new NetworkError(
|
|
642
|
+
`The ${method} request timed out after ${this.#timeoutMs} ms.${hint}`,
|
|
643
|
+
{ timedOut: true, requestId }
|
|
644
|
+
);
|
|
645
|
+
}
|
|
646
|
+
const reason = failure.reason;
|
|
647
|
+
const detail = this.#redact(describe(reason));
|
|
648
|
+
const message = detail === "" ? `The ${method} request failed to complete.${hint}` : `The ${method} request failed to complete: ${detail}.${hint}`;
|
|
649
|
+
return new NetworkError(
|
|
650
|
+
message,
|
|
651
|
+
this.#isClean(reason) ? { cause: reason, requestId } : { requestId }
|
|
652
|
+
);
|
|
653
|
+
}
|
|
654
|
+
#redact(text) {
|
|
655
|
+
let out = text;
|
|
656
|
+
for (const secret of this.#secrets) {
|
|
657
|
+
out = out.split(secret).join(REDACTED);
|
|
658
|
+
}
|
|
659
|
+
return out;
|
|
660
|
+
}
|
|
661
|
+
#isClean(reason) {
|
|
662
|
+
let haystack;
|
|
663
|
+
try {
|
|
664
|
+
haystack = reason instanceof Error ? `${reason.message}
|
|
665
|
+
${reason.stack ?? ""}
|
|
666
|
+
${describe(reason.cause)}` : String(reason);
|
|
667
|
+
} catch {
|
|
668
|
+
return false;
|
|
669
|
+
}
|
|
670
|
+
return this.#secrets.every((secret) => !haystack.includes(secret));
|
|
671
|
+
}
|
|
672
|
+
/** Safe summary for `JSON.stringify` — never includes the credentials. */
|
|
673
|
+
toJSON() {
|
|
674
|
+
return {
|
|
675
|
+
baseUrl: this.#baseUrl,
|
|
676
|
+
country: this.#defaultCountry === "" ? null : this.#defaultCountry,
|
|
677
|
+
credentials: REDACTED
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
/** Safe summary for `console.log` / `util.inspect`. */
|
|
681
|
+
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
682
|
+
return `ApiClient ${JSON.stringify(this.toJSON())}`;
|
|
683
|
+
}
|
|
684
|
+
};
|
|
685
|
+
function handle(response, sentRequestId, allowEmpty) {
|
|
686
|
+
const { status, text, retryAfter, headers } = response;
|
|
687
|
+
const requestId = response.requestId ?? sentRequestId;
|
|
688
|
+
if (status >= 300 && status < 400) {
|
|
689
|
+
throw new ApiError(
|
|
690
|
+
`Unexpected redirect (HTTP ${status}). The SDK never follows redirects \u2014 check the base URL.`,
|
|
691
|
+
{ httpStatus: status, requestId, headers }
|
|
692
|
+
);
|
|
693
|
+
}
|
|
694
|
+
const envelope = decodeEnvelope(text);
|
|
695
|
+
const envStatus = envelope?.status;
|
|
696
|
+
if (status < 200 || status >= 400 || envStatus === "error" || envStatus === "failed") {
|
|
697
|
+
throw ApiError.fromEnvelope(status, envelope ?? {}, requestId, retryAfter, headers);
|
|
698
|
+
}
|
|
699
|
+
if (envelope === null) {
|
|
700
|
+
if (allowEmpty && text.trim() === "") {
|
|
701
|
+
return {};
|
|
702
|
+
}
|
|
703
|
+
throw new ApiError(
|
|
704
|
+
`Unexpected response (HTTP ${status}): the body is not a JSON object. The request was accepted: after a create call, look it up by your order id before sending it again.`,
|
|
705
|
+
{ code: "invalid_response", httpStatus: status, requestId, headers }
|
|
706
|
+
);
|
|
707
|
+
}
|
|
708
|
+
return envelope;
|
|
709
|
+
}
|
|
710
|
+
function isRetryableStatus(status, mode) {
|
|
711
|
+
if (status === 429) {
|
|
712
|
+
return true;
|
|
713
|
+
}
|
|
714
|
+
if (mode !== "idempotent") {
|
|
715
|
+
return false;
|
|
716
|
+
}
|
|
717
|
+
return status === 502 || status === 503 || status === 504;
|
|
718
|
+
}
|
|
719
|
+
function backoffMs(attempt, random) {
|
|
720
|
+
const ceiling = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempt);
|
|
721
|
+
return Math.round(ceiling / 2 + random() * (ceiling / 2));
|
|
722
|
+
}
|
|
723
|
+
function retryDelayMs(attempt, retryAfter, random) {
|
|
724
|
+
if (retryAfter === null) {
|
|
725
|
+
return backoffMs(attempt, random);
|
|
726
|
+
}
|
|
727
|
+
if (retryAfter > MAX_RETRY_AFTER_SECONDS) {
|
|
728
|
+
return null;
|
|
729
|
+
}
|
|
730
|
+
return Math.round(retryAfter * 1e3 + random() * 250);
|
|
731
|
+
}
|
|
732
|
+
function parseRetryAfter(value) {
|
|
733
|
+
if (value === null) {
|
|
734
|
+
return null;
|
|
735
|
+
}
|
|
736
|
+
const trimmed = value.trim();
|
|
737
|
+
if (/^\d{1,9}$/.test(trimmed)) {
|
|
738
|
+
return Number.parseInt(trimmed, 10);
|
|
739
|
+
}
|
|
740
|
+
if (trimmed === "" || !/[a-z]/i.test(trimmed)) {
|
|
741
|
+
return null;
|
|
742
|
+
}
|
|
743
|
+
const at = Date.parse(trimmed);
|
|
744
|
+
if (Number.isNaN(at)) {
|
|
745
|
+
return null;
|
|
746
|
+
}
|
|
747
|
+
return Math.max(0, Math.ceil((at - Date.now()) / 1e3));
|
|
748
|
+
}
|
|
749
|
+
function streamOf(response) {
|
|
750
|
+
const body = response.body;
|
|
751
|
+
if (typeof body !== "object" || body === null) {
|
|
752
|
+
return null;
|
|
753
|
+
}
|
|
754
|
+
const getReader = body.getReader;
|
|
755
|
+
return typeof getReader === "function" ? getReader.call(body) : null;
|
|
756
|
+
}
|
|
757
|
+
function tooLarge() {
|
|
758
|
+
return new Error("The response body exceeds the maximum accepted size");
|
|
759
|
+
}
|
|
760
|
+
async function readCapped(response) {
|
|
761
|
+
const declared = readHeader(response, "content-length");
|
|
762
|
+
if (declared !== null && /^\d+$/.test(declared.trim()) && Number(declared) > MAX_RESPONSE_BYTES) {
|
|
763
|
+
throw tooLarge();
|
|
764
|
+
}
|
|
765
|
+
const reader = streamOf(response);
|
|
766
|
+
if (reader === null) {
|
|
767
|
+
const text = await response.text();
|
|
768
|
+
if (text.length > MAX_RESPONSE_BYTES) {
|
|
769
|
+
throw tooLarge();
|
|
770
|
+
}
|
|
771
|
+
return text;
|
|
772
|
+
}
|
|
773
|
+
const chunks = [];
|
|
774
|
+
let total = 0;
|
|
775
|
+
for (; ; ) {
|
|
776
|
+
const { done, value } = await reader.read();
|
|
777
|
+
if (done) {
|
|
778
|
+
break;
|
|
779
|
+
}
|
|
780
|
+
if (value === void 0) {
|
|
781
|
+
continue;
|
|
782
|
+
}
|
|
783
|
+
total += value.byteLength;
|
|
784
|
+
if (total > MAX_RESPONSE_BYTES) {
|
|
785
|
+
await reader.cancel().catch(() => void 0);
|
|
786
|
+
throw tooLarge();
|
|
787
|
+
}
|
|
788
|
+
chunks.push(value);
|
|
789
|
+
}
|
|
790
|
+
const bytes = new Uint8Array(total);
|
|
791
|
+
let offset = 0;
|
|
792
|
+
for (const chunk of chunks) {
|
|
793
|
+
bytes.set(chunk, offset);
|
|
794
|
+
offset += chunk.byteLength;
|
|
795
|
+
}
|
|
796
|
+
return new TextDecoder().decode(bytes);
|
|
797
|
+
}
|
|
798
|
+
function readHeader(response, name) {
|
|
799
|
+
const headers = response.headers;
|
|
800
|
+
try {
|
|
801
|
+
if (typeof headers === "object" && headers !== null) {
|
|
802
|
+
const getter = headers.get;
|
|
803
|
+
if (typeof getter === "function") {
|
|
804
|
+
const value = getter.call(headers, name);
|
|
805
|
+
return typeof value === "string" && value !== "" ? value : null;
|
|
806
|
+
}
|
|
807
|
+
if (isRecord(headers)) {
|
|
808
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
809
|
+
if (key.toLowerCase() === name && typeof value === "string" && value !== "") {
|
|
810
|
+
return value;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
} catch {
|
|
816
|
+
}
|
|
817
|
+
return null;
|
|
818
|
+
}
|
|
819
|
+
function buildQuery(query) {
|
|
820
|
+
if (!query) {
|
|
821
|
+
return "";
|
|
822
|
+
}
|
|
823
|
+
const search = new URLSearchParams();
|
|
824
|
+
for (const [key, value] of Object.entries(query)) {
|
|
825
|
+
if (value === null || value === void 0) {
|
|
826
|
+
continue;
|
|
827
|
+
}
|
|
828
|
+
if (typeof value === "boolean") {
|
|
829
|
+
search.append(key, value ? "1" : "0");
|
|
830
|
+
} else if (value instanceof Date) {
|
|
831
|
+
search.append(key, value.toISOString());
|
|
832
|
+
} else {
|
|
833
|
+
search.append(key, String(value));
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
return search.toString();
|
|
837
|
+
}
|
|
838
|
+
function describe(reason) {
|
|
839
|
+
if (reason === void 0 || reason === null) {
|
|
840
|
+
return "";
|
|
841
|
+
}
|
|
842
|
+
if (!(reason instanceof Error)) {
|
|
843
|
+
return typeof reason === "string" ? reason : "";
|
|
844
|
+
}
|
|
845
|
+
const inner = reason.cause;
|
|
846
|
+
const code = isRecord(inner) || inner instanceof Error ? inner.code : reason.code;
|
|
847
|
+
return typeof code === "string" && code !== "" && !reason.message.includes(code) ? `${reason.message} (${code})` : reason.message;
|
|
848
|
+
}
|
|
849
|
+
function secretsOf(authorization) {
|
|
850
|
+
const token = authorization.replace(/^bearer\s+/i, "");
|
|
851
|
+
const parts = [token];
|
|
852
|
+
const colon = token.indexOf(":");
|
|
853
|
+
if (colon !== -1) {
|
|
854
|
+
parts.push(token.slice(colon + 1));
|
|
855
|
+
}
|
|
856
|
+
return parts.filter((part) => part.length >= 6);
|
|
857
|
+
}
|
|
858
|
+
function defaultSleep(ms) {
|
|
859
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
// src/resources/shared.ts
|
|
863
|
+
function expectResource(envelope, key) {
|
|
864
|
+
const resource = resourceOf(envelope, key);
|
|
865
|
+
if (resource === null) {
|
|
866
|
+
throw unexpected(envelope, `\`data.${key}\` is missing`);
|
|
867
|
+
}
|
|
868
|
+
return resource;
|
|
869
|
+
}
|
|
870
|
+
function expectData(envelope) {
|
|
871
|
+
const data = coerceObject(envelope, "data");
|
|
872
|
+
if (data === null) {
|
|
873
|
+
throw unexpected(envelope, "`data` is missing");
|
|
874
|
+
}
|
|
875
|
+
return data;
|
|
876
|
+
}
|
|
877
|
+
function expectRows(envelope, key) {
|
|
878
|
+
const data = expectData(envelope);
|
|
879
|
+
const rows = data[key];
|
|
880
|
+
if (!Array.isArray(rows) || !rows.every(isRecord)) {
|
|
881
|
+
throw unexpected(envelope, `\`data.${key}\` is missing or not a list of objects`);
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
function unexpected(envelope, what) {
|
|
885
|
+
return new ApiError(
|
|
886
|
+
`Unexpected response from the API: ${what}. The request was accepted: after a create call, look it up by your order id before sending it again.`,
|
|
887
|
+
{
|
|
888
|
+
code: "invalid_response",
|
|
889
|
+
httpStatus: 200,
|
|
890
|
+
requestId: coerceStr(envelope, "request_id")
|
|
891
|
+
}
|
|
892
|
+
);
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
// src/resources/balance.ts
|
|
896
|
+
var BalanceResource = class {
|
|
897
|
+
#api;
|
|
898
|
+
constructor(api) {
|
|
899
|
+
this.#api = api;
|
|
900
|
+
}
|
|
901
|
+
/** The merchant's wallet balance for the country. */
|
|
902
|
+
async get(options = {}) {
|
|
903
|
+
const env = await this.#api.request("GET", "balance", { country: options.country });
|
|
904
|
+
return hydrateBalance(expectData(env));
|
|
905
|
+
}
|
|
906
|
+
};
|
|
907
|
+
|
|
908
|
+
// src/resources/operators.ts
|
|
909
|
+
var Operators = class {
|
|
910
|
+
#api;
|
|
911
|
+
constructor(api) {
|
|
912
|
+
this.#api = api;
|
|
913
|
+
}
|
|
914
|
+
/** Real-time payment/transfer availability per operator (`operational`, `degraded`, `down`). */
|
|
915
|
+
async availability(options = {}) {
|
|
916
|
+
const env = await this.#api.request("GET", "operators/availability", {
|
|
917
|
+
country: options.country
|
|
918
|
+
});
|
|
919
|
+
return expectData(env);
|
|
920
|
+
}
|
|
921
|
+
/**
|
|
922
|
+
* Operator capabilities (OTP requirement, amount bounds, payer instructions).
|
|
923
|
+
* This is the authoritative list of operators for the country.
|
|
924
|
+
*/
|
|
925
|
+
async info(options = {}) {
|
|
926
|
+
const env = await this.#api.request("GET", "operators/info", {
|
|
927
|
+
country: options.country
|
|
928
|
+
});
|
|
929
|
+
return expectData(env);
|
|
930
|
+
}
|
|
931
|
+
};
|
|
932
|
+
|
|
933
|
+
// src/resources/paymentLinks.ts
|
|
934
|
+
var PaymentLinks = class {
|
|
935
|
+
#api;
|
|
936
|
+
constructor(api) {
|
|
937
|
+
this.#api = api;
|
|
938
|
+
}
|
|
939
|
+
/**
|
|
940
|
+
* Create a payment link (`title` + `amount` are required). No payment exists
|
|
941
|
+
* yet: payments are born when your customers pay on `link.url`.
|
|
942
|
+
*
|
|
943
|
+
* ⚠️ Never re-sent automatically on a timeout or a 5xx (it could create the
|
|
944
|
+
* link twice).
|
|
945
|
+
*/
|
|
946
|
+
async create(params, options = {}) {
|
|
947
|
+
const env = await this.#api.request("POST", "payments/links", {
|
|
948
|
+
country: options.country,
|
|
949
|
+
body: params
|
|
950
|
+
});
|
|
951
|
+
return hydratePaymentLink(expectResource(env, "payment_link"));
|
|
952
|
+
}
|
|
953
|
+
/**
|
|
954
|
+
* List your payment links, newest first. Filters: `status` (one or several,
|
|
955
|
+
* comma-separated), `usage`, `source`, `page`, `per_page` (max 100).
|
|
956
|
+
*/
|
|
957
|
+
async list(params = {}, options = {}) {
|
|
958
|
+
const env = await this.#api.request("GET", "payments/links", {
|
|
959
|
+
country: options.country,
|
|
960
|
+
query: params
|
|
961
|
+
});
|
|
962
|
+
expectRows(env, "payment_links");
|
|
963
|
+
return hydratePaymentLinkList(env);
|
|
964
|
+
}
|
|
965
|
+
/** Retrieve a payment link by its `PL-…` id or its slug. */
|
|
966
|
+
async get(id, options = {}) {
|
|
967
|
+
const env = await this.#api.request("GET", linkPath(id), {
|
|
968
|
+
country: options.country
|
|
969
|
+
});
|
|
970
|
+
return hydratePaymentLink(expectResource(env, "payment_link"));
|
|
971
|
+
}
|
|
972
|
+
/**
|
|
973
|
+
* Edit an active or paused link. Only `title`, `description`, `expires_at`
|
|
974
|
+
* and `redirect` can change; pass `null` to clear a nullable field.
|
|
975
|
+
*/
|
|
976
|
+
async update(id, params, options = {}) {
|
|
977
|
+
const env = await this.#api.request("PATCH", linkPath(id), {
|
|
978
|
+
country: options.country,
|
|
979
|
+
body: params
|
|
980
|
+
});
|
|
981
|
+
return hydratePaymentLink(expectResource(env, "payment_link"));
|
|
982
|
+
}
|
|
983
|
+
/** Cancel a link for good (active or paused → canceled). Cancelling twice is harmless. */
|
|
984
|
+
async cancel(id, options = {}) {
|
|
985
|
+
const env = await this.#api.request("DELETE", linkPath(id), {
|
|
986
|
+
country: options.country
|
|
987
|
+
});
|
|
988
|
+
return hydratePaymentLink(expectResource(env, "payment_link"));
|
|
989
|
+
}
|
|
990
|
+
/**
|
|
991
|
+
* Pause an active link: the checkout refuses new payers at once. A link in
|
|
992
|
+
* any other state is returned unchanged — check `status` on the result.
|
|
993
|
+
*/
|
|
994
|
+
async pause(id, options = {}) {
|
|
995
|
+
const env = await this.#api.request("POST", `${linkPath(id)}/pause`, {
|
|
996
|
+
country: options.country
|
|
997
|
+
});
|
|
998
|
+
return hydratePaymentLink(expectResource(env, "payment_link"));
|
|
999
|
+
}
|
|
1000
|
+
/**
|
|
1001
|
+
* Re-open a paused link. A link in any other state is returned unchanged —
|
|
1002
|
+
* check `status` on the result.
|
|
1003
|
+
*/
|
|
1004
|
+
async resume(id, options = {}) {
|
|
1005
|
+
const env = await this.#api.request("POST", `${linkPath(id)}/resume`, {
|
|
1006
|
+
country: options.country
|
|
1007
|
+
});
|
|
1008
|
+
return hydratePaymentLink(expectResource(env, "payment_link"));
|
|
1009
|
+
}
|
|
1010
|
+
/**
|
|
1011
|
+
* Payments made through a link, newest first — the country you call only.
|
|
1012
|
+
* A link open to several countries spreads its payments across them: call
|
|
1013
|
+
* each one (`{ country }`) for the full picture. `paymentLink.stats` on the
|
|
1014
|
+
* result is global either way.
|
|
1015
|
+
*/
|
|
1016
|
+
async listPayments(id, params = {}, options = {}) {
|
|
1017
|
+
const env = await this.#api.request("GET", `${linkPath(id)}/payments`, {
|
|
1018
|
+
country: options.country,
|
|
1019
|
+
query: params
|
|
1020
|
+
});
|
|
1021
|
+
expectRows(env, "payments");
|
|
1022
|
+
return hydratePaymentLinkPaymentList(env);
|
|
1023
|
+
}
|
|
1024
|
+
};
|
|
1025
|
+
function linkPath(id) {
|
|
1026
|
+
return `payments/links/${pathSegment(id, "payment link id")}`;
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
// src/resources/payments.ts
|
|
1030
|
+
var Payments = class {
|
|
1031
|
+
#api;
|
|
1032
|
+
constructor(api) {
|
|
1033
|
+
this.#api = api;
|
|
1034
|
+
}
|
|
1035
|
+
/**
|
|
1036
|
+
* Create a collection (payment): charge a payer now. Pass `operator`,
|
|
1037
|
+
* `phone_number`, `amount`, `order: { id }` and, for operators that take it
|
|
1038
|
+
* up-front, `otp`. Branch on the returned `status` (`SUCCESSFUL`,
|
|
1039
|
+
* `AWAITING_OTP`, `PROCESSING_OPERATOR`…).
|
|
1040
|
+
*
|
|
1041
|
+
* Optional `return_url` / `cancel_url`: where an operator that redirects the
|
|
1042
|
+
* payer (WAVE in Sénégal) sends them back. Only sent when given; validated
|
|
1043
|
+
* by the API (422 `ValidationError`). The return is not a proof of payment.
|
|
1044
|
+
*
|
|
1045
|
+
* This is always a direct payment. For a hosted checkout page where the
|
|
1046
|
+
* payer chooses how to pay, use `paymentLinks.create`.
|
|
1047
|
+
*
|
|
1048
|
+
* A refused payment rejects with `PaymentFailedError` (its `payment`
|
|
1049
|
+
* property holds the `FAILED` snapshot).
|
|
1050
|
+
*
|
|
1051
|
+
* ⚠️ Never re-sent automatically on a timeout or a 5xx (it could charge the
|
|
1052
|
+
* payer twice). Set `order.unique: true` and, if the outcome is unknown,
|
|
1053
|
+
* look the payment up with `payments.list({ order_id })` before retrying.
|
|
1054
|
+
*/
|
|
1055
|
+
async create(params, options = {}) {
|
|
1056
|
+
if (typeof params !== "object" || params === null) {
|
|
1057
|
+
throw new ConfigurationError("`payments.create` expects an object of parameters.");
|
|
1058
|
+
}
|
|
1059
|
+
const env = await this.#api.request("POST", "payments", {
|
|
1060
|
+
country: options.country,
|
|
1061
|
+
body: params
|
|
1062
|
+
});
|
|
1063
|
+
return hydratePayment(expectResource(env, "payment"));
|
|
1064
|
+
}
|
|
1065
|
+
/**
|
|
1066
|
+
* List payments, newest first. Filters: `status`, `operator`, `phone_number`,
|
|
1067
|
+
* `channel`, `order_id`, `amount` + `amount_operator`, `from_date` +
|
|
1068
|
+
* `to_date` (both or neither), `page`, `per_page` (max 200).
|
|
1069
|
+
*/
|
|
1070
|
+
async list(filters = {}, options = {}) {
|
|
1071
|
+
const env = await this.#api.request("GET", "payments", {
|
|
1072
|
+
country: options.country,
|
|
1073
|
+
query: filters
|
|
1074
|
+
});
|
|
1075
|
+
expectRows(env, "payments");
|
|
1076
|
+
return hydratePaymentList(env);
|
|
1077
|
+
}
|
|
1078
|
+
/**
|
|
1079
|
+
* Look up a payment by its `publicId` (UUID) or by your `order.id`.
|
|
1080
|
+
*
|
|
1081
|
+
* An id shaped like a UUID is always read as a `publicId`. If several
|
|
1082
|
+
* payments share the same order id, the first match is returned — use
|
|
1083
|
+
* `list({ order_id })` to get them all.
|
|
1084
|
+
*/
|
|
1085
|
+
async get(id, options = {}) {
|
|
1086
|
+
const env = await this.#api.request(
|
|
1087
|
+
"GET",
|
|
1088
|
+
`payments/${pathSegment(id, "payment id")}`,
|
|
1089
|
+
{
|
|
1090
|
+
country: options.country
|
|
1091
|
+
}
|
|
1092
|
+
);
|
|
1093
|
+
expectRows(env, "payments");
|
|
1094
|
+
const row = firstRow(env, "payments");
|
|
1095
|
+
if (row === null) {
|
|
1096
|
+
throw new NotFoundError(`No payment found for "${id}".`, {
|
|
1097
|
+
code: "resource_not_found",
|
|
1098
|
+
httpStatus: 404
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
return hydratePayment(row);
|
|
1102
|
+
}
|
|
1103
|
+
/**
|
|
1104
|
+
* Confirm a payment that is `AWAITING_OTP` with the code the payer received.
|
|
1105
|
+
* Pass the OTP as a string: a leading zero is significant.
|
|
1106
|
+
*
|
|
1107
|
+
* Only operators that send the OTP after creation use this step — today
|
|
1108
|
+
* MOOV in Burkina Faso; the endpoint exists on `bf` only.
|
|
1109
|
+
*/
|
|
1110
|
+
async confirmOtp(publicId, otp, options = {}) {
|
|
1111
|
+
const env = await this.#api.request(
|
|
1112
|
+
"POST",
|
|
1113
|
+
`payments/${pathSegment(publicId, "payment id")}/confirm-otp`,
|
|
1114
|
+
{ country: options.country, body: { otp: String(otp) } }
|
|
1115
|
+
);
|
|
1116
|
+
return hydratePayment(expectResource(env, "payment"));
|
|
1117
|
+
}
|
|
1118
|
+
/** Send the payer a new OTP for a payment that is still `AWAITING_OTP` (`bf` only, see `confirmOtp`). */
|
|
1119
|
+
async resendOtp(publicId, options = {}) {
|
|
1120
|
+
await this.#api.request(
|
|
1121
|
+
"POST",
|
|
1122
|
+
`payments/${pathSegment(publicId, "payment id")}/resend-otp`,
|
|
1123
|
+
{ country: options.country, allowEmpty: true }
|
|
1124
|
+
);
|
|
1125
|
+
}
|
|
1126
|
+
};
|
|
1127
|
+
|
|
1128
|
+
// src/resources/transfers.ts
|
|
1129
|
+
var Transfers = class {
|
|
1130
|
+
#api;
|
|
1131
|
+
constructor(api) {
|
|
1132
|
+
this.#api = api;
|
|
1133
|
+
}
|
|
1134
|
+
/**
|
|
1135
|
+
* Create a disbursement (transfer): `operator`, `phone_number`, `amount`,
|
|
1136
|
+
* `order: { id }`.
|
|
1137
|
+
*
|
|
1138
|
+
* A transfer whose status is `UNCERTAIN` was accepted but the operator has
|
|
1139
|
+
* not confirmed yet: do NOT send it again, the verdict arrives by webhook.
|
|
1140
|
+
* A refused transfer rejects with `TransferFailedError`, an underfunded one
|
|
1141
|
+
* with `InsufficientBalanceError`, a duplicate with `ConflictError`.
|
|
1142
|
+
*
|
|
1143
|
+
* ⚠️ Never re-sent automatically on a timeout or a 5xx (it could pay the
|
|
1144
|
+
* recipient twice). Set `order.unique: true` and, if the outcome is unknown,
|
|
1145
|
+
* look the transfer up with `transfers.list({ order_id })` before retrying.
|
|
1146
|
+
*/
|
|
1147
|
+
async create(params, options = {}) {
|
|
1148
|
+
const env = await this.#api.request("POST", "transfers", {
|
|
1149
|
+
country: options.country,
|
|
1150
|
+
body: params
|
|
1151
|
+
});
|
|
1152
|
+
return hydrateTransfer(expectResource(env, "transfer"));
|
|
1153
|
+
}
|
|
1154
|
+
/**
|
|
1155
|
+
* List transfers, newest first. Filters: `status`, `operator`,
|
|
1156
|
+
* `phone_number`, `channel`, `order_id`, `amount` + `amount_operator`,
|
|
1157
|
+
* `from_date` + `to_date` (both or neither), `page`, `per_page` (max 200).
|
|
1158
|
+
*/
|
|
1159
|
+
async list(filters = {}, options = {}) {
|
|
1160
|
+
const env = await this.#api.request("GET", "transfers", {
|
|
1161
|
+
country: options.country,
|
|
1162
|
+
query: filters
|
|
1163
|
+
});
|
|
1164
|
+
expectRows(env, "transfers");
|
|
1165
|
+
return hydrateTransferList(env);
|
|
1166
|
+
}
|
|
1167
|
+
/**
|
|
1168
|
+
* Look up a transfer by its `publicId` (UUID) or by your `order.id`.
|
|
1169
|
+
*
|
|
1170
|
+
* An id shaped like a UUID is always read as a `publicId`. If several
|
|
1171
|
+
* transfers share the same order id, the first match is returned — use
|
|
1172
|
+
* `list({ order_id })` to get them all.
|
|
1173
|
+
*/
|
|
1174
|
+
async get(id, options = {}) {
|
|
1175
|
+
const env = await this.#api.request(
|
|
1176
|
+
"GET",
|
|
1177
|
+
`transfers/${pathSegment(id, "transfer id")}`,
|
|
1178
|
+
{
|
|
1179
|
+
country: options.country
|
|
1180
|
+
}
|
|
1181
|
+
);
|
|
1182
|
+
expectRows(env, "transfers");
|
|
1183
|
+
const row = firstRow(env, "transfers");
|
|
1184
|
+
if (row === null) {
|
|
1185
|
+
throw new NotFoundError(`No transfer found for "${id}".`, {
|
|
1186
|
+
code: "resource_not_found",
|
|
1187
|
+
httpStatus: 404
|
|
1188
|
+
});
|
|
1189
|
+
}
|
|
1190
|
+
return hydrateTransfer(row);
|
|
1191
|
+
}
|
|
1192
|
+
};
|
|
1193
|
+
|
|
1194
|
+
// src/version.ts
|
|
1195
|
+
var VERSION = "2.0.0";
|
|
1196
|
+
|
|
1197
|
+
// src/client.ts
|
|
1198
|
+
var DEFAULT_BASE_URL = "https://hub.barkapay.com";
|
|
1199
|
+
var DEFAULT_TIMEOUT_MS = 4e4;
|
|
1200
|
+
var DEFAULT_MAX_RETRIES = 2;
|
|
1201
|
+
var MAX_RETRIES_CEILING = 10;
|
|
1202
|
+
var BarkaPay = class {
|
|
1203
|
+
static {
|
|
1204
|
+
this.VERSION = VERSION;
|
|
1205
|
+
}
|
|
1206
|
+
#api;
|
|
1207
|
+
constructor(options) {
|
|
1208
|
+
if (typeof options !== "object" || options === null) {
|
|
1209
|
+
throw new ConfigurationError(
|
|
1210
|
+
"Pass an options object: new BarkaPay({ apiKey, country })."
|
|
1211
|
+
);
|
|
1212
|
+
}
|
|
1213
|
+
const fetchFn = options.fetch ?? globalThis.fetch;
|
|
1214
|
+
if (typeof fetchFn !== "function") {
|
|
1215
|
+
throw new ConfigurationError(
|
|
1216
|
+
"No global `fetch` available. Use Node 18+ or pass a `fetch` implementation."
|
|
1217
|
+
);
|
|
1218
|
+
}
|
|
1219
|
+
this.#api = new ApiClient({
|
|
1220
|
+
fetchFn,
|
|
1221
|
+
authorization: buildAuthorization(options),
|
|
1222
|
+
baseUrl: normalizeBaseUrl(options.baseUrl, options.fetch !== void 0),
|
|
1223
|
+
defaultCountry: normalizeDefaultCountry(options.country),
|
|
1224
|
+
maxRetries: normalizeMaxRetries(options.maxRetries),
|
|
1225
|
+
timeoutMs: normalizeTimeout(options.timeoutMs),
|
|
1226
|
+
userAgent: buildUserAgent()
|
|
1227
|
+
});
|
|
1228
|
+
this.payments = new Payments(this.#api);
|
|
1229
|
+
this.paymentLinks = new PaymentLinks(this.#api);
|
|
1230
|
+
this.transfers = new Transfers(this.#api);
|
|
1231
|
+
this.balance = new BalanceResource(this.#api);
|
|
1232
|
+
this.operators = new Operators(this.#api);
|
|
1233
|
+
}
|
|
1234
|
+
/** Liveness check (also confirms your key works). */
|
|
1235
|
+
async ping(country) {
|
|
1236
|
+
const env = await this.#api.request("GET", "ping", { country });
|
|
1237
|
+
return expectData(env);
|
|
1238
|
+
}
|
|
1239
|
+
/** Current merchant + API application details (scopes, operator permissions). */
|
|
1240
|
+
async me(country) {
|
|
1241
|
+
const env = await this.#api.request("GET", "me", { country });
|
|
1242
|
+
return expectData(env);
|
|
1243
|
+
}
|
|
1244
|
+
/** Safe summary for `JSON.stringify` — never includes the API key. */
|
|
1245
|
+
toJSON() {
|
|
1246
|
+
return { sdk: "barkapay", version: VERSION, ...this.#api.toJSON() };
|
|
1247
|
+
}
|
|
1248
|
+
/** Safe summary for `console.log` / `util.inspect` — never includes the API key. */
|
|
1249
|
+
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
1250
|
+
return `BarkaPay ${JSON.stringify(this.toJSON())}`;
|
|
1251
|
+
}
|
|
1252
|
+
};
|
|
1253
|
+
var CREDENTIAL_PATTERN = /^[\x21-\x7e]+$/;
|
|
1254
|
+
function buildAuthorization(options) {
|
|
1255
|
+
let token = null;
|
|
1256
|
+
if (typeof options.apiKey === "string" && options.apiKey.trim() !== "") {
|
|
1257
|
+
token = options.apiKey.trim();
|
|
1258
|
+
if (/^bearer\s+/i.test(token)) {
|
|
1259
|
+
token = token.replace(/^bearer\s+/i, "").trim();
|
|
1260
|
+
}
|
|
1261
|
+
} else if (typeof options.keyId === "string" && typeof options.secret === "string" && options.keyId.trim() !== "" && options.secret.trim() !== "") {
|
|
1262
|
+
token = `${options.keyId.trim()}:${options.secret.trim()}`;
|
|
1263
|
+
}
|
|
1264
|
+
if (token === null || token === "") {
|
|
1265
|
+
throw new ConfigurationError(
|
|
1266
|
+
'Provide `apiKey` ("key_id:secret") or both `keyId` and `secret`.'
|
|
1267
|
+
);
|
|
1268
|
+
}
|
|
1269
|
+
if (!CREDENTIAL_PATTERN.test(token)) {
|
|
1270
|
+
throw new ConfigurationError(
|
|
1271
|
+
"The API key contains whitespace or non-ASCII characters. Copy it again from the dashboard."
|
|
1272
|
+
);
|
|
1273
|
+
}
|
|
1274
|
+
return `Bearer ${token}`;
|
|
1275
|
+
}
|
|
1276
|
+
function normalizeDefaultCountry(value) {
|
|
1277
|
+
if (value === void 0 || value === null) {
|
|
1278
|
+
return "";
|
|
1279
|
+
}
|
|
1280
|
+
if (typeof value === "string" && value.trim() === "") {
|
|
1281
|
+
return "";
|
|
1282
|
+
}
|
|
1283
|
+
return normalizeCountry(value);
|
|
1284
|
+
}
|
|
1285
|
+
function normalizeBaseUrl(value, customFetch) {
|
|
1286
|
+
if (value === void 0 || value === null) {
|
|
1287
|
+
return DEFAULT_BASE_URL;
|
|
1288
|
+
}
|
|
1289
|
+
if (typeof value !== "string") {
|
|
1290
|
+
throw new ConfigurationError("`baseUrl` must be a string.");
|
|
1291
|
+
}
|
|
1292
|
+
if (value.trim() === "") {
|
|
1293
|
+
return DEFAULT_BASE_URL;
|
|
1294
|
+
}
|
|
1295
|
+
let url;
|
|
1296
|
+
try {
|
|
1297
|
+
url = new URL(value.trim());
|
|
1298
|
+
} catch {
|
|
1299
|
+
throw new ConfigurationError(
|
|
1300
|
+
'`baseUrl` is not a valid URL (expected e.g. "https://hub.barkapay.com").'
|
|
1301
|
+
);
|
|
1302
|
+
}
|
|
1303
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
|
1304
|
+
throw new ConfigurationError("`baseUrl` must be an http(s) URL.");
|
|
1305
|
+
}
|
|
1306
|
+
if (url.username !== "" || url.password !== "") {
|
|
1307
|
+
throw new ConfigurationError("`baseUrl` must not embed credentials.");
|
|
1308
|
+
}
|
|
1309
|
+
if (url.search !== "" || url.hash !== "") {
|
|
1310
|
+
throw new ConfigurationError(
|
|
1311
|
+
"`baseUrl` must not carry a query string or a fragment."
|
|
1312
|
+
);
|
|
1313
|
+
}
|
|
1314
|
+
if (url.protocol === "http:") {
|
|
1315
|
+
const host = url.hostname.toLowerCase().replace(/\.$/, "");
|
|
1316
|
+
if (host === "barkapay.com" || host.endsWith(".barkapay.com")) {
|
|
1317
|
+
throw new ConfigurationError(
|
|
1318
|
+
`The barkapay API is only served over HTTPS: use ${DEFAULT_BASE_URL}.`
|
|
1319
|
+
);
|
|
1320
|
+
}
|
|
1321
|
+
if (!isLoopback(host)) {
|
|
1322
|
+
if (!customFetch) {
|
|
1323
|
+
throw new ConfigurationError(
|
|
1324
|
+
"`baseUrl` must use https:// (http:// is accepted for localhost only): the API key must never travel in clear text."
|
|
1325
|
+
);
|
|
1326
|
+
}
|
|
1327
|
+
warnInsecureBaseUrl();
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
return `${url.origin}${url.pathname}`.replace(/\/+$/, "");
|
|
1331
|
+
}
|
|
1332
|
+
function isLoopback(hostname) {
|
|
1333
|
+
return hostname === "localhost" || hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(hostname);
|
|
1334
|
+
}
|
|
1335
|
+
var insecureBaseUrlWarned = false;
|
|
1336
|
+
function warnInsecureBaseUrl() {
|
|
1337
|
+
if (insecureBaseUrlWarned) {
|
|
1338
|
+
return;
|
|
1339
|
+
}
|
|
1340
|
+
insecureBaseUrlWarned = true;
|
|
1341
|
+
if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
|
|
1342
|
+
process.emitWarning(
|
|
1343
|
+
"barkapay: `baseUrl` uses plain http \u2014 the API key will be sent unencrypted. Use https outside of local testing.",
|
|
1344
|
+
{ code: "BARKAPAY_INSECURE_BASE_URL" }
|
|
1345
|
+
);
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
function normalizeMaxRetries(value) {
|
|
1349
|
+
if (value === void 0) {
|
|
1350
|
+
return DEFAULT_MAX_RETRIES;
|
|
1351
|
+
}
|
|
1352
|
+
if (typeof value !== "number" || Number.isNaN(value)) {
|
|
1353
|
+
throw new ConfigurationError("`maxRetries` must be a number.");
|
|
1354
|
+
}
|
|
1355
|
+
return Math.min(MAX_RETRIES_CEILING, Math.max(0, Math.floor(value)));
|
|
1356
|
+
}
|
|
1357
|
+
function normalizeTimeout(value) {
|
|
1358
|
+
if (value === void 0) {
|
|
1359
|
+
return DEFAULT_TIMEOUT_MS;
|
|
1360
|
+
}
|
|
1361
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
1362
|
+
throw new ConfigurationError(
|
|
1363
|
+
"`timeoutMs` must be a positive number of milliseconds."
|
|
1364
|
+
);
|
|
1365
|
+
}
|
|
1366
|
+
return Math.ceil(value);
|
|
1367
|
+
}
|
|
1368
|
+
function buildUserAgent() {
|
|
1369
|
+
const node = typeof process !== "undefined" && typeof process.versions?.node === "string" ? ` node/${process.versions.node}` : "";
|
|
1370
|
+
return `barkapay-node/${VERSION}${node}`;
|
|
1371
|
+
}
|
|
1372
|
+
var WEBHOOK_SIGNATURE_HEADER = "Barkapay-Signature";
|
|
1373
|
+
var DEFAULT_TOLERANCE_SECONDS = 300;
|
|
1374
|
+
var MAX_HEADER_LENGTH = 4096;
|
|
1375
|
+
var MAX_SIGNATURES = 16;
|
|
1376
|
+
var HEX_SHA256 = /^[0-9a-f]{64}$/i;
|
|
1377
|
+
function verifyWebhookSignature(payload, signatureHeader, secret, toleranceSeconds = DEFAULT_TOLERANCE_SECONDS) {
|
|
1378
|
+
try {
|
|
1379
|
+
assertSignature(payload, signatureHeader, secret, toleranceSeconds);
|
|
1380
|
+
return true;
|
|
1381
|
+
} catch (error) {
|
|
1382
|
+
if (error instanceof SignatureVerificationError) {
|
|
1383
|
+
return false;
|
|
1384
|
+
}
|
|
1385
|
+
throw error;
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
function parseWebhook(payload, signatureHeader, secret, toleranceSeconds = DEFAULT_TOLERANCE_SECONDS) {
|
|
1389
|
+
const body = assertSignature(payload, signatureHeader, secret, toleranceSeconds);
|
|
1390
|
+
let decoded;
|
|
1391
|
+
try {
|
|
1392
|
+
decoded = JSON.parse(body.toString("utf8"));
|
|
1393
|
+
} catch {
|
|
1394
|
+
throw new SignatureVerificationError("Webhook payload is not valid JSON.");
|
|
1395
|
+
}
|
|
1396
|
+
if (!isRecord(decoded)) {
|
|
1397
|
+
throw new SignatureVerificationError("Webhook payload is not a JSON object.");
|
|
1398
|
+
}
|
|
1399
|
+
return decoded;
|
|
1400
|
+
}
|
|
1401
|
+
function assertSignature(payload, header, secret, tolerance) {
|
|
1402
|
+
const body = toBytes(payload);
|
|
1403
|
+
if (typeof secret !== "string" || secret === "") {
|
|
1404
|
+
throw new ConfigurationError(
|
|
1405
|
+
"A webhook secret (whsec_\u2026) is required to verify signatures."
|
|
1406
|
+
);
|
|
1407
|
+
}
|
|
1408
|
+
if (typeof tolerance !== "number" || !Number.isFinite(tolerance) || tolerance <= 0) {
|
|
1409
|
+
throw new ConfigurationError(
|
|
1410
|
+
"`toleranceSeconds` must be a positive, finite number of seconds (default 300)."
|
|
1411
|
+
);
|
|
1412
|
+
}
|
|
1413
|
+
const parsed = parseHeader(header);
|
|
1414
|
+
if (parsed === null) {
|
|
1415
|
+
throw new SignatureVerificationError(
|
|
1416
|
+
`Malformed or missing ${WEBHOOK_SIGNATURE_HEADER} header.`
|
|
1417
|
+
);
|
|
1418
|
+
}
|
|
1419
|
+
const { timestamp, signatures } = parsed;
|
|
1420
|
+
const expected = node_crypto.createHmac("sha256", secret).update(`${parsed.rawTimestamp}.`, "utf8").update(body).digest();
|
|
1421
|
+
let matched = false;
|
|
1422
|
+
for (const signature of signatures) {
|
|
1423
|
+
const candidate = Buffer.from(signature, "hex");
|
|
1424
|
+
if (candidate.length === expected.length && node_crypto.timingSafeEqual(candidate, expected)) {
|
|
1425
|
+
matched = true;
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
if (!matched) {
|
|
1429
|
+
throw new SignatureVerificationError("Webhook signature mismatch.");
|
|
1430
|
+
}
|
|
1431
|
+
if (Math.abs(Math.floor(Date.now() / 1e3) - timestamp) > tolerance) {
|
|
1432
|
+
throw new SignatureVerificationError(
|
|
1433
|
+
"Webhook timestamp is outside the tolerance window."
|
|
1434
|
+
);
|
|
1435
|
+
}
|
|
1436
|
+
return body;
|
|
1437
|
+
}
|
|
1438
|
+
function toBytes(payload) {
|
|
1439
|
+
if (typeof payload === "string") {
|
|
1440
|
+
return Buffer.from(payload, "utf8");
|
|
1441
|
+
}
|
|
1442
|
+
if (payload instanceof Uint8Array) {
|
|
1443
|
+
return Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength);
|
|
1444
|
+
}
|
|
1445
|
+
throw new ConfigurationError(
|
|
1446
|
+
'Webhook verification needs the RAW request body (a string or a Buffer), not a parsed object. With Express, mount `express.raw({ type: "application/json" })` on the webhook route instead of `express.json()`.'
|
|
1447
|
+
);
|
|
1448
|
+
}
|
|
1449
|
+
function parseHeader(header) {
|
|
1450
|
+
const value = Array.isArray(header) ? header.join(",") : header;
|
|
1451
|
+
if (typeof value !== "string" || value === "" || value.length > MAX_HEADER_LENGTH) {
|
|
1452
|
+
return null;
|
|
1453
|
+
}
|
|
1454
|
+
let timestamp = null;
|
|
1455
|
+
let rawTimestamp = "";
|
|
1456
|
+
const signatures = [];
|
|
1457
|
+
for (const element of value.split(",")) {
|
|
1458
|
+
const part = element.trim();
|
|
1459
|
+
const idx = part.indexOf("=");
|
|
1460
|
+
if (idx <= 0) {
|
|
1461
|
+
return null;
|
|
1462
|
+
}
|
|
1463
|
+
const key = part.slice(0, idx);
|
|
1464
|
+
const val = part.slice(idx + 1);
|
|
1465
|
+
if (key === "t") {
|
|
1466
|
+
if (timestamp !== null || !/^\d{1,12}$/.test(val)) {
|
|
1467
|
+
return null;
|
|
1468
|
+
}
|
|
1469
|
+
timestamp = Number.parseInt(val, 10);
|
|
1470
|
+
rawTimestamp = val;
|
|
1471
|
+
} else if (key === "v1") {
|
|
1472
|
+
if (!HEX_SHA256.test(val) || signatures.length >= MAX_SIGNATURES) {
|
|
1473
|
+
return null;
|
|
1474
|
+
}
|
|
1475
|
+
signatures.push(val);
|
|
1476
|
+
} else if (!/^[a-z][a-z0-9]*$/i.test(key)) {
|
|
1477
|
+
return null;
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
if (timestamp === null || timestamp <= 0 || signatures.length === 0) {
|
|
1481
|
+
return null;
|
|
1482
|
+
}
|
|
1483
|
+
return { timestamp, rawTimestamp, signatures };
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
exports.ApiError = ApiError;
|
|
1487
|
+
exports.AuthenticationError = AuthenticationError;
|
|
1488
|
+
exports.AuthorizationError = AuthorizationError;
|
|
1489
|
+
exports.BarkaPay = BarkaPay;
|
|
1490
|
+
exports.BarkaPayError = BarkaPayError;
|
|
1491
|
+
exports.ConfigurationError = ConfigurationError;
|
|
1492
|
+
exports.ConflictError = ConflictError;
|
|
1493
|
+
exports.DEFAULT_TOLERANCE_SECONDS = DEFAULT_TOLERANCE_SECONDS;
|
|
1494
|
+
exports.InsufficientBalanceError = InsufficientBalanceError;
|
|
1495
|
+
exports.NetworkError = NetworkError;
|
|
1496
|
+
exports.NotFoundError = NotFoundError;
|
|
1497
|
+
exports.PAYMENT_LINK_STATUSES = PAYMENT_LINK_STATUSES;
|
|
1498
|
+
exports.PAYMENT_STATUSES = PAYMENT_STATUSES;
|
|
1499
|
+
exports.PaymentFailedError = PaymentFailedError;
|
|
1500
|
+
exports.REASON_CODES = REASON_CODES;
|
|
1501
|
+
exports.RateLimitError = RateLimitError;
|
|
1502
|
+
exports.ServerError = ServerError;
|
|
1503
|
+
exports.ServiceUnavailableError = ServiceUnavailableError;
|
|
1504
|
+
exports.SignatureVerificationError = SignatureVerificationError;
|
|
1505
|
+
exports.TRANSFER_STATUSES = TRANSFER_STATUSES;
|
|
1506
|
+
exports.TransferFailedError = TransferFailedError;
|
|
1507
|
+
exports.VERSION = VERSION;
|
|
1508
|
+
exports.ValidationError = ValidationError;
|
|
1509
|
+
exports.WEBHOOK_SIGNATURE_HEADER = WEBHOOK_SIGNATURE_HEADER;
|
|
1510
|
+
exports.isPaymentStatusFinal = isPaymentStatusFinal;
|
|
1511
|
+
exports.isTransferStatusFinal = isTransferStatusFinal;
|
|
1512
|
+
exports.parseWebhook = parseWebhook;
|
|
1513
|
+
exports.verifyWebhookSignature = verifyWebhookSignature;
|