@nomba/node-sdk 0.3.0 → 0.4.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 (43) hide show
  1. package/README.md +46 -12
  2. package/dist/index.d.ts +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/interfaces/v1/globals/collections/IGlobalCollectionsService.d.ts +3 -1
  5. package/dist/interfaces/v1/globals/payouts/IGlobalPayoutService.d.ts +8 -6
  6. package/dist/lib/errors.d.ts +19 -0
  7. package/dist/lib/errors.js +23 -0
  8. package/dist/lib/outcome.d.ts +9 -3
  9. package/dist/lib/outcome.js +10 -4
  10. package/dist/lib/sdk-version.generated.d.ts +1 -1
  11. package/dist/lib/sdk-version.generated.js +1 -1
  12. package/dist/lib/util.d.ts +0 -1
  13. package/dist/lib/util.js +0 -6
  14. package/dist/services/http/http-client.service.js +4 -3
  15. package/dist/services/v1/betting/betting.service.d.ts +1 -0
  16. package/dist/services/v1/betting/betting.service.js +1 -0
  17. package/dist/services/v1/cable/cable.service.d.ts +1 -0
  18. package/dist/services/v1/cable/cable.service.js +1 -0
  19. package/dist/services/v1/checkout/checkout.service.js +1 -1
  20. package/dist/services/v1/globals/collections.service.d.ts +3 -1
  21. package/dist/services/v1/globals/collections.service.js +10 -5
  22. package/dist/services/v1/globals/payout.service.d.ts +12 -8
  23. package/dist/services/v1/globals/payout.service.js +19 -12
  24. package/dist/services/v1/requery/requery.service.d.ts +23 -5
  25. package/dist/services/v1/requery/requery.service.js +23 -5
  26. package/dist/services/v1/terminals/terminals.service.d.ts +37 -9
  27. package/dist/services/v1/terminals/terminals.service.js +38 -10
  28. package/dist/services/v1/transactions/transactions.service.d.ts +70 -12
  29. package/dist/services/v1/transactions/transactions.service.js +70 -12
  30. package/dist/services/v1/virtual-accounts/virtual-accounts.service.d.ts +48 -7
  31. package/dist/services/v1/virtual-accounts/virtual-accounts.service.js +48 -7
  32. package/dist/services/v1/webhooks/webhooks.service.d.ts +28 -6
  33. package/dist/services/v1/webhooks/webhooks.service.js +28 -6
  34. package/dist/services/v2/airtime/airtime.service.js +1 -1
  35. package/dist/services/v2/betting/betting.service.js +1 -1
  36. package/dist/services/v2/cable/cable.service.js +1 -1
  37. package/dist/services/v2/data/data.service.js +1 -1
  38. package/dist/services/v2/electricity/electricity.service.js +1 -1
  39. package/dist/services/v2/transfers/transfers.service.js +4 -4
  40. package/dist/types/common/common.types.d.ts +2 -1
  41. package/dist/types/v1/globals/collections.types.d.ts +3 -3
  42. package/dist/types/v1/globals/payout.types.d.ts +3 -3
  43. package/package.json +1 -1
package/README.md CHANGED
@@ -87,7 +87,7 @@ Store errors never fail a request — the SDK falls back to its in-process copy
87
87
 
88
88
  ## Resources
89
89
 
90
- Every resource hangs off the client (`nomba.<resource>`), and every method maps to one documented Nomba endpoint. Methods return the response's `data` directly, typed. Mutating methods take an optional last argument, `RequestOptions` (`{ idempotencyKey }`).
90
+ Every resource hangs off the client (`nomba.<resource>`), and every method maps to one documented Nomba endpoint. Methods return the response's `data` directly, typed. Each money-moving call takes its idempotency key from its params (`merchantTxRef`, `transactionId` or `idempotencyKey`), not from an options argument.
91
91
 
92
92
  | Resource | Covers |
93
93
  |---|---|
@@ -179,7 +179,7 @@ For building your own payment page on top of a checkout order.
179
179
  |---|---|---|
180
180
  | `listBanks()` | `GET /v1/transfers/banks` | |
181
181
  | `lookupBankAccount({ accountNumber, bankCode })` | `POST /v1/transfers/bank/lookup` | |
182
- | `bankTransfer(params)` | `POST /v2/transfers/bank` | Idempotency key defaults to `merchantTxRef` |
182
+ | `bankTransfer(params)` | `POST /v2/transfers/bank` | Idempotency key is `merchantTxRef` (required) |
183
183
  | `bankTransferFromSubAccount(subAccountId, params)` | `POST /v2/transfers/bank/{subAccountId}` | Nomba must enable this for your account |
184
184
  | `walletTransfer(params)` | `POST /v2/transfers/wallet` | To another Nomba account |
185
185
  | `walletTransferFromSubAccount(subAccountId, params)` | `POST /v2/transfers/wallet/{subAccountId}` | |
@@ -297,7 +297,7 @@ Each is its own product using **version 2** endpoints (payments only).
297
297
  | `buyData(params)` | `POST /v2/bill/data` | Select the bundle by `productId` |
298
298
  | `buyDataFromSubAccount(subAccountId, params)` | `POST /v2/bill/data/{subAccountId}` | |
299
299
 
300
- For both airtime and data, `network` is `GLO`, `MTN`, `9MOBILE` or `AIRTEL` (lowercase also accepted), and the idempotency key defaults to `merchantTxRef`.
300
+ For both airtime and data, `network` is `GLO`, `MTN`, `9MOBILE` or `AIRTEL` (lowercase also accepted), and the idempotency key is `merchantTxRef` (required).
301
301
 
302
302
  #### Version 2 bill payments
303
303
 
