@nomba/node-sdk 0.0.0-stage → 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.
Files changed (201) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +550 -2
  3. package/dist/index.d.ts +86 -0
  4. package/dist/index.js +53 -0
  5. package/dist/interfaces/http/IHttpClient.d.ts +17 -0
  6. package/dist/interfaces/http/IHttpClient.js +5 -0
  7. package/dist/interfaces/http/index.d.ts +1 -0
  8. package/dist/interfaces/http/index.js +1 -0
  9. package/dist/interfaces/v1/accounts/IAccountsService.d.ts +24 -0
  10. package/dist/interfaces/v1/accounts/IAccountsService.js +5 -0
  11. package/dist/interfaces/v1/accounts/index.d.ts +1 -0
  12. package/dist/interfaces/v1/accounts/index.js +1 -0
  13. package/dist/interfaces/v1/betting/IBettingService.d.ts +11 -0
  14. package/dist/interfaces/v1/betting/IBettingService.js +5 -0
  15. package/dist/interfaces/v1/betting/index.d.ts +1 -0
  16. package/dist/interfaces/v1/betting/index.js +1 -0
  17. package/dist/interfaces/v1/cable/ICableService.d.ts +11 -0
  18. package/dist/interfaces/v1/cable/ICableService.js +5 -0
  19. package/dist/interfaces/v1/cable/index.d.ts +1 -0
  20. package/dist/interfaces/v1/cable/index.js +1 -0
  21. package/dist/interfaces/v1/charge/IChargeService.d.ts +33 -0
  22. package/dist/interfaces/v1/charge/IChargeService.js +5 -0
  23. package/dist/interfaces/v1/charge/index.d.ts +1 -0
  24. package/dist/interfaces/v1/charge/index.js +1 -0
  25. package/dist/interfaces/v1/checkout/ICheckoutService.d.ts +30 -0
  26. package/dist/interfaces/v1/checkout/ICheckoutService.js +5 -0
  27. package/dist/interfaces/v1/checkout/index.d.ts +1 -0
  28. package/dist/interfaces/v1/checkout/index.js +1 -0
  29. package/dist/interfaces/v1/data/IDataService.d.ts +9 -0
  30. package/dist/interfaces/v1/data/IDataService.js +5 -0
  31. package/dist/interfaces/v1/data/index.d.ts +1 -0
  32. package/dist/interfaces/v1/data/index.js +1 -0
  33. package/dist/interfaces/v1/direct-debits/IDirectDebitsService.d.ts +31 -0
  34. package/dist/interfaces/v1/direct-debits/IDirectDebitsService.js +5 -0
  35. package/dist/interfaces/v1/direct-debits/index.d.ts +1 -0
  36. package/dist/interfaces/v1/direct-debits/index.js +1 -0
  37. package/dist/interfaces/v1/electricity/IElectricityService.d.ts +11 -0
  38. package/dist/interfaces/v1/electricity/IElectricityService.js +5 -0
  39. package/dist/interfaces/v1/electricity/index.d.ts +1 -0
  40. package/dist/interfaces/v1/electricity/index.js +1 -0
  41. package/dist/interfaces/v1/globals/collections/IGlobalCollectionsService.d.ts +14 -0
  42. package/dist/interfaces/v1/globals/collections/IGlobalCollectionsService.js +5 -0
  43. package/dist/interfaces/v1/globals/collections/index.d.ts +1 -0
  44. package/dist/interfaces/v1/globals/collections/index.js +1 -0
  45. package/dist/interfaces/v1/globals/payouts/IGlobalPayoutService.d.ts +30 -0
  46. package/dist/interfaces/v1/globals/payouts/IGlobalPayoutService.js +5 -0
  47. package/dist/interfaces/v1/globals/payouts/index.d.ts +1 -0
  48. package/dist/interfaces/v1/globals/payouts/index.js +1 -0
  49. package/dist/interfaces/v1/requery/IRequeryService.d.ts +17 -0
  50. package/dist/interfaces/v1/requery/IRequeryService.js +5 -0
  51. package/dist/interfaces/v1/requery/index.d.ts +1 -0
  52. package/dist/interfaces/v1/requery/index.js +1 -0
  53. package/dist/interfaces/v1/terminals/ITerminalsService.d.ts +18 -0
  54. package/dist/interfaces/v1/terminals/ITerminalsService.js +5 -0
  55. package/dist/interfaces/v1/terminals/index.d.ts +1 -0
  56. package/dist/interfaces/v1/terminals/index.js +1 -0
  57. package/dist/interfaces/v1/transactions/ITransactionsService.d.ts +34 -0
  58. package/dist/interfaces/v1/transactions/ITransactionsService.js +5 -0
  59. package/dist/interfaces/v1/transactions/index.d.ts +1 -0
  60. package/dist/interfaces/v1/transactions/index.js +1 -0
  61. package/dist/interfaces/v1/virtual-accounts/IVirtualAccountsService.d.ts +27 -0
  62. package/dist/interfaces/v1/virtual-accounts/IVirtualAccountsService.js +5 -0
  63. package/dist/interfaces/v1/virtual-accounts/index.d.ts +1 -0
  64. package/dist/interfaces/v1/virtual-accounts/index.js +1 -0
  65. package/dist/interfaces/v1/webhooks/IWebhooksService.d.ts +21 -0
  66. package/dist/interfaces/v1/webhooks/IWebhooksService.js +5 -0
  67. package/dist/interfaces/v1/webhooks/index.d.ts +1 -0
  68. package/dist/interfaces/v1/webhooks/index.js +1 -0
  69. package/dist/interfaces/v2/airtime/IAirtimeV2Service.d.ts +12 -0
  70. package/dist/interfaces/v2/airtime/IAirtimeV2Service.js +5 -0
  71. package/dist/interfaces/v2/airtime/index.d.ts +1 -0
  72. package/dist/interfaces/v2/airtime/index.js +1 -0
  73. package/dist/interfaces/v2/betting/IBettingV2Service.d.ts +12 -0
  74. package/dist/interfaces/v2/betting/IBettingV2Service.js +5 -0
  75. package/dist/interfaces/v2/betting/index.d.ts +1 -0
  76. package/dist/interfaces/v2/betting/index.js +1 -0
  77. package/dist/interfaces/v2/cable/ICableV2Service.d.ts +12 -0
  78. package/dist/interfaces/v2/cable/ICableV2Service.js +5 -0
  79. package/dist/interfaces/v2/cable/index.d.ts +1 -0
  80. package/dist/interfaces/v2/cable/index.js +1 -0
  81. package/dist/interfaces/v2/data/IDataV2Service.d.ts +12 -0
  82. package/dist/interfaces/v2/data/IDataV2Service.js +5 -0
  83. package/dist/interfaces/v2/data/index.d.ts +1 -0
  84. package/dist/interfaces/v2/data/index.js +1 -0
  85. package/dist/interfaces/v2/electricity/IElectricityV2Service.d.ts +12 -0
  86. package/dist/interfaces/v2/electricity/IElectricityV2Service.js +5 -0
  87. package/dist/interfaces/v2/electricity/index.d.ts +1 -0
  88. package/dist/interfaces/v2/electricity/index.js +1 -0
  89. package/dist/interfaces/v2/transfers/ITransfersService.d.ts +20 -0
  90. package/dist/interfaces/v2/transfers/ITransfersService.js +5 -0
  91. package/dist/interfaces/v2/transfers/index.d.ts +1 -0
  92. package/dist/interfaces/v2/transfers/index.js +1 -0
  93. package/dist/lib/errors.d.ts +62 -0
  94. package/dist/lib/errors.js +92 -0
  95. package/dist/lib/outcome.d.ts +18 -0
  96. package/dist/lib/outcome.js +107 -0
  97. package/dist/lib/paginate.d.ts +21 -0
  98. package/dist/lib/paginate.js +25 -0
  99. package/dist/lib/sdk-version.d.ts +5 -0
  100. package/dist/lib/sdk-version.generated.d.ts +1 -0
  101. package/dist/lib/sdk-version.generated.js +1 -0
  102. package/dist/lib/sdk-version.js +5 -0
  103. package/dist/lib/token-store.d.ts +49 -0
  104. package/dist/lib/token-store.js +26 -0
  105. package/dist/lib/util.d.ts +31 -0
  106. package/dist/lib/util.js +31 -0
  107. package/dist/lib/webhooks.d.ts +43 -0
  108. package/dist/lib/webhooks.js +64 -0
  109. package/dist/nomba.d.ts +63 -0
  110. package/dist/nomba.js +97 -0
  111. package/dist/services/http/http-client.service.d.ts +27 -0
  112. package/dist/services/http/http-client.service.js +317 -0
  113. package/dist/services/v1/accounts/accounts.service.d.ts +38 -0
  114. package/dist/services/v1/accounts/accounts.service.js +58 -0
  115. package/dist/services/v1/betting/betting.service.d.ts +16 -0
  116. package/dist/services/v1/betting/betting.service.js +21 -0
  117. package/dist/services/v1/cable/cable.service.d.ts +16 -0
  118. package/dist/services/v1/cable/cable.service.js +23 -0
  119. package/dist/services/v1/charge/charge.service.d.ts +52 -0
  120. package/dist/services/v1/charge/charge.service.js +99 -0
  121. package/dist/services/v1/checkout/checkout.service.d.ts +44 -0
  122. package/dist/services/v1/checkout/checkout.service.js +100 -0
  123. package/dist/services/v1/data/data.service.d.ts +14 -0
  124. package/dist/services/v1/data/data.service.js +16 -0
  125. package/dist/services/v1/direct-debits/direct-debits.service.d.ts +45 -0
  126. package/dist/services/v1/direct-debits/direct-debits.service.js +69 -0
  127. package/dist/services/v1/electricity/electricity.service.d.ts +16 -0
  128. package/dist/services/v1/electricity/electricity.service.js +21 -0
  129. package/dist/services/v1/globals/collections.service.d.ts +28 -0
  130. package/dist/services/v1/globals/collections.service.js +38 -0
  131. package/dist/services/v1/globals/payout.service.d.ts +45 -0
  132. package/dist/services/v1/globals/payout.service.js +95 -0
  133. package/dist/services/v1/requery/requery.service.d.ts +31 -0
  134. package/dist/services/v1/requery/requery.service.js +41 -0
  135. package/dist/services/v1/terminals/terminals.service.d.ts +38 -0
  136. package/dist/services/v1/terminals/terminals.service.js +69 -0
  137. package/dist/services/v1/transactions/transactions.service.d.ts +48 -0
  138. package/dist/services/v1/transactions/transactions.service.js +98 -0
  139. package/dist/services/v1/virtual-accounts/virtual-accounts.service.d.ts +41 -0
  140. package/dist/services/v1/virtual-accounts/virtual-accounts.service.js +56 -0
  141. package/dist/services/v1/webhooks/webhooks.service.d.ts +36 -0
  142. package/dist/services/v1/webhooks/webhooks.service.js +60 -0
  143. package/dist/services/v2/airtime/airtime.service.d.ts +18 -0
  144. package/dist/services/v2/airtime/airtime.service.js +35 -0
  145. package/dist/services/v2/betting/betting.service.d.ts +19 -0
  146. package/dist/services/v2/betting/betting.service.js +36 -0
  147. package/dist/services/v2/cable/cable.service.d.ts +19 -0
  148. package/dist/services/v2/cable/cable.service.js +36 -0
  149. package/dist/services/v2/data/data.service.d.ts +18 -0
  150. package/dist/services/v2/data/data.service.js +35 -0
  151. package/dist/services/v2/electricity/electricity.service.d.ts +19 -0
  152. package/dist/services/v2/electricity/electricity.service.js +36 -0
  153. package/dist/services/v2/transfers/transfers.service.d.ts +30 -0
  154. package/dist/services/v2/transfers/transfers.service.js +67 -0
  155. package/dist/types/common/common.types.d.ts +78 -0
  156. package/dist/types/common/common.types.js +5 -0
  157. package/dist/types/common/outcome.types.d.ts +53 -0
  158. package/dist/types/common/outcome.types.js +5 -0
  159. package/dist/types/v1/accounts/accounts.types.d.ts +37 -0
  160. package/dist/types/v1/accounts/accounts.types.js +8 -0
  161. package/dist/types/v1/betting/betting.types.d.ts +26 -0
  162. package/dist/types/v1/betting/betting.types.js +5 -0
  163. package/dist/types/v1/cable/cable.types.d.ts +24 -0
  164. package/dist/types/v1/cable/cable.types.js +5 -0
  165. package/dist/types/v1/charge/charge.types.d.ts +102 -0
  166. package/dist/types/v1/charge/charge.types.js +5 -0
  167. package/dist/types/v1/checkout/checkout.types.d.ts +139 -0
  168. package/dist/types/v1/checkout/checkout.types.js +5 -0
  169. package/dist/types/v1/data/data.types.d.ts +14 -0
  170. package/dist/types/v1/data/data.types.js +5 -0
  171. package/dist/types/v1/direct-debits/direct-debits.types.d.ts +104 -0
  172. package/dist/types/v1/direct-debits/direct-debits.types.js +5 -0
  173. package/dist/types/v1/electricity/electricity.types.d.ts +21 -0
  174. package/dist/types/v1/electricity/electricity.types.js +5 -0
  175. package/dist/types/v1/globals/collections.types.d.ts +49 -0
  176. package/dist/types/v1/globals/collections.types.js +5 -0
  177. package/dist/types/v1/globals/payout.types.d.ts +183 -0
  178. package/dist/types/v1/globals/payout.types.js +5 -0
  179. package/dist/types/v1/requery/requery.types.d.ts +49 -0
  180. package/dist/types/v1/requery/requery.types.js +5 -0
  181. package/dist/types/v1/terminals/terminals.types.d.ts +44 -0
  182. package/dist/types/v1/terminals/terminals.types.js +5 -0
  183. package/dist/types/v1/transactions/transactions.types.d.ts +87 -0
  184. package/dist/types/v1/transactions/transactions.types.js +5 -0
  185. package/dist/types/v1/virtual-accounts/virtual-accounts.types.d.ts +64 -0
  186. package/dist/types/v1/virtual-accounts/virtual-accounts.types.js +5 -0
  187. package/dist/types/v1/webhooks/webhooks.types.d.ts +54 -0
  188. package/dist/types/v1/webhooks/webhooks.types.js +5 -0
  189. package/dist/types/v2/airtime/airtime.types.d.ts +31 -0
  190. package/dist/types/v2/airtime/airtime.types.js +5 -0
  191. package/dist/types/v2/betting/betting.types.d.ts +33 -0
  192. package/dist/types/v2/betting/betting.types.js +5 -0
  193. package/dist/types/v2/cable/cable.types.d.ts +32 -0
  194. package/dist/types/v2/cable/cable.types.js +5 -0
  195. package/dist/types/v2/data/data.types.d.ts +32 -0
  196. package/dist/types/v2/data/data.types.js +5 -0
  197. package/dist/types/v2/electricity/electricity.types.d.ts +34 -0
  198. package/dist/types/v2/electricity/electricity.types.js +5 -0
  199. package/dist/types/v2/transfers/transfers.types.d.ts +99 -0
  200. package/dist/types/v2/transfers/transfers.types.js +5 -0
  201. package/package.json +42 -5
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @module nomba/lib/paginate
3
+ * @description Nomba SDK for Node.js
4
+ * @description Utility types and classes
5
+ * @author Nomba Financial Services
6
+ * @version 1.0.0
7
+ * @license MIT
8
+ * @copyright 2026 Nomba
9
+ * @homepage https://nomba.com
10
+ * @support https://nomba.com/support
11
+ * @repository https://github.com/kudi-inc/nomba-sdk-node
12
+ * @docs https://developer.nomba.com
13
+ */
14
+ export type PageParams = {
15
+ /** Page size, at most 50 (see docs/api-basics/pagination). */
16
+ limit?: number;
17
+ cursor?: string;
18
+ };
19
+ export declare const pathId: (v: string) => string;
20
+ export declare const pageQuery: <T extends {
21
+ cursor?: string;
22
+ }>(p: T) => T & {
23
+ cursor: string | undefined;
24
+ };
25
+ export declare const sleep: (ms: number) => Promise<void>;
26
+ export declare const assertKey: (key: string) => void;
27
+ /** A cursor-paginated list response: `{ results, cursor }`, with `cursor` empty on the last page. */
28
+ export type Page<T> = {
29
+ results?: T[];
30
+ cursor?: string;
31
+ };
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @module nomba/lib/paginate
3
+ * @description Nomba SDK for Node.js
4
+ * @description Utility types and classes
5
+ * @author Nomba Financial Services
6
+ * @version 1.0.0
7
+ * @license MIT
8
+ * @copyright 2026 Nomba
9
+ * @homepage https://nomba.com
10
+ * @support https://nomba.com/support
11
+ * @repository https://github.com/kudi-inc/nomba-sdk-node
12
+ * @docs https://developer.nomba.com
13
+ */
14
+ // Path ids come from callers; reject values that would change the endpoint ("", ".", "..").
15
+ export const pathId = (v) => {
16
+ if (!v || v === "." || v === "..")
17
+ throw new Error(`Invalid id "${v}"`);
18
+ return encodeURIComponent(v);
19
+ };
20
+ // The API returns cursor "" on the last page; the docs say to send a cursor only when given one.
21
+ export const pageQuery = (p) => ({
22
+ ...p,
23
+ cursor: p.cursor || undefined,
24
+ });
25
+ export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
26
+ // A header-safe idempotency key: printable ASCII, no spaces. Anything else would make fetch throw before
27
+ // sending, which would look like a network failure.
28
+ export const assertKey = (key) => {
29
+ if (!/^[\x21-\x7e]+$/.test(key))
30
+ throw new Error(`Invalid idempotency key "${key}": use printable ASCII without spaces`);
31
+ };
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @module nomba/lib/webhooks
3
+ * @description Nomba SDK for Node.js
4
+ * @description Webhook signature verification
5
+ * @author Nomba Financial Services
6
+ * @version 1.0.0
7
+ * @license MIT
8
+ * @copyright 2026 Nomba
9
+ * @homepage https://nomba.com
10
+ * @support https://nomba.com/support
11
+ * @repository https://github.com/kudi-inc/nomba-sdk-node
12
+ * @docs https://developer.nomba.com
13
+ * @see https://developer.nomba.com/docs/api-basics/webhook
14
+ */
15
+ /** The fields the signature covers. Everything else in the event is left as `unknown`. */
16
+ export interface WebhookEvent {
17
+ [key: string]: unknown;
18
+ /** e.g. payment_success, payment_failed, payout_success, payout_refund. */
19
+ event_type?: string;
20
+ requestId?: string;
21
+ data?: {
22
+ [key: string]: unknown;
23
+ merchant?: {
24
+ [key: string]: unknown;
25
+ userId?: string;
26
+ walletId?: string;
27
+ };
28
+ transaction?: {
29
+ [key: string]: unknown;
30
+ transactionId?: string;
31
+ type?: string;
32
+ time?: string;
33
+ responseCode?: string;
34
+ };
35
+ };
36
+ }
37
+ /**
38
+ * True when `signature` (the nomba-signature header) matches the event, signed with your dashboard's
39
+ * webhook signature key and the nomba-timestamp header. `body` is the raw request body (string or Buffer) or the parsed event.
40
+ * A missing or malformed signature or body returns false rather than throwing.
41
+ * The docs compare signatures case-insensitively, so this does too.
42
+ */
43
+ export declare function verifyWebhook(body: string | Buffer | WebhookEvent, signature: string | undefined, timestamp: string, secret: string): boolean;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * @module nomba/lib/webhooks
3
+ * @description Nomba SDK for Node.js
4
+ * @description Webhook signature verification
5
+ * @author Nomba Financial Services
6
+ * @version 1.0.0
7
+ * @license MIT
8
+ * @copyright 2026 Nomba
9
+ * @homepage https://nomba.com
10
+ * @support https://nomba.com/support
11
+ * @repository https://github.com/kudi-inc/nomba-sdk-node
12
+ * @docs https://developer.nomba.com
13
+ * @see https://developer.nomba.com/docs/api-basics/webhook
14
+ */
15
+ import { createHmac, timingSafeEqual } from "node:crypto";
16
+ /**
17
+ * The base64 HMAC-SHA256 of the signing string the docs define:
18
+ * event_type:requestId:userId:walletId:transactionId:type:time:responseCode:timestamp,
19
+ * with a missing field (or a responseCode of "null") as "".
20
+ */
21
+ function webhookSignature(event, secret, timestamp) {
22
+ const merchant = event.data?.merchant ?? {};
23
+ const tx = event.data?.transaction ?? {};
24
+ const responseCode = tx.responseCode === "null" ? "" : tx.responseCode;
25
+ const signed = [
26
+ event.event_type,
27
+ event.requestId,
28
+ merchant.userId,
29
+ merchant.walletId,
30
+ tx.transactionId,
31
+ tx.type,
32
+ tx.time,
33
+ responseCode,
34
+ timestamp,
35
+ ]
36
+ .map((v) => v || "")
37
+ .join(":");
38
+ return createHmac("sha256", secret).update(signed).digest("base64");
39
+ }
40
+ /**
41
+ * True when `signature` (the nomba-signature header) matches the event, signed with your dashboard's
42
+ * webhook signature key and the nomba-timestamp header. `body` is the raw request body (string or Buffer) or the parsed event.
43
+ * A missing or malformed signature or body returns false rather than throwing.
44
+ * The docs compare signatures case-insensitively, so this does too.
45
+ */
46
+ export function verifyWebhook(body, signature, timestamp, secret) {
47
+ if (typeof signature !== "string")
48
+ return false;
49
+ let event;
50
+ try {
51
+ event =
52
+ typeof body === "string" || Buffer.isBuffer(body)
53
+ ? JSON.parse(body.toString())
54
+ : body;
55
+ }
56
+ catch {
57
+ return false;
58
+ }
59
+ if (typeof event !== "object" || event === null)
60
+ return false;
61
+ const expected = Buffer.from(webhookSignature(event, secret, timestamp).toLowerCase());
62
+ const given = Buffer.from(signature.toLowerCase());
63
+ return expected.length === given.length && timingSafeEqual(expected, given);
64
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * @module nomba
3
+ * @description Composition root: builds the HTTP client and injects it into every service
4
+ */
5
+ import type { IHttpClient } from "./interfaces/http/IHttpClient.js";
6
+ import type { IAccountsService } from "./interfaces/v1/accounts/index.js";
7
+ import type { IBettingService } from "./interfaces/v1/betting/index.js";
8
+ import type { ICableService } from "./interfaces/v1/cable/index.js";
9
+ import type { IChargeService } from "./interfaces/v1/charge/index.js";
10
+ import type { ICheckoutService } from "./interfaces/v1/checkout/index.js";
11
+ import type { IDataService } from "./interfaces/v1/data/index.js";
12
+ import type { IDirectDebitsService } from "./interfaces/v1/direct-debits/index.js";
13
+ import type { IElectricityService } from "./interfaces/v1/electricity/index.js";
14
+ import type { IGlobalCollectionsService } from "./interfaces/v1/globals/collections/index.js";
15
+ import type { IGlobalPayoutService } from "./interfaces/v1/globals/payouts/index.js";
16
+ import type { IRequeryService } from "./interfaces/v1/requery/index.js";
17
+ import type { ITerminalsService } from "./interfaces/v1/terminals/index.js";
18
+ import type { ITransactionsService } from "./interfaces/v1/transactions/index.js";
19
+ import type { IVirtualAccountsService } from "./interfaces/v1/virtual-accounts/index.js";
20
+ import type { IWebhooksService } from "./interfaces/v1/webhooks/index.js";
21
+ import type { IAirtimeV2Service } from "./interfaces/v2/airtime/index.js";
22
+ import type { IBettingV2Service } from "./interfaces/v2/betting/index.js";
23
+ import type { ICableV2Service } from "./interfaces/v2/cable/index.js";
24
+ import type { IDataV2Service } from "./interfaces/v2/data/index.js";
25
+ import type { IElectricityV2Service } from "./interfaces/v2/electricity/index.js";
26
+ import type { ITransfersService } from "./interfaces/v2/transfers/index.js";
27
+ import type { TokenData } from "./lib/token-store.js";
28
+ import type { Environment, HttpMethod, HttpRequestOptions, NombaOptions } from "./types/common/common.types.js";
29
+ export declare class Nomba {
30
+ #private;
31
+ readonly accounts: IAccountsService;
32
+ readonly virtualAccounts: IVirtualAccountsService;
33
+ readonly checkout: ICheckoutService;
34
+ readonly charge: IChargeService;
35
+ readonly transfers: ITransfersService;
36
+ readonly requery: IRequeryService;
37
+ readonly directDebits: IDirectDebitsService;
38
+ readonly transactions: ITransactionsService;
39
+ readonly terminals: ITerminalsService;
40
+ readonly electricity: IElectricityV2Service;
41
+ readonly cable: ICableV2Service;
42
+ readonly betting: IBettingV2Service;
43
+ readonly airtime: IAirtimeV2Service;
44
+ readonly data: IDataV2Service;
45
+ readonly billElectricity: IElectricityService;
46
+ readonly billCable: ICableService;
47
+ readonly billBetting: IBettingService;
48
+ readonly billData: IDataService;
49
+ readonly globalCollections: IGlobalCollectionsService;
50
+ readonly globalPayout: IGlobalPayoutService;
51
+ readonly webhooks: IWebhooksService;
52
+ /** Pass `http` to replace the transport, e.g. in tests. */
53
+ constructor(options: NombaOptions, http?: IHttpClient);
54
+ get environment(): Environment;
55
+ /** POST /v1/auth/token/issue */
56
+ issueToken(): Promise<TokenData>;
57
+ /** POST /v1/auth/token/refresh */
58
+ refreshToken(): Promise<TokenData>;
59
+ /** POST /v1/auth/token/revoke. No-op if no token is held. */
60
+ revokeToken(): Promise<void>;
61
+ /** Authenticated call to any endpoint; returns the response `data`. */
62
+ request<T>(method: HttpMethod, path: string, options?: HttpRequestOptions): Promise<T>;
63
+ }
package/dist/nomba.js ADDED
@@ -0,0 +1,97 @@
1
+ /**
2
+ * @module nomba
3
+ * @description Composition root: builds the HTTP client and injects it into every service
4
+ */
5
+ import { HttpClient } from "./services/http/http-client.service.js";
6
+ import { AccountsService } from "./services/v1/accounts/accounts.service.js";
7
+ import { BettingService } from "./services/v1/betting/betting.service.js";
8
+ import { CableService } from "./services/v1/cable/cable.service.js";
9
+ import { ChargeService } from "./services/v1/charge/charge.service.js";
10
+ import { CheckoutService } from "./services/v1/checkout/checkout.service.js";
11
+ import { DataService } from "./services/v1/data/data.service.js";
12
+ import { DirectDebitsService } from "./services/v1/direct-debits/direct-debits.service.js";
13
+ import { ElectricityService } from "./services/v1/electricity/electricity.service.js";
14
+ import { GlobalCollectionsService } from "./services/v1/globals/collections.service.js";
15
+ import { GlobalPayoutService } from "./services/v1/globals/payout.service.js";
16
+ import { RequeryService } from "./services/v1/requery/requery.service.js";
17
+ import { TerminalsService } from "./services/v1/terminals/terminals.service.js";
18
+ import { TransactionsService } from "./services/v1/transactions/transactions.service.js";
19
+ import { VirtualAccountsService } from "./services/v1/virtual-accounts/virtual-accounts.service.js";
20
+ import { WebhooksService } from "./services/v1/webhooks/webhooks.service.js";
21
+ import { AirtimeV2Service } from "./services/v2/airtime/airtime.service.js";
22
+ import { BettingV2Service } from "./services/v2/betting/betting.service.js";
23
+ import { CableV2Service } from "./services/v2/cable/cable.service.js";
24
+ import { DataV2Service } from "./services/v2/data/data.service.js";
25
+ import { ElectricityV2Service } from "./services/v2/electricity/electricity.service.js";
26
+ import { TransfersService } from "./services/v2/transfers/transfers.service.js";
27
+ export class Nomba {
28
+ accounts;
29
+ virtualAccounts;
30
+ checkout;
31
+ charge;
32
+ transfers;
33
+ requery;
34
+ directDebits;
35
+ transactions;
36
+ terminals;
37
+ electricity;
38
+ cable;
39
+ betting;
40
+ airtime;
41
+ data;
42
+ // v1 bill validation services
43
+ billElectricity;
44
+ billCable;
45
+ billBetting;
46
+ billData;
47
+ globalCollections;
48
+ globalPayout;
49
+ webhooks;
50
+ #http;
51
+ /** Pass `http` to replace the transport, e.g. in tests. */
52
+ constructor(options, http = new HttpClient(options)) {
53
+ this.#http = http;
54
+ this.accounts = new AccountsService(http);
55
+ this.virtualAccounts = new VirtualAccountsService(http);
56
+ this.checkout = new CheckoutService(http);
57
+ this.charge = new ChargeService(http);
58
+ this.transfers = new TransfersService(http);
59
+ this.requery = new RequeryService(http);
60
+ this.directDebits = new DirectDebitsService(http);
61
+ this.transactions = new TransactionsService(http);
62
+ this.terminals = new TerminalsService(http);
63
+ // Electricity, cable, betting, airtime and data use v2 endpoints for payments
64
+ this.electricity = new ElectricityV2Service(http);
65
+ this.cable = new CableV2Service(http);
66
+ this.betting = new BettingV2Service(http);
67
+ this.airtime = new AirtimeV2Service(http);
68
+ this.data = new DataV2Service(http);
69
+ // v1 bill validation services (provider lists, lookups, plan fetching)
70
+ this.billElectricity = new ElectricityService(http);
71
+ this.billCable = new CableService(http);
72
+ this.billBetting = new BettingService(http);
73
+ this.billData = new DataService(http);
74
+ this.globalCollections = new GlobalCollectionsService(http);
75
+ this.globalPayout = new GlobalPayoutService(http);
76
+ this.webhooks = new WebhooksService(http);
77
+ }
78
+ get environment() {
79
+ return this.#http.environment;
80
+ }
81
+ /** POST /v1/auth/token/issue */
82
+ issueToken() {
83
+ return this.#http.issueToken();
84
+ }
85
+ /** POST /v1/auth/token/refresh */
86
+ refreshToken() {
87
+ return this.#http.refreshToken();
88
+ }
89
+ /** POST /v1/auth/token/revoke. No-op if no token is held. */
90
+ revokeToken() {
91
+ return this.#http.revokeToken();
92
+ }
93
+ /** Authenticated call to any endpoint; returns the response `data`. */
94
+ request(method, path, options) {
95
+ return this.#http.request(method, path, options);
96
+ }
97
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * @module nomba/services/http
3
+ * @description Authenticated HTTP transport: token lifecycle, retries, response envelope
4
+ */
5
+ import type { IHttpClient } from "../../interfaces/http/IHttpClient.js";
6
+ import { type TokenData } from "../../lib/token-store.js";
7
+ import type { Environment, HttpMethod, HttpRequestOptions, NombaOptions } from "../../types/common/common.types.js";
8
+ import type { OutcomeEvent } from "../../types/common/outcome.types.js";
9
+ export declare class HttpClient implements IHttpClient {
10
+ #private;
11
+ readonly environment: Environment;
12
+ constructor(options: NombaOptions);
13
+ /** POST /v1/auth/token/issue */
14
+ issueToken(): Promise<TokenData>;
15
+ /** POST /v1/auth/token/refresh */
16
+ refreshToken(): Promise<TokenData>;
17
+ /** POST /v1/auth/token/revoke. No-op if no token is held. */
18
+ revokeToken(): Promise<void>;
19
+ /**
20
+ * Authenticated call. Issues or refreshes the token as needed; returns the response `data`.
21
+ * `okCodes` lists the body codes that are not errors; the default is ["00"].
22
+ * Every non-GET call carries an idempotency key, so failures that leave the outcome unknown are retried
23
+ * safely, and surface as OutcomeUnknownError once retries run out.
24
+ */
25
+ request<T>(method: HttpMethod, path: string, { body, query, okCodes, idempotencyKey, codeField, descriptionField, envelope, }?: HttpRequestOptions): Promise<T>;
26
+ reportOutcome(event: OutcomeEvent): void;
27
+ }
@@ -0,0 +1,317 @@
1
+ /**
2
+ * @module nomba/services/http
3
+ * @description Authenticated HTTP transport: token lifecycle, retries, response envelope
4
+ */
5
+ import { randomUUID } from "node:crypto";
6
+ import { NombaError, OutcomeUnknownError, TokenError, } from "../../lib/errors.js";
7
+ import { SDK_VERSION } from "../../lib/sdk-version.js";
8
+ import { MemoryTokenStore, } from "../../lib/token-store.js";
9
+ import { assertKey, sleep } from "../../lib/util.js";
10
+ const BASE_URLS = {
11
+ production: "https://api.nomba.com",
12
+ sandbox: "https://sandbox.nomba.com",
13
+ };
14
+ // Docs: refresh the access_token at least 5 minutes before it expires.
15
+ const REFRESH_MARGIN_MS = 5 * 60_000;
16
+ // A failed store.set() is retried this many times (100ms, 200ms apart) before giving up on the shared copy.
17
+ const SET_RETRIES = 2;
18
+ export class HttpClient {
19
+ environment;
20
+ #options;
21
+ #baseUrl;
22
+ #store;
23
+ #pending;
24
+ // This process's copy of the latest token, used when the shared store is failing.
25
+ #local;
26
+ // True when the last store.set() failed, so #local is newer than whatever the store holds.
27
+ #unsynced = false;
28
+ constructor(options) {
29
+ this.#options = options;
30
+ this.#store = options.tokenStore ?? new MemoryTokenStore();
31
+ const env = options.environment ?? "production";
32
+ if (!Object.hasOwn(BASE_URLS, env))
33
+ throw new Error(`Unknown environment "${env}"; use "production" or "sandbox"`);
34
+ this.environment = env;
35
+ this.#baseUrl = BASE_URLS[env];
36
+ }
37
+ /** POST /v1/auth/token/issue */
38
+ issueToken() {
39
+ return this.#locked(() => this.#issue());
40
+ }
41
+ /** POST /v1/auth/token/refresh */
42
+ refreshToken() {
43
+ return this.#locked(async () => {
44
+ const t = await this.#read();
45
+ if (!t)
46
+ throw new Error("No token to refresh; call issueToken() first");
47
+ return this.#refresh(t);
48
+ });
49
+ }
50
+ /** POST /v1/auth/token/revoke. No-op if no token is held. */
51
+ revokeToken() {
52
+ return this.#locked(async () => {
53
+ const t = await this.#read();
54
+ if (!t)
55
+ return;
56
+ await this.#send("POST", "/v1/auth/token/revoke", {
57
+ body: {
58
+ clientId: this.#options.clientId,
59
+ access_token: t.access_token,
60
+ },
61
+ });
62
+ this.#local = undefined;
63
+ this.#unsynced = false;
64
+ try {
65
+ await this.#store.clear();
66
+ }
67
+ catch (e) {
68
+ this.#onStoreError(e);
69
+ }
70
+ });
71
+ }
72
+ /**
73
+ * Authenticated call. Issues or refreshes the token as needed; returns the response `data`.
74
+ * `okCodes` lists the body codes that are not errors; the default is ["00"].
75
+ * Every non-GET call carries an idempotency key, so failures that leave the outcome unknown are retried
76
+ * safely, and surface as OutcomeUnknownError once retries run out.
77
+ */
78
+ async request(method, path, { body, query, okCodes, idempotencyKey, codeField, descriptionField, envelope, } = {}) {
79
+ // The URL is base + path, so a path not starting with "/" (".evil.com", "@evil.com") would change the host
80
+ // and send the bearer token there. Checked before the token is even read.
81
+ if (!path.startsWith("/"))
82
+ throw new TypeError(`path must start with "/", like "/v1/...", got ${JSON.stringify(path)}`);
83
+ const qs = new URLSearchParams(Object.entries(query ?? {}).flatMap(([k, v]) => v === undefined ? [] : [[k, String(v)]])).toString();
84
+ const url = qs ? `${path}?${qs}` : path;
85
+ // One key for every attempt of this call, including the retry after a 401 token renewal.
86
+ const key = method === "GET" ? undefined : idempotencyKey || randomUUID();
87
+ if (key !== undefined)
88
+ assertKey(key);
89
+ const token = await this.#tokenForRequest();
90
+ try {
91
+ return await this.#send(method, url, {
92
+ body,
93
+ bearer: token,
94
+ okCodes,
95
+ idempotencyKey: key,
96
+ codeField,
97
+ descriptionField,
98
+ envelope,
99
+ });
100
+ }
101
+ catch (e) {
102
+ // Docs: a 401 signals the access_token expired; renew it and retry once.
103
+ if (!(e instanceof NombaError && e.status === 401))
104
+ throw e;
105
+ return this.#send(method, url, {
106
+ body,
107
+ bearer: await this.#tokenForRequest(token),
108
+ okCodes,
109
+ idempotencyKey: key,
110
+ codeField,
111
+ descriptionField,
112
+ envelope,
113
+ });
114
+ }
115
+ }
116
+ reportOutcome(event) {
117
+ this.#hook(() => this.#options.onOutcome?.(event));
118
+ }
119
+ // A caller's hook must never break a request: its errors are logged instead.
120
+ #hook(fn) {
121
+ try {
122
+ fn();
123
+ }
124
+ catch (e) {
125
+ console.warn("nomba: hook threw", e);
126
+ }
127
+ }
128
+ // The store's lock (if any) makes every auth call exclusive across instances.
129
+ #locked(fn) {
130
+ return this.#store.lock ? this.#store.lock(fn) : fn();
131
+ }
132
+ async #issue() {
133
+ return this.#save(await this.#send("POST", "/v1/auth/token/issue", {
134
+ body: {
135
+ grant_type: "client_credentials",
136
+ client_id: this.#options.clientId,
137
+ client_secret: this.#options.clientSecret,
138
+ },
139
+ }));
140
+ }
141
+ async #refresh(t) {
142
+ return this.#save(await this.#send("POST", "/v1/auth/token/refresh", {
143
+ body: { grant_type: "refresh_token", refresh_token: t.refresh_token },
144
+ bearer: t.access_token,
145
+ }));
146
+ }
147
+ #onStoreError(e) {
148
+ (this.#options.onStoreError ?? console.warn)(e);
149
+ }
150
+ async #save(token) {
151
+ // Nomba has already rotated the session, so this token must not be lost even if the store fails.
152
+ this.#local = token;
153
+ for (let attempt = 0;; attempt++) {
154
+ try {
155
+ await this.#store.set(token);
156
+ this.#unsynced = false;
157
+ return token;
158
+ }
159
+ catch (e) {
160
+ if (attempt === SET_RETRIES) {
161
+ this.#unsynced = true;
162
+ this.#onStoreError(e);
163
+ return token;
164
+ }
165
+ await sleep(100 * (attempt + 1));
166
+ }
167
+ }
168
+ }
169
+ /** The shared store's token, or this process's newer copy when the store is failing or behind. */
170
+ async #read() {
171
+ let stored;
172
+ try {
173
+ stored = await this.#store.get();
174
+ }
175
+ catch (e) {
176
+ this.#onStoreError(e);
177
+ return this.#local;
178
+ }
179
+ const local = this.#local;
180
+ // The store is authoritative unless our last write to it failed.
181
+ if (!local || !this.#unsynced)
182
+ return stored;
183
+ return !stored || Date.parse(local.expiresAt) > Date.parse(stored.expiresAt)
184
+ ? local
185
+ : stored;
186
+ }
187
+ /** A stored token that is not `rejected` and is not within 5 minutes of expiry, else renew. */
188
+ // Token failures happen before the request is sent, so they must never look like a request's outcome.
189
+ async #tokenForRequest(rejected) {
190
+ try {
191
+ return await this.#accessToken(rejected);
192
+ }
193
+ catch (e) {
194
+ throw new TokenError(e);
195
+ }
196
+ }
197
+ async #accessToken(rejected) {
198
+ const usable = (t) => !!t &&
199
+ t.access_token !== rejected &&
200
+ Date.parse(t.expiresAt) - Date.now() > REFRESH_MARGIN_MS;
201
+ const cached = await this.#read();
202
+ if (usable(cached))
203
+ return cached.access_token;
204
+ // One in-flight renewal per process; the lock covers other instances.
205
+ const joined = !!this.#pending;
206
+ this.#pending ??= this.#locked(async () => {
207
+ // Another instance may have renewed while we waited for the lock.
208
+ const current = await this.#read();
209
+ if (usable(current))
210
+ return current;
211
+ if (!current)
212
+ return this.#issue();
213
+ try {
214
+ return await this.#refresh(current);
215
+ }
216
+ catch (e) {
217
+ // Only a rejected refresh_token warrants a full re-issue; not network, 429 or 5xx errors.
218
+ if (e instanceof NombaError && [400, 401, 403].includes(e.status))
219
+ return this.#issue();
220
+ throw e;
221
+ }
222
+ }).finally(() => {
223
+ this.#pending = undefined;
224
+ });
225
+ const renewed = await this.#pending;
226
+ // A renewal started by a caller that did not know `rejected` may hand back that same token.
227
+ if (joined && renewed.access_token === rejected)
228
+ return this.#accessToken(rejected);
229
+ return renewed.access_token;
230
+ }
231
+ /**
232
+ * One logical request, retried where that is verified safe:
233
+ * - 429: never processed (rejected before reaching business logic), so always retried, on GETs and
234
+ * mutating calls alike.
235
+ * - GET: also retried on a timeout, network error, 5xx or 409, since reading data twice is harmless.
236
+ * - A mutating call (has an idempotencyKey): NOT auto-retried on a timeout, network error, 5xx or 409.
237
+ * Nomba uses merchantTxRef in the request body for idempotency, not headers. Retrying automatically
238
+ * with a different merchantTxRef could double-execute payments. Such a call fails after one attempt
239
+ * with OutcomeUnknownError; the caller decides whether and how to retry (using the same merchantTxRef).
240
+ * - Any other 4xx, or a non-ok body code: a definite rejection, thrown as is, no retry, for either kind.
241
+ */
242
+ async #send(method, path, { body, bearer, okCodes = ["00"], idempotencyKey, codeField = "code", descriptionField = "description", envelope = false, } = {}) {
243
+ const maxAttempts = this.#options.maxAttempts ?? 3;
244
+ const baseDelay = this.#options.retryDelayMs ?? 500;
245
+ const payload = body === undefined ? undefined : JSON.stringify(body);
246
+ for (let attempt = 1;; attempt++) {
247
+ try {
248
+ const hookPath = path.split("?")[0] ?? path;
249
+ this.#hook(() => this.#options.onRequest?.({ method, path: hookPath, attempt }));
250
+ const started = Date.now();
251
+ const res = await (this.#options.fetch ?? fetch)(this.#baseUrl + path, {
252
+ method,
253
+ headers: {
254
+ accountId: this.#options.accountId,
255
+ "X-Nomba-Sdk-Version": SDK_VERSION,
256
+ ...(payload === undefined
257
+ ? {}
258
+ : { "Content-Type": "application/json" }),
259
+ ...(bearer ? { Authorization: `Bearer ${bearer}` } : {}),
260
+ },
261
+ ...(payload === undefined ? {} : { body: payload }),
262
+ signal: AbortSignal.timeout(this.#options.timeoutMs ?? 30_000),
263
+ });
264
+ let json = null;
265
+ try {
266
+ json = (await res.json());
267
+ }
268
+ catch {
269
+ // A 2xx we could not read (cut off, timed out mid-body, not JSON): whether it took effect is unknown.
270
+ if (res.ok)
271
+ throw new Error(`Unreadable response (HTTP ${res.status})`);
272
+ }
273
+ // Docs: a 200 does not always mean success; the body's code field must be "00" (or one the
274
+ // caller accepts). Most endpoints call it `code`; codeField lets one call it something else.
275
+ const code = json?.[codeField];
276
+ this.#hook(() => this.#options.onResponse?.({
277
+ method,
278
+ path: hookPath,
279
+ attempt,
280
+ httpStatus: res.status,
281
+ ...(typeof code === "string" ? { code } : {}),
282
+ durationMs: Date.now() - started,
283
+ }));
284
+ if (!res.ok ||
285
+ !json ||
286
+ typeof code !== "string" ||
287
+ !okCodes.includes(code)) {
288
+ throw new NombaError(res.status, typeof code === "string" ? code : String(res.status), json?.[descriptionField] ?? res.statusText);
289
+ }
290
+ return (envelope ? { code, data: json.data } : json.data);
291
+ }
292
+ catch (e) {
293
+ const status = e instanceof NombaError ? e.status : undefined;
294
+ // 409 is "same key still being processed" (retry) or a real key conflict (definite): only the
295
+ // message tells them apart.
296
+ const inFlight = status === 409 &&
297
+ /being processed|retry/i.test(e.description);
298
+ if (status !== undefined &&
299
+ status < 500 &&
300
+ status !== 408 &&
301
+ status !== 429 &&
302
+ !inFlight)
303
+ throw e;
304
+ // Verified unsafe to retry a mutating call on anything but 429 (see #send's doc comment).
305
+ const safeToRepeat = status === 429 || method === "GET";
306
+ if (attempt < maxAttempts && safeToRepeat) {
307
+ const delay = baseDelay * 2 ** (attempt - 1);
308
+ await sleep(delay + Math.random() * delay * 0.2);
309
+ continue;
310
+ }
311
+ if (status === 429 || !idempotencyKey)
312
+ throw e;
313
+ throw new OutcomeUnknownError(method, path, idempotencyKey, attempt, e);
314
+ }
315
+ }
316
+ }
317
+ }