@@ -310,7 +310,7 @@ For both airtime and data, `network` is `GLO`, `MTN`, `9MOBILE` or `AIRTEL` (low
310
310
  | Method | Endpoint | Notes |
311
311
  |---|---|---|
312
312
  | `inflowProviders()` | `GET /v1/global-collection/drc/inflow/providers` | Use `code` as `topupVendor` |
313
- | `initiateInflow(params)` | `POST /v1/global-collection/inflow/initiate` | Prompts the customer to approve on their phone |
313
+ | `initiateInflow(params)` | `POST /v1/global-collection/inflow/initiate` | `idempotencyKey` required in body; prompts the customer to approve on their phone |
314
314
  | `getTransaction(transactionReference)` | `GET /v1/global-collection/transactions/{transactionId}` | `PENDING_APPROVAL` can still settle later |
315
315
 
316
316
  ### Global payout
@@ -323,8 +323,8 @@ For both airtime and data, `network` is `GLO`, `MTN`, `9MOBILE` or `AIRTEL` (low
323
323
  | `convert(params)` | `POST /v1/global-payout/money/convert` | A quote only; no money moves |
324
324
  | `institutionProviders({ isMobileMoney?, countryIsoCode? })` | `GET /v1/global-payout/bank/providers` | Banks or mobile money providers |
325
325
  | `paymentMethods({ destinationCountryIsoCode?, ... })` | `GET /v1/global-payout/payment-methods` | The fields each corridor requires |
326
- | `authorizeTransfer(params)` | `POST /v1/global-payout/transfer/authorize` | Cross-border transfer |
327
- | `authorizeExchange(params)` | `POST /v1/global-payout/exchange/authorize` | Between your own wallets |
326
+ | `authorizeTransfer(params)` | `POST /v1/global-payout/transfer/authorize` | `idempotencyKey` required in body; cross-border transfer |
327
+ | `authorizeExchange(params)` | `POST /v1/global-payout/exchange/authorize` | `idempotencyKey` required in body; between your own wallets |
328
328
  | `getTransaction(wtTransactionId)` | `GET /v1/global-payout/transactions/{transactionId}` | |
329
329
 
330
330
  ### Webhook troubleshooting
@@ -399,6 +399,7 @@ const payout = await nomba.globalPayout.authorizeTransfer({
399
399
  paymentMethod: "MobileMoney",
400
400
  accountType: "INDIVIDUAL",
401
401
  lockedExchangeRateId: rate.exchangeRateId,
402
+ idempotencyKey: "payout-ke-9981", // required; use a stable key for safe retries
402
403
  });
403
404
 
404
405
  const status = await nomba.globalPayout.getTransaction(payout.wtTransactionId);
@@ -406,6 +407,24 @@ const status = await nomba.globalPayout.getTransaction(payout.wtTransactionId);
406
407
 
407
408
  Call `nomba.globalPayout.paymentMethods({ destinationCountryIsoCode })` first to see which fields a corridor requires.
408
409
 
410
+ ### DRC mobile money collection
411
+
412
+ ```ts
413
+ const providers = await nomba.globalCollections.inflowProviders();
414
+
415
+ const inflow = await nomba.globalCollections.initiateInflow({
416
+ phoneNumber: "0980802000",
417
+ callbackUrl: "https://example.com/hook",
418
+ amount: 100,
419
+ currency: "CDF",
420
+ topupVendor: providers[0].code, // e.g. "AIRTEL"
421
+ idempotencyKey: "inflow-drc-1234", // required; use a stable key for safe retries
422
+ });
423
+
424
+ // Poll for status or wait for webhook
425
+ const status = await nomba.globalCollections.getTransaction(inflow.transactionReference);
426
+ ```
427
+
409
428
  ## Webhooks
410
429
 
411
430
  Verify every webhook before acting on it. Pass the raw request body, the `nomba-signature` and `nomba-timestamp` headers, and the signature key you set on the Nomba dashboard:
@@ -481,12 +500,15 @@ Methods that take outcome closures:
481
500
  ## Errors
482
501
 
483
502
  ```ts
484
- import { isPending, NombaError } from "@nomba/node-sdk";
503
+ import { IdempotencyKeyAbsentError, isPending, NombaError } from "@nomba/node-sdk";
485
504
 
486
505
  try {
487
506
  await nomba.transfers.bankTransfer(params);
488
507
  } catch (err) {
489
- if (isPending(err)) {
508
+ if (err instanceof IdempotencyKeyAbsentError) {
509
+ // Missing required idempotency key: err.field tells you which field (e.g. "merchantTxRef")
510
+ console.error(`Set ${err.field} in the request body for ${err.path}`);
511
+ } else if (isPending(err)) {
490
512
  // OutcomeUnknownError (no readable answer) or UnconfirmedOutcomeError (pending result without onPending closure).
491
513
  // It may still complete. Do NOT retry it as a new request: wait for the webhook or requery first.
492
514
  } else if (err instanceof NombaError) {
@@ -499,6 +521,7 @@ try {
499
521
 
500
522
  - **`NombaError`** — a definite, non-2xx (or non-"00" body code) response. Safe to treat as "did not happen."
501
523
  - **`TokenError`** — getting or renewing the access token failed, so the request was never sent and nothing happened on Nomba's side. `err.cause` holds the underlying error. It is never reported as a pending payment.
524
+ - **`IdempotencyKeyAbsentError`** — a money-moving operation was attempted without a valid idempotency key. The SDK refuses to generate random keys for these operations to prevent double disbursement. Provides `err.field` (the required field name, e.g. `"merchantTxRef"` or `"idempotencyKey"`) and `err.path` (the endpoint).
502
525
  - **`UnconfirmedOutcomeError`** — a money-moving call got a pending result (documented or undocumented) without an `onPending` closure to handle it. Also thrown when the `code` or `data.status` isn't documented for that endpoint (`err.reason` says which). Treat it as pending: wait for the webhook or requery. It carries `code`, `status`, `data` and `idempotencyKey`.
503
526
  - **`OutcomeUnknownError`** — thrown only for mutating calls (transfers, checkout orders, etc.) after a failure that doesn't reveal whether the operation was processed. **Never retry by sending the same request again** — check the transaction's real status first (via `requery`, or your webhook), and only resubmit with the same `idempotencyKey` once you know it wasn't processed.
504
527
 
@@ -521,22 +544,33 @@ await nomba.transfers.bankTransfer({
521
544
  });
522
545
  ```
523
546
 
524
- The SDK tracks `idempotencyKey` internally (defaults to `merchantTxRef` for these operations) for error reporting and `onOutcome` events, but **does not send it as a header** — Nomba's server-side idempotency relies solely on the `merchantTxRef` field in the request body.
547
+ The SDK tracks `idempotencyKey` internally (it is `merchantTxRef` for these operations, and an empty one throws `IdempotencyKeyAbsentError`) for error reporting and `onOutcome` events, but **does not send it as a header** — Nomba's server-side idempotency relies solely on the `merchantTxRef` field in the request body.
525
548
 
526
549
  > **Important:** The SDK does **not** auto-retry mutating calls on timeouts, network errors, 5xx, or 409 — only `GET` requests and 429 responses are retried automatically. A failed mutating call surfaces as `OutcomeUnknownError` so you can decide how to proceed safely: check the transaction status first (via webhook or requery), then retry with the **same** `merchantTxRef` if it wasn't processed, or use a new reference if you're changing the payment.
527
550
 
528
551
  ### Global Payout and Global Collections
529
552
 
530
- **These take an `idempotencyKey` in the request body** (not `merchantTxRef`), and Nomba documents that it deduplicates correctly: resending the same key returns the original transaction (`idempotentReplay: true`) instead of creating a new one. The SDK always sends one, generating a UUID if you don't provide it.
553
+ **These require an `idempotencyKey` in the request body** (not `merchantTxRef`), and Nomba documents that it deduplicates correctly: resending the same key returns the original transaction (`idempotentReplay: true`) instead of creating a new one. **You must always provide this key — the SDK never generates one for you** to prevent accidental double disbursement.
531
554
 
532
555
  ```ts
533
- await nomba.globalPayout.authorizeTransfer(params, {
534
- idempotencyKey: "stable-key-123", // optional; SDK generates UUID if omitted
556
+ await nomba.globalPayout.authorizeTransfer({
557
+ // ... other params
558
+ idempotencyKey: "stable-key-123", // required
535
559
  });
536
560
  ```
537
561
 
538
562
  After an `OutcomeUnknownError`, retry with `err.idempotencyKey`. If you change anything about the payment, use a new key.
539
563
 
564
+ ### Checkout, Charge, and Direct Debits
565
+
566
+ These operations track an idempotency key **internally only** — for error reporting (`OutcomeUnknownError.idempotencyKey`) and the `onOutcome` hook. The key is **not sent to Nomba** and does not affect server-side behavior.
567
+
568
+ - **Checkout**: Uses `orderReference` when provided; falls back to a generated UUID if omitted
569
+ - **Charge**: Uses `orderReference`, `transactionId`, or `tokenKey` depending on the method
570
+ - **Direct Debits**: Uses `merchantReference` for `createMandate`
571
+
572
+ Because these keys are only used locally for tracking, generating a UUID when none is provided is harmless — it does not risk double disbursement. `IdempotencyKeyAbsentError` is thrown only when the key is required: an empty `idempotencyKey` for Global Payout and Global Collections (sent to Nomba, which dedupes on it), and an empty `merchantTxRef` or `transactionId` for transfers, bill payments, terminal payment requests and checkout refunds.
573
+
540
574
  ## TypeScript
541
575
 
542
576
  Every parameter and response type is exported, so you can type your own code against them:
package/dist/index.d.ts CHANGED
@@ -32,7 +32,7 @@ export type * from "./interfaces/v2/cable/index.js";
32
32
  export type * from "./interfaces/v2/data/index.js";
33
33
  export type * from "./interfaces/v2/electricity/index.js";
34
34
  export type * from "./interfaces/v2/transfers/ITransfersService.js";
35
- export { isPending, NombaError, OutcomeUnknownError, TokenError, UnconfirmedOutcomeError, } from "./lib/errors.js";
35
+ export { IdempotencyKeyAbsentError, isPending, NombaError, OutcomeUnknownError, TokenError, UnconfirmedOutcomeError, } from "./lib/errors.js";
36
36
  export type { TokenData, TokenStore } from "./lib/token-store.js";
37
37
  export { MemoryTokenStore } from "./lib/token-store.js";
38
38
  export type { PageParams } from "./lib/util.js";
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@
10
10
  * @repository https://github.com/kudi-inc/nomba-sdk-node
11
11
  * @docs https://developer.nomba.com
12
12
  */
13
- export { isPending, NombaError, OutcomeUnknownError, TokenError, UnconfirmedOutcomeError, } from "./lib/errors.js";
13
+ export { IdempotencyKeyAbsentError, isPending, NombaError, OutcomeUnknownError, TokenError, UnconfirmedOutcomeError, } from "./lib/errors.js";
14
14
  export { MemoryTokenStore } from "./lib/token-store.js";
15
15
  export { verifyWebhook } from "./lib/webhooks.js";
16
16
  export { Nomba } from "./nomba.js";
@@ -12,8 +12,10 @@ export interface IGlobalCollectionsService {
12
12
  inflowProviders(): Promise<InflowProvider[]>;
13
13
  /**
14
14
  * `POST /v1/global-collection/inflow/initiate`. Prompts the customer to approve the charge on their phone.
15
- * @param params The inflow to initiate; `idempotencyKey` defaults to a generated one.
15
+ * @param params The inflow to initiate. Must include `idempotencyKey` — the SDK never generates
16
+ * one for you to prevent double collection.
16
17
  * @returns The initiated inflow, including its `transactionReference`.
18
+ * @throws {IdempotencyKeyAbsentError} `idempotencyKey` is missing or empty.
17
19
  * @throws {NombaError} The inflow params were rejected.
18
20
  * @throws {OutcomeUnknownError} The call failed in a way that does not say whether it was processed;
19
21
  * check the transaction status before retrying.
@@ -61,10 +61,11 @@ export interface IGlobalPayoutService {
61
61
  paymentMethods(params?: PaymentMethodsParams): Promise<PaymentMethodInfo[]>;
62
62
  /**
63
63
  * `POST /v1/global-payout/transfer/authorize`. Sends money cross-border.
64
- * @param params The transfer to authorize; `idempotencyKey` defaults to a generated one.
65
- * @param options Per-call overrides, including `idempotencyKey` and the `onSuccess`/`onPending`/`onFailed`
66
- * outcome handlers.
64
+ * @param params The transfer to authorize. Must include `idempotencyKey` — the SDK never generates
65
+ * one for you to prevent double disbursement.
66
+ * @param options Outcome closures (`onSuccess`, `onPending`, `onFailed`).
67
67
  * @returns The settled payout result (or the type `options` maps it to).
68
+ * @throws {IdempotencyKeyAbsentError} `idempotencyKey` is missing or empty.
68
69
  * @throws {NombaError} The transfer was rejected.
69
70
  * @throws {OutcomeUnknownError} The request outcome could not be determined and no `onPending` was supplied.
70
71
  * @throws {UnconfirmedOutcomeError} The response was pending or undocumented and no `onPending` was supplied.
@@ -72,10 +73,11 @@ export interface IGlobalPayoutService {
72
73
  authorizeTransfer<R = PayoutResult>(params: AuthorizeTransferParams, options?: CallOptions<PayoutResult, R>): Promise<PayoutResult | R>;
73
74
  /**
74
75
  * `POST /v1/global-payout/exchange/authorize`. Moves money between your own wallets in different currencies.
75
- * @param params The exchange to authorize; `idempotencyKey` defaults to a generated one.
76
- * @param options Per-call overrides, including `idempotencyKey` and the `onSuccess`/`onPending`/`onFailed`
77
- * outcome handlers.
76
+ * @param params The exchange to authorize. Must include `idempotencyKey` — the SDK never generates
77
+ * one for you to prevent double disbursement.
78
+ * @param options Outcome closures (`onSuccess`, `onPending`, `onFailed`).
78
79
  * @returns The settled payout result (or the type `options` maps it to).
80
+ * @throws {IdempotencyKeyAbsentError} `idempotencyKey` is missing or empty.
79
81
  * @throws {NombaError} The exchange was rejected.
80
82
  * @throws {OutcomeUnknownError} The request outcome could not be determined and no `onPending` was supplied.
81
83
  * @throws {UnconfirmedOutcomeError} The response was pending or undocumented and no `onPending` was supplied.
@@ -60,3 +60,22 @@ export declare const isPending: (e: unknown) => e is OutcomeUnknownError | Uncon
60
60
  export declare class TokenError extends Error {
61
61
  constructor(cause: unknown);
62
62
  }
63
+ /**
64
+ * Thrown when a money-moving request is attempted without a valid idempotency key. The SDK refuses to
65
+ * generate a random key for money-moving operations because doing so can lead to double disbursement:
66
+ * if the request times out and is retried, a new random key would create a duplicate transaction.
67
+ *
68
+ * Always provide a stable, caller-controlled idempotency key (e.g., `merchantTxRef`, `orderReference`,
69
+ * or `idempotencyKey`) so the same reference can be used to safely retry or requery the transaction.
70
+ */
71
+ export declare class IdempotencyKeyAbsentError extends Error {
72
+ /** The field name that must be set in the request body. */
73
+ readonly field: string;
74
+ /** The API endpoint being called. */
75
+ readonly path: string;
76
+ constructor(
77
+ /** The field name that must be set in the request body. */
78
+ field: string,
79
+ /** The API endpoint being called. */
80
+ path: string);
81
+ }
@@ -90,3 +90,26 @@ export class TokenError extends Error {
90
90
  this.name = "TokenError";
91
91
  }
92
92
  }
93
+ /**
94
+ * Thrown when a money-moving request is attempted without a valid idempotency key. The SDK refuses to
95
+ * generate a random key for money-moving operations because doing so can lead to double disbursement:
96
+ * if the request times out and is retried, a new random key would create a duplicate transaction.
97
+ *
98
+ * Always provide a stable, caller-controlled idempotency key (e.g., `merchantTxRef`, `orderReference`,
99
+ * or `idempotencyKey`) so the same reference can be used to safely retry or requery the transaction.
100
+ */
101
+ export class IdempotencyKeyAbsentError extends Error {
102
+ field;
103
+ path;
104
+ constructor(
105
+ /** The field name that must be set in the request body. */
106
+ field,
107
+ /** The API endpoint being called. */
108
+ path) {
109
+ super(`Idempotency key required: set "${field}" in the request body for ${path}. ` +
110
+ `The SDK does not generate random keys for money-moving operations to prevent double disbursement.`);
111
+ this.field = field;
112
+ this.path = path;
113
+ this.name = "IdempotencyKeyAbsentError";
114
+ }
115
+ }
@@ -26,12 +26,18 @@ export declare const classify: (table: OutcomeTable, code: string, status: strin
26
26
  * @param path The API endpoint path.
27
27
  * @param request The request body and query; `okCodes`, `envelope`, and `idempotencyKey` are set internally.
28
28
  * @param table Maps body codes and `data.status` values to outcomes; unlisted values are pending.
29
- * @param idempotencyKey Derived from params (e.g., `merchantTxRef`). Tracked in errors so callers know
30
- * which transaction to requery; not sent in headers.
29
+ * @param idempotency `value` is the idempotency key, derived from params (e.g., `merchantTxRef`). Tracked
30
+ * in errors so callers know which transaction to requery; not sent in headers. Must be non-empty.
31
+ * `field` is the name of the field in the request body that holds it (e.g., `"merchantTxRef"`). Used in
32
+ * error messages when the key is missing.
31
33
  * @param options Outcome closures: `onSuccess`, `onPending`, `onFailed`. Each transforms the result or error.
32
34
  * @returns The response `data`, or what the matching closure returns.
35
+ * @throws {IdempotencyKeyAbsentError} The idempotency key is missing or empty.
33
36
  * @throws {NombaError} A documented rejection (4xx body code).
34
37
  * @throws {OutcomeUnknownError} Transport failure — outcome unknown; requery before retrying.
35
38
  * @throws {UnconfirmedOutcomeError} Pending or undocumented response — do not retry without requerying.
36
39
  */
37
- export declare function settle<T, R = T>(http: IHttpClient, method: HttpMethod, path: string, request: Omit<HttpRequestOptions, "okCodes" | "envelope" | "idempotencyKey">, table: OutcomeTable, idempotencyKey: string, options?: OutcomeHandlers<T, R>): Promise<T | R>;
40
+ export declare function settle<T, R = T>(http: IHttpClient, method: HttpMethod, path: string, request: Omit<HttpRequestOptions, "okCodes" | "envelope" | "idempotencyKey">, table: OutcomeTable, { field: idempotencyField, value: idempotencyKey, }: {
41
+ field: string;
42
+ value: string;
43
+ }, options?: OutcomeHandlers<T, R>): Promise<T | R>;
@@ -2,7 +2,7 @@
2
2
  * @module nomba/lib/outcome
3
3
  * @description Classifies a money-moving call as success, pending or failed, using only documented values
4
4
  */
5
- import { isPending, NombaError, OutcomeUnknownError, UnconfirmedOutcomeError, } from "./errors.js";
5
+ import { IdempotencyKeyAbsentError, isPending, NombaError, OutcomeUnknownError, UnconfirmedOutcomeError, } from "./errors.js";
6
6
  /** Documented 4xx body codes (docs/api-basics/response-codes): definite rejections, safe to report as failed. */
7
7
  export const REJECTED = {
8
8
  "400": "failed",
@@ -44,15 +44,21 @@ const defaultStatusOf = (data) => {
44
44
  * @param path The API endpoint path.
45
45
  * @param request The request body and query; `okCodes`, `envelope`, and `idempotencyKey` are set internally.
46
46
  * @param table Maps body codes and `data.status` values to outcomes; unlisted values are pending.
47
- * @param idempotencyKey Derived from params (e.g., `merchantTxRef`). Tracked in errors so callers know
48
- * which transaction to requery; not sent in headers.
47
+ * @param idempotency `value` is the idempotency key, derived from params (e.g., `merchantTxRef`). Tracked
48
+ * in errors so callers know which transaction to requery; not sent in headers. Must be non-empty.
49
+ * `field` is the name of the field in the request body that holds it (e.g., `"merchantTxRef"`). Used in
50
+ * error messages when the key is missing.
49
51
  * @param options Outcome closures: `onSuccess`, `onPending`, `onFailed`. Each transforms the result or error.
50
52
  * @returns The response `data`, or what the matching closure returns.
53
+ * @throws {IdempotencyKeyAbsentError} The idempotency key is missing or empty.
51
54
  * @throws {NombaError} A documented rejection (4xx body code).
52
55
  * @throws {OutcomeUnknownError} Transport failure — outcome unknown; requery before retrying.
53
56
  * @throws {UnconfirmedOutcomeError} Pending or undocumented response — do not retry without requerying.
54
57
  */
55
- export async function settle(http, method, path, request, table, idempotencyKey, options = {}) {
58
+ export async function settle(http, method, path, request, table, { field: idempotencyField, value: idempotencyKey, }, options = {}) {
59
+ if (typeof idempotencyKey !== "string" || !idempotencyKey.trim()) {
60
+ throw new IdempotencyKeyAbsentError(idempotencyField, path);
61
+ }
56
62
  const { onSuccess, onPending, onFailed } = options;
57
63
  const report = (outcome, code, status, key = idempotencyKey) => http.reportOutcome({
58
64
  method,
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "0.3.0";
1
+ export declare const SDK_VERSION = "0.4.0";
@@ -1 +1 @@
1
- export const SDK_VERSION = "0.3.0";
1
+ export const SDK_VERSION = "0.4.0";
@@ -23,7 +23,6 @@ export declare const pageQuery: <T extends {
23
23
  cursor: string | undefined;
24
24
  };
25
25
  export declare const sleep: (ms: number) => Promise<void>;
26
- export declare const assertKey: (key: string) => void;
27
26
  /** A cursor-paginated list response: `{ results, cursor }`, with `cursor` empty on the last page. */
28
27
  export type Page<T> = {
29
28
  results?: T[];
package/dist/lib/util.js CHANGED
@@ -23,9 +23,3 @@ export const pageQuery = (p) => ({
23
23
  cursor: p.cursor || undefined,
24
24
  });
25
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
- };
@@ -6,7 +6,7 @@ import { randomUUID } from "node:crypto";
6
6
  import { NombaError, OutcomeUnknownError, TokenError, } from "../../lib/errors.js";
7
7
  import { SDK_VERSION } from "../../lib/sdk-version.js";
8
8
  import { MemoryTokenStore, } from "../../lib/token-store.js";
9
- import { assertKey, sleep } from "../../lib/util.js";
9
+ import { sleep } from "../../lib/util.js";
10
10
  const BASE_URLS = {
11
11
  production: "https://api.nomba.com",
12
12
  sandbox: "https://sandbox.nomba.com",
@@ -116,9 +116,10 @@ export class HttpClient {
116
116
  const qs = new URLSearchParams(Object.entries(query ?? {}).flatMap(([k, v]) => v === undefined ? [] : [[k, String(v)]])).toString();
117
117
  const url = qs ? `${path}?${qs}` : path;
118
118
  // One key for every attempt of this call, including the retry after a 401 token renewal.
119
+ // The key is only tracked internally for error reporting (OutcomeUnknownError) and hooks (onOutcome);
120
+ // it is never sent in headers. User-provided values (orderReference, tokenKey, etc.) can contain
121
+ // any characters.
119
122
  const key = method === "GET" ? undefined : idempotencyKey || randomUUID();
120
- if (key !== undefined)
121
- assertKey(key);
122
123
  const token = await this.#tokenForRequest();
123
124
  try {
124
125
  return await this.#send(method, url, {
@@ -6,6 +6,7 @@
6
6
  import type { IHttpClient } from "../../../interfaces/http/IHttpClient.js";
7
7
  import type { IBettingService } from "../../../interfaces/v1/betting/index.js";
8
8
  import type { BettingCustomerLookupParams, BettingCustomerLookupResult, BettingProvidersResult } from "../../../types/v1/betting/betting.types.js";
9
+ /** Betting lookups (v1): provider listing and customer lookup. Use BettingV2Service for payments. */
9
10
  export declare class BettingService implements IBettingService {
10
11
  private readonly http;
11
12
  constructor(http: IHttpClient);
@@ -3,6 +3,7 @@
3
3
  * @description Betting (v1): GET /v1/bill/betting/providers, GET /v1/bill/betting/lookup
4
4
  * @see https://developer.nomba.com/docs/api-reference/bills
5
5
  */
6
+ /** Betting lookups (v1): provider listing and customer lookup. Use BettingV2Service for payments. */
6
7
  export class BettingService {
7
8
  http;
8
9
  constructor(http) {
@@ -6,6 +6,7 @@
6
6
  import type { IHttpClient } from "../../../interfaces/http/IHttpClient.js";
7
7
  import type { ICableService } from "../../../interfaces/v1/cable/index.js";
8
8
  import type { CableCustomerLookupParams, CableCustomerLookupResult, CablePlansParams, CablePlansResult } from "../../../types/v1/cable/cable.types.js";
9
+ /** Cable TV lookups (v1): plan listing and customer lookup. Use CableV2Service for payments. */
9
10
  export declare class CableService implements ICableService {
10
11
  private readonly http;
11
12
  constructor(http: IHttpClient);
@@ -3,6 +3,7 @@
3
3
  * @description Cable TV (v1): GET /v1/bill/cableTvProduct, GET /v1/bill/cable/lookup
4
4
  * @see https://developer.nomba.com/docs/api-reference/bills
5
5
  */
6
+ /** Cable TV lookups (v1): plan listing and customer lookup. Use CableV2Service for payments. */
6
7
  export class CableService {
7
8
  http;
8
9
  constructor(http) {
@@ -77,7 +77,7 @@ export class CheckoutService {
77
77
  * @throws {UnconfirmedOutcomeError} The outcome stayed pending after polling ran out.
78
78
  */
79
79
  async refund(params, options = {}) {
80
- return settle(this.http, "POST", "/v1/checkout/refund", { body: params }, REFUND_OUTCOMES, params.transactionId, options);
80
+ return settle(this.http, "POST", "/v1/checkout/refund", { body: params }, REFUND_OUTCOMES, { field: "transactionId", value: params.transactionId }, options);
81
81
  }
82
82
  /**
83
83
  * `POST /v1/checkout/tokenized-card-payment`. Check `status` on the result: it says whether the charge
@@ -27,8 +27,10 @@ export declare class GlobalCollectionsService implements IGlobalCollectionsServi
27
27
  inflowProviders(): Promise<InflowProvider[]>;
28
28
  /**
29
29
  * `POST /v1/global-collection/inflow/initiate`. Prompts the customer to approve the charge on their phone.
30
- * @param params The inflow to initiate; `idempotencyKey` defaults to a generated one.
30
+ * @param params The inflow to initiate. Must include `idempotencyKey` — the SDK never generates
31
+ * one for you to prevent double collection.
31
32
  * @returns The initiated inflow, including its `transactionReference`.
33
+ * @throws {IdempotencyKeyAbsentError} `idempotencyKey` is missing or empty.
32
34
  * @throws {NombaError} The inflow params were rejected.
33
35
  * @throws {OutcomeUnknownError} The call failed in a way that does not say whether it was processed;
34
36
  * check the transaction status before retrying.
@@ -12,7 +12,7 @@
12
12
  * @docs https://developer.nomba.com
13
13
  * @see https://developer.nomba.com/docs/products/global-collections/introduction
14
14
  */
15
- import { randomUUID } from "node:crypto";
15
+ import { IdempotencyKeyAbsentError } from "../../../lib/errors.js";
16
16
  import { pathId } from "../../../lib/util.js";
17
17
  /** Global Collections (v1): DRC mobile money inflows. */
18
18
  export class GlobalCollectionsService {
@@ -30,16 +30,21 @@ export class GlobalCollectionsService {
30
30
  }
31
31
  /**
32
32
  * `POST /v1/global-collection/inflow/initiate`. Prompts the customer to approve the charge on their phone.
33
- * @param params The inflow to initiate; `idempotencyKey` defaults to a generated one.
33
+ * @param params The inflow to initiate. Must include `idempotencyKey` — the SDK never generates
34
+ * one for you to prevent double collection.
34
35
  * @returns The initiated inflow, including its `transactionReference`.
36
+ * @throws {IdempotencyKeyAbsentError} `idempotencyKey` is missing or empty.
35
37
  * @throws {NombaError} The inflow params were rejected.
36
38
  * @throws {OutcomeUnknownError} The call failed in a way that does not say whether it was processed;
37
39
  * check the transaction status before retrying.
38
40
  */
39
- initiateInflow(params) {
40
- const idempotencyKey = params.idempotencyKey || randomUUID();
41
+ async initiateInflow(params) {
42
+ const { idempotencyKey } = params;
43
+ if (!idempotencyKey?.trim()) {
44
+ throw new IdempotencyKeyAbsentError("idempotencyKey", "/v1/global-collection/inflow/initiate");
45
+ }
41
46
  return this.http.request("POST", "/v1/global-collection/inflow/initiate", {
42
- body: { ...params, idempotencyKey },
47
+ body: params,
43
48
  idempotencyKey,
44
49
  });
45
50
  }
@@ -77,22 +77,26 @@ export declare class GlobalPayoutService implements IGlobalPayoutService {
77
77
  paymentMethods(params?: PaymentMethodsParams): Promise<PaymentMethodInfo[]>;
78
78
  /**
79
79
  * `POST /v1/global-payout/transfer/authorize`. Sends money cross-border.
80
- * @param params The transfer to authorize; `idempotencyKey` defaults to a generated one.
81
- * @param options Per-call overrides, including `okCodes`/`onOutcome` via `CallOptions`.
80
+ * @param params The transfer to authorize. Must include `idempotencyKey` — the SDK never generates
81
+ * one for you to prevent double disbursement.
82
+ * @param options Per-call overrides including outcome closures (`onSuccess`, `onPending`, `onFailed`).
82
83
  * @returns The settled payout result (or the type `options` maps it to).
84
+ * @throws {IdempotencyKeyAbsentError} `idempotencyKey` is missing or empty.
83
85
  * @throws {NombaError} The transfer was rejected.
84
- * @throws {OutcomeUnknownError} The call failed in a way that does not say whether it was processed
85
- * (not thrown if `options` resolves unknown outcomes instead).
86
+ * @throws {OutcomeUnknownError} The call failed in a way that does not say whether it was processed;
87
+ * check the transaction status before retrying (not thrown if `options` resolves unknown outcomes).
86
88
  */
87
89
  authorizeTransfer<R = PayoutResult>(params: AuthorizeTransferParams, options?: CallOptions<PayoutResult, R>): Promise<PayoutResult | R>;
88
90
  /**
89
91
  * `POST /v1/global-payout/exchange/authorize`. Moves money between your own wallets in different currencies.
90
- * @param params The exchange to authorize; `idempotencyKey` defaults to a generated one.
91
- * @param options Per-call overrides, including `okCodes`/`onOutcome` via `CallOptions`.
92
+ * @param params The exchange to authorize. Must include `idempotencyKey` — the SDK never generates
93
+ * one for you to prevent double disbursement.
94
+ * @param options Per-call overrides including outcome closures (`onSuccess`, `onPending`, `onFailed`).
92
95
  * @returns The settled payout result (or the type `options` maps it to).
96
+ * @throws {IdempotencyKeyAbsentError} `idempotencyKey` is missing or empty.
93
97
  * @throws {NombaError} The exchange was rejected.
94
- * @throws {OutcomeUnknownError} The call failed in a way that does not say whether it was processed
95
- * (not thrown if `options` resolves unknown outcomes instead).
98
+ * @throws {OutcomeUnknownError} The call failed in a way that does not say whether it was processed;
99
+ * check the transaction status before retrying (not thrown if `options` resolves unknown outcomes).
96
100
  */
97
101
  authorizeExchange<R = PayoutResult>(params: AuthorizeExchangeParams, options?: CallOptions<PayoutResult, R>): Promise<PayoutResult | R>;
98
102
  /**
@@ -12,7 +12,7 @@
12
12
  * @docs https://developer.nomba.com
13
13
  * @see https://developer.nomba.com/docs/products/global-payout/introduction
14
14
  */
15
- import { randomUUID } from "node:crypto";
15
+ import { IdempotencyKeyAbsentError } from "../../../lib/errors.js";
16
16
  import { REJECTED, settle } from "../../../lib/outcome.js";
17
17
  import { pathId } from "../../../lib/util.js";
18
18
  // authorize-transfer documents data.status PROCESSING, PENDING, COMPLETED and FAILED. The docs never say FAILED is
@@ -115,24 +115,28 @@ export class GlobalPayoutService {
115
115
  }
116
116
  /**
117
117
  * `POST /v1/global-payout/transfer/authorize`. Sends money cross-border.
118
- * @param params The transfer to authorize; `idempotencyKey` defaults to a generated one.
119
- * @param options Per-call overrides, including `okCodes`/`onOutcome` via `CallOptions`.
118
+ * @param params The transfer to authorize. Must include `idempotencyKey` — the SDK never generates
119
+ * one for you to prevent double disbursement.
120
+ * @param options Per-call overrides including outcome closures (`onSuccess`, `onPending`, `onFailed`).
120
121
  * @returns The settled payout result (or the type `options` maps it to).
122
+ * @throws {IdempotencyKeyAbsentError} `idempotencyKey` is missing or empty.
121
123
  * @throws {NombaError} The transfer was rejected.
122
- * @throws {OutcomeUnknownError} The call failed in a way that does not say whether it was processed
123
- * (not thrown if `options` resolves unknown outcomes instead).
124
+ * @throws {OutcomeUnknownError} The call failed in a way that does not say whether it was processed;
125
+ * check the transaction status before retrying (not thrown if `options` resolves unknown outcomes).
124
126
  */
125
127
  async authorizeTransfer(params, options = {}) {
126
128
  return this.#authorize("/v1/global-payout/transfer/authorize", params, options, TRANSFER_OUTCOMES);
127
129
  }
128
130
  /**
129
131
  * `POST /v1/global-payout/exchange/authorize`. Moves money between your own wallets in different currencies.
130
- * @param params The exchange to authorize; `idempotencyKey` defaults to a generated one.
131
- * @param options Per-call overrides, including `okCodes`/`onOutcome` via `CallOptions`.
132
+ * @param params The exchange to authorize. Must include `idempotencyKey` — the SDK never generates
133
+ * one for you to prevent double disbursement.
134
+ * @param options Per-call overrides including outcome closures (`onSuccess`, `onPending`, `onFailed`).
132
135
  * @returns The settled payout result (or the type `options` maps it to).
136
+ * @throws {IdempotencyKeyAbsentError} `idempotencyKey` is missing or empty.
133
137
  * @throws {NombaError} The exchange was rejected.
134
- * @throws {OutcomeUnknownError} The call failed in a way that does not say whether it was processed
135
- * (not thrown if `options` resolves unknown outcomes instead).
138
+ * @throws {OutcomeUnknownError} The call failed in a way that does not say whether it was processed;
139
+ * check the transaction status before retrying (not thrown if `options` resolves unknown outcomes).
136
140
  */
137
141
  async authorizeExchange(params, options = {}) {
138
142
  return this.#authorize("/v1/global-payout/exchange/authorize", params, options, EXCHANGE_OUTCOMES);
@@ -146,9 +150,12 @@ export class GlobalPayoutService {
146
150
  async getTransaction(transactionId) {
147
151
  return this.http.request("GET", `/v1/global-payout/transactions/${pathId(transactionId)}`);
148
152
  }
149
- // One key in the body (the one the API dedupes on) and the header, so OutcomeUnknownError reports it.
153
+ // One key in the body (the one the API dedupes on), required to prevent double disbursement; OutcomeUnknownError reports it.
150
154
  #authorize(path, params, options, table) {
151
- const idempotencyKey = params.idempotencyKey || randomUUID();
152
- return settle(this.http, "POST", path, { body: { ...params, idempotencyKey } }, table, idempotencyKey, options);
155
+ const { idempotencyKey } = params;
156
+ if (!idempotencyKey?.trim()) {
157
+ throw new IdempotencyKeyAbsentError("idempotencyKey", path);
158
+ }
159
+ return settle(this.http, "POST", path, { body: params }, table, { field: "idempotencyKey", value: idempotencyKey }, options);
153
160
  }
154
161
  }
@@ -15,17 +15,35 @@
15
15
  import type { IHttpClient } from "../../../interfaces/http/IHttpClient.js";
16
16
  import type { IRequeryService } from "../../../interfaces/v1/requery/IRequeryService.js";
17
17
  import type { Transaction, TransactionLookup } from "../../../types/v1/requery/requery.types.js";
18
+ /** Requery (v1): look up a single transaction's current status. */
18
19
  export declare class RequeryService implements IRequeryService {
19
20
  private readonly http;
20
21
  constructor(http: IHttpClient);
21
- /** GET /v1/transactions/accounts/single */
22
+ /**
23
+ * `GET /v1/transactions/accounts/single`. Looks up a transaction on the parent account by
24
+ * reference or ID.
25
+ * @param lookup The transaction identifier (e.g., `transactionId` or `merchantTxRef`).
26
+ * @returns The transaction's current details and status.
27
+ * @throws {NombaError} The transaction was not found, or the call failed.
28
+ */
22
29
  fetchParentTransaction(lookup: TransactionLookup): Promise<Transaction>;
23
- /** GET /v1/transactions/accounts/{subAccountId}/single */
30
+ /**
31
+ * `GET /v1/transactions/accounts/{subAccountId}/single`. Looks up a transaction on a sub account
32
+ * by reference or ID.
33
+ * @param subAccountId The sub account's ID.
34
+ * @param lookup The transaction identifier (e.g., `transactionId` or `merchantTxRef`).
35
+ * @returns The transaction's current details and status.
36
+ * @throws {NombaError} The transaction was not found, `subAccountId` does not exist, or the call failed.
37
+ */
24
38
  fetchSubAccountTransaction(subAccountId: string, lookup: TransactionLookup): Promise<Transaction>;
25
39
  /**
26
- * GET /v1/transactions/requery/{sessionId}. Use for transfers made through both parent and sub
27
- * accounts. Nomba-to-Nomba wallet transfers return no sessionId; use fetchParentTransaction or
28
- * fetchSubAccountTransaction for those instead.
40
+ * `GET /v1/transactions/requery/{sessionId}`. Looks up a bank transfer by its session ID.
41
+ * Use this for transfers made through both parent and sub accounts. Note: Nomba-to-Nomba
42
+ * wallet transfers do not return a `sessionId`; use `fetchParentTransaction` or
43
+ * `fetchSubAccountTransaction` for those instead.
44
+ * @param sessionId The transfer's session ID from the original response.
45
+ * @returns The transaction's current details and status.
46
+ * @throws {NombaError} The session was not found, or the call failed.
29
47
  */
30
48
  requeryBySession(sessionId: string): Promise<Transaction>;
31
49
  }