@easyslip/sdk 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +21 -0
  3. package/README.md +595 -2
  4. package/README.th.md +610 -0
  5. package/dist/cjs/client.d.ts +59 -0
  6. package/dist/cjs/client.js +150 -0
  7. package/dist/cjs/core/call.d.ts +18 -0
  8. package/dist/cjs/core/call.js +60 -0
  9. package/dist/cjs/core/error-codes.d.ts +8 -0
  10. package/dist/cjs/core/error-codes.js +87 -0
  11. package/dist/cjs/core/errors.d.ts +162 -0
  12. package/dist/cjs/core/errors.js +210 -0
  13. package/dist/cjs/core/files.d.ts +20 -0
  14. package/dist/cjs/core/files.js +131 -0
  15. package/dist/cjs/core/http.d.ts +65 -0
  16. package/dist/cjs/core/http.js +242 -0
  17. package/dist/cjs/core/meta.d.ts +33 -0
  18. package/dist/cjs/core/meta.js +52 -0
  19. package/dist/cjs/core/redact.d.ts +43 -0
  20. package/dist/cjs/core/redact.js +208 -0
  21. package/dist/cjs/core/runtime.d.ts +16 -0
  22. package/dist/cjs/core/runtime.js +86 -0
  23. package/dist/cjs/core/settings.d.ts +19 -0
  24. package/dist/cjs/core/settings.js +22 -0
  25. package/dist/cjs/core/sha256.d.ts +6 -0
  26. package/dist/cjs/core/sha256.js +101 -0
  27. package/dist/cjs/index.d.ts +13 -0
  28. package/dist/cjs/index.js +55 -0
  29. package/dist/cjs/models.d.ts +398 -0
  30. package/dist/cjs/models.js +234 -0
  31. package/dist/cjs/package.json +1 -0
  32. package/dist/cjs/resources/bank-accounts.d.ts +63 -0
  33. package/dist/cjs/resources/bank-accounts.js +126 -0
  34. package/dist/cjs/resources/banks.d.ts +10 -0
  35. package/dist/cjs/resources/banks.js +22 -0
  36. package/dist/cjs/resources/jobs.d.ts +64 -0
  37. package/dist/cjs/resources/jobs.js +177 -0
  38. package/dist/cjs/resources/v1.d.ts +88 -0
  39. package/dist/cjs/resources/v1.js +137 -0
  40. package/dist/cjs/resources/verify.d.ts +39 -0
  41. package/dist/cjs/resources/verify.js +105 -0
  42. package/dist/cjs/version.d.ts +2 -0
  43. package/dist/cjs/version.js +5 -0
  44. package/dist/cjs/webhooks.d.ts +26 -0
  45. package/dist/cjs/webhooks.js +92 -0
  46. package/dist/esm/client.d.ts +59 -0
  47. package/dist/esm/client.js +146 -0
  48. package/dist/esm/core/call.d.ts +18 -0
  49. package/dist/esm/core/call.js +52 -0
  50. package/dist/esm/core/error-codes.d.ts +8 -0
  51. package/dist/esm/core/error-codes.js +84 -0
  52. package/dist/esm/core/errors.d.ts +162 -0
  53. package/dist/esm/core/errors.js +184 -0
  54. package/dist/esm/core/files.d.ts +20 -0
  55. package/dist/esm/core/files.js +126 -0
  56. package/dist/esm/core/http.d.ts +65 -0
  57. package/dist/esm/core/http.js +235 -0
  58. package/dist/esm/core/meta.d.ts +33 -0
  59. package/dist/esm/core/meta.js +45 -0
  60. package/dist/esm/core/redact.d.ts +43 -0
  61. package/dist/esm/core/redact.js +198 -0
  62. package/dist/esm/core/runtime.d.ts +16 -0
  63. package/dist/esm/core/runtime.js +47 -0
  64. package/dist/esm/core/settings.d.ts +19 -0
  65. package/dist/esm/core/settings.js +19 -0
  66. package/dist/esm/core/sha256.d.ts +6 -0
  67. package/dist/esm/core/sha256.js +96 -0
  68. package/dist/esm/index.d.ts +13 -0
  69. package/dist/esm/index.js +7 -0
  70. package/dist/esm/models.d.ts +398 -0
  71. package/dist/esm/models.js +228 -0
  72. package/dist/esm/package.json +1 -0
  73. package/dist/esm/resources/bank-accounts.d.ts +63 -0
  74. package/dist/esm/resources/bank-accounts.js +122 -0
  75. package/dist/esm/resources/banks.d.ts +10 -0
  76. package/dist/esm/resources/banks.js +18 -0
  77. package/dist/esm/resources/jobs.d.ts +64 -0
  78. package/dist/esm/resources/jobs.js +173 -0
  79. package/dist/esm/resources/v1.d.ts +88 -0
  80. package/dist/esm/resources/v1.js +133 -0
  81. package/dist/esm/resources/verify.d.ts +39 -0
  82. package/dist/esm/resources/verify.js +100 -0
  83. package/dist/esm/version.d.ts +2 -0
  84. package/dist/esm/version.js +2 -0
  85. package/dist/esm/webhooks.d.ts +26 -0
  86. package/dist/esm/webhooks.js +86 -0
  87. package/package.json +80 -5
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Verify = void 0;
4
+ exports.verifyFields = verifyFields;
5
+ const call_js_1 = require("../core/call.js");
6
+ const files_js_1 = require("../core/files.js");
7
+ const OPTION_KEYS = ['remark', 'matchAccount', 'matchAmount', 'checkDuplicate'];
8
+ function verifyFields(options) {
9
+ return (0, call_js_1.defined)(options, OPTION_KEYS);
10
+ }
11
+ /**
12
+ * v2 slip verification (`client.verify`). Every call here is billed: it can spend quota, so
13
+ * the SDK only retries it when the request never reached the API (or on 429).
14
+ */
15
+ class Verify {
16
+ #t;
17
+ constructor(transport) {
18
+ this.#t = transport;
19
+ }
20
+ /** Verifies a bank slip from its QR payload string. */
21
+ async bankByPayload(payload, options) {
22
+ (0, call_js_1.requireString)(payload, 'payload');
23
+ return (0, call_js_1.call)(this.#t, 'BankSlipResult', {
24
+ ...(0, call_js_1.requestOptions)(options),
25
+ api: 'v2',
26
+ method: 'POST',
27
+ path: '/verify/bank',
28
+ json: { payload, ...verifyFields(options) },
29
+ retry: 'billed',
30
+ });
31
+ }
32
+ /** Verifies a bank slip image (JPEG, PNG, GIF or WebP, up to 4 MB). */
33
+ async bankByImage(file, options) {
34
+ const prepared = await (0, files_js_1.prepareFile)(file);
35
+ return (0, call_js_1.call)(this.#t, 'BankSlipResult', {
36
+ ...(0, call_js_1.requestOptions)(options),
37
+ api: 'v2',
38
+ method: 'POST',
39
+ path: '/verify/bank',
40
+ form: (0, call_js_1.imageForm)('image', prepared, verifyFields(options)),
41
+ retry: 'billed',
42
+ });
43
+ }
44
+ /** Verifies a base64 bank slip image. A `data:image/...;base64,` prefix is fine. */
45
+ async bankByBase64(base64, options) {
46
+ (0, call_js_1.requireString)(base64, 'base64');
47
+ return (0, call_js_1.call)(this.#t, 'BankSlipResult', {
48
+ ...(0, call_js_1.requestOptions)(options),
49
+ api: 'v2',
50
+ method: 'POST',
51
+ path: '/verify/bank',
52
+ json: { base64, ...verifyFields(options) },
53
+ retry: 'billed',
54
+ });
55
+ }
56
+ /** Verifies a bank slip image the API downloads from a public http(s) URL. */
57
+ async bankByUrl(url, options) {
58
+ (0, call_js_1.requireString)(url, 'url');
59
+ return (0, call_js_1.call)(this.#t, 'BankSlipResult', {
60
+ ...(0, call_js_1.requestOptions)(options),
61
+ api: 'v2',
62
+ method: 'POST',
63
+ path: '/verify/bank',
64
+ json: { url, ...verifyFields(options) },
65
+ retry: 'billed',
66
+ });
67
+ }
68
+ /** Verifies a TrueMoney Wallet slip image. */
69
+ async truewalletByImage(file, options) {
70
+ const prepared = await (0, files_js_1.prepareFile)(file);
71
+ return (0, call_js_1.call)(this.#t, 'TrueWalletResult', {
72
+ ...(0, call_js_1.requestOptions)(options),
73
+ api: 'v2',
74
+ method: 'POST',
75
+ path: '/verify/truewallet',
76
+ form: (0, call_js_1.imageForm)('image', prepared, verifyFields(options)),
77
+ retry: 'billed',
78
+ });
79
+ }
80
+ /** Verifies a base64 TrueMoney Wallet slip image. */
81
+ async truewalletByBase64(base64, options) {
82
+ (0, call_js_1.requireString)(base64, 'base64');
83
+ return (0, call_js_1.call)(this.#t, 'TrueWalletResult', {
84
+ ...(0, call_js_1.requestOptions)(options),
85
+ api: 'v2',
86
+ method: 'POST',
87
+ path: '/verify/truewallet',
88
+ json: { base64, ...verifyFields(options) },
89
+ retry: 'billed',
90
+ });
91
+ }
92
+ /** Verifies a TrueMoney Wallet slip image from a public URL (up to 255 characters). */
93
+ async truewalletByUrl(url, options) {
94
+ (0, call_js_1.requireString)(url, 'url');
95
+ return (0, call_js_1.call)(this.#t, 'TrueWalletResult', {
96
+ ...(0, call_js_1.requestOptions)(options),
97
+ api: 'v2',
98
+ method: 'POST',
99
+ path: '/verify/truewallet',
100
+ json: { url, ...verifyFields(options) },
101
+ retry: 'billed',
102
+ });
103
+ }
104
+ }
105
+ exports.Verify = Verify;
@@ -0,0 +1,2 @@
1
+ /** SDK version, sent in the User-Agent header. */
2
+ export declare const VERSION = "1.0.1";
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VERSION = void 0;
4
+ /** SDK version, sent in the User-Agent header. */
5
+ exports.VERSION = '1.0.1'; // x-release-please-version
@@ -0,0 +1,26 @@
1
+ import { type WebhookEvent } from './models.js';
2
+ /** Name of the header that carries the webhook signature. */
3
+ export declare const WEBHOOK_SIGNATURE_HEADER: string;
4
+ /** The webhook body exactly as received: a string or the raw bytes. */
5
+ export type WebhookBody = string | Uint8Array | ArrayBuffer;
6
+ /** A header value as web and Node frameworks hand it over. */
7
+ export type SignatureHeader = string | readonly string[] | null | undefined;
8
+ /**
9
+ * Checks a webhook signature: `sha256=` plus the lower-case hex HMAC-SHA256 of the raw body
10
+ * under your webhook secret, compared in constant time. Pass the body exactly as received,
11
+ * before any JSON parsing. A missing header gives false.
12
+ *
13
+ * @param secret Your branch's webhook secret. Defaults to the webhook secret env variable.
14
+ */
15
+ export declare function verifyWebhookSignature(rawBody: WebhookBody, signatureHeader: SignatureHeader, secret?: string): boolean;
16
+ /**
17
+ * Parses a webhook body into a {@link WebhookEvent} without checking the signature. Throws
18
+ * {@link InputError} when the body is not a JSON object with string `jobId`, `status` and
19
+ * `timestamp` fields.
20
+ */
21
+ export declare function parseWebhookEvent(rawBody: WebhookBody): WebhookEvent;
22
+ /**
23
+ * Verifies the signature, then parses the body. Throws {@link WebhookSignatureError} when the
24
+ * signature is missing or wrong, and {@link InputError} when a signed body is not a webhook event.
25
+ */
26
+ export declare function constructWebhookEvent(rawBody: WebhookBody, signatureHeader: SignatureHeader, secret?: string): WebhookEvent;
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WEBHOOK_SIGNATURE_HEADER = void 0;
4
+ exports.verifyWebhookSignature = verifyWebhookSignature;
5
+ exports.parseWebhookEvent = parseWebhookEvent;
6
+ exports.constructWebhookEvent = constructWebhookEvent;
7
+ const errors_js_1 = require("./core/errors.js");
8
+ const runtime_js_1 = require("./core/runtime.js");
9
+ const settings_js_1 = require("./core/settings.js");
10
+ const sha256_js_1 = require("./core/sha256.js");
11
+ const models_js_1 = require("./models.js");
12
+ /** Name of the header that carries the webhook signature. */
13
+ exports.WEBHOOK_SIGNATURE_HEADER = settings_js_1.settings.webhook.signatureHeader;
14
+ const PREFIX = settings_js_1.settings.webhook.signaturePrefix;
15
+ const SIGNATURE = /^[0-9a-f]{64}$/;
16
+ function toBytes(body) {
17
+ if (typeof body === 'string')
18
+ return new TextEncoder().encode(body);
19
+ if (body instanceof ArrayBuffer)
20
+ return new Uint8Array(body);
21
+ if (body instanceof Uint8Array)
22
+ return body;
23
+ throw new errors_js_1.InputError('INVALID_ARGUMENT', 'webhook body must be a string or bytes');
24
+ }
25
+ function secretOrEnv(secret) {
26
+ const value = secret ?? (0, runtime_js_1.readEnv)(settings_js_1.settings.env.webhookSecret);
27
+ if (!value) {
28
+ throw new errors_js_1.InputError('INVALID_ARGUMENT', `no webhook secret: pass one or set ${settings_js_1.settings.env.webhookSecret}`);
29
+ }
30
+ return value;
31
+ }
32
+ function equalConstantTime(a, b) {
33
+ if (a.length !== b.length)
34
+ return false;
35
+ let diff = 0;
36
+ for (let i = 0; i < a.length; i++)
37
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
38
+ return diff === 0;
39
+ }
40
+ /**
41
+ * Checks a webhook signature: `sha256=` plus the lower-case hex HMAC-SHA256 of the raw body
42
+ * under your webhook secret, compared in constant time. Pass the body exactly as received,
43
+ * before any JSON parsing. A missing header gives false.
44
+ *
45
+ * @param secret Your branch's webhook secret. Defaults to the webhook secret env variable.
46
+ */
47
+ function verifyWebhookSignature(rawBody, signatureHeader, secret) {
48
+ const key = secretOrEnv(secret);
49
+ const header = Array.isArray(signatureHeader) ? signatureHeader[0] : signatureHeader;
50
+ if (typeof header !== 'string' || !header.startsWith(PREFIX))
51
+ return false;
52
+ const given = header.slice(PREFIX.length);
53
+ if (!SIGNATURE.test(given))
54
+ return false;
55
+ const expected = (0, sha256_js_1.toHex)((0, sha256_js_1.hmacSha256)(new TextEncoder().encode(key), toBytes(rawBody)));
56
+ return equalConstantTime(given, expected);
57
+ }
58
+ /**
59
+ * Parses a webhook body into a {@link WebhookEvent} without checking the signature. Throws
60
+ * {@link InputError} when the body is not a JSON object with string `jobId`, `status` and
61
+ * `timestamp` fields.
62
+ */
63
+ function parseWebhookEvent(rawBody) {
64
+ const text = typeof rawBody === 'string' ? rawBody : new TextDecoder().decode(toBytes(rawBody));
65
+ let value;
66
+ try {
67
+ value = JSON.parse(text);
68
+ }
69
+ catch (cause) {
70
+ throw new errors_js_1.InputError('INVALID_ARGUMENT', 'webhook body is not JSON', { cause });
71
+ }
72
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
73
+ throw new errors_js_1.InputError('INVALID_ARGUMENT', 'webhook body is not a JSON object');
74
+ }
75
+ const fields = value;
76
+ if (typeof fields.jobId !== 'string' ||
77
+ typeof fields.status !== 'string' ||
78
+ typeof fields.timestamp !== 'string') {
79
+ throw new errors_js_1.InputError('INVALID_ARGUMENT', 'webhook body must contain jobId, status and timestamp');
80
+ }
81
+ return (0, models_js_1.parseModel)('WebhookEvent', value);
82
+ }
83
+ /**
84
+ * Verifies the signature, then parses the body. Throws {@link WebhookSignatureError} when the
85
+ * signature is missing or wrong, and {@link InputError} when a signed body is not a webhook event.
86
+ */
87
+ function constructWebhookEvent(rawBody, signatureHeader, secret) {
88
+ if (!verifyWebhookSignature(rawBody, signatureHeader, secret)) {
89
+ throw new errors_js_1.WebhookSignatureError(`webhook signature in ${exports.WEBHOOK_SIGNATURE_HEADER} is missing or does not match`);
90
+ }
91
+ return parseWebhookEvent(rawBody);
92
+ }
@@ -0,0 +1,59 @@
1
+ import { type FetchLike, type RequestOptions } from './core/http.js';
2
+ import type { WithMeta } from './core/meta.js';
3
+ import type { Info } from './models.js';
4
+ import { BankAccounts } from './resources/bank-accounts.js';
5
+ import { Banks } from './resources/banks.js';
6
+ import { Jobs } from './resources/jobs.js';
7
+ import { V1 } from './resources/v1.js';
8
+ import { Verify } from './resources/verify.js';
9
+ /** Client settings. Every field is optional when the matching env variable is set. */
10
+ export interface ClientOptions {
11
+ /** API key. Defaults to the API key env variable, then the file named by the key file env variable. */
12
+ apiKey?: string;
13
+ /** v2 base URL. Defaults to the v2 base URL env variable, then the production host. */
14
+ v2BaseUrl?: string;
15
+ /** v1 base URL. Defaults to the v1 base URL env variable, then the production host. */
16
+ v1BaseUrl?: string;
17
+ /** Per-attempt timeout in milliseconds. Default 30000. */
18
+ timeout?: number;
19
+ /** Retries after the first attempt, following each call's retry class. Default 2. */
20
+ maxRetries?: number;
21
+ /** A fetch implementation, for proxies, custom agents or tests. Default: global fetch. */
22
+ fetch?: FetchLike;
23
+ }
24
+ /**
25
+ * API client. Create one and reuse it.
26
+ *
27
+ * ```ts
28
+ * const client = new Client({ apiKey: 'YOUR_API_KEY' })
29
+ * const result = await client.verify.bankByPayload(payload, { checkDuplicate: true })
30
+ * ```
31
+ */
32
+ export declare class Client {
33
+ #private;
34
+ /** v2 slip verification. */
35
+ readonly verify: Verify;
36
+ /** Supported banks. */
37
+ readonly banks: Banks;
38
+ /** Registered receiving accounts. */
39
+ readonly bankAccounts: BankAccounts;
40
+ /** Async verification jobs. */
41
+ readonly jobs: Jobs;
42
+ /** The v1 API. */
43
+ readonly v1: V1;
44
+ /** v2 base URL in use. */
45
+ readonly v2BaseUrl: string;
46
+ /** v1 base URL in use. */
47
+ readonly v1BaseUrl: string;
48
+ /** Per-attempt timeout in milliseconds. */
49
+ readonly timeout: number;
50
+ /** Retries after the first attempt. */
51
+ readonly maxRetries: number;
52
+ constructor(options?: ClientOptions);
53
+ /** The User-Agent header this client sends. */
54
+ get userAgent(): string;
55
+ /** Application, branch, quota and account details of the API key. */
56
+ getInfo(options?: RequestOptions): Promise<WithMeta<Info>>;
57
+ toJSON(): Record<string, unknown>;
58
+ toString(): string;
59
+ }
@@ -0,0 +1,146 @@
1
+ import { call, requestOptions } from './core/call.js';
2
+ import { InputError } from './core/errors.js';
3
+ import { Transport } from './core/http.js';
4
+ import { loadFs, readEnv, runtimeToken, sleep } from './core/runtime.js';
5
+ import { settings } from './core/settings.js';
6
+ import { BankAccounts } from './resources/bank-accounts.js';
7
+ import { Banks } from './resources/banks.js';
8
+ import { Jobs } from './resources/jobs.js';
9
+ import { V1 } from './resources/v1.js';
10
+ import { Verify } from './resources/verify.js';
11
+ import { VERSION } from './version.js';
12
+ function keyFromFile(path) {
13
+ let cached;
14
+ return () => {
15
+ cached ??= (async () => {
16
+ const fs = await loadFs();
17
+ if (!fs) {
18
+ throw new InputError('FILE_NOT_READABLE', `${settings.env.apiKeyFile} needs a runtime with a file system`);
19
+ }
20
+ let text;
21
+ try {
22
+ text = new TextDecoder().decode(await fs.readFile(path));
23
+ }
24
+ catch (cause) {
25
+ throw new InputError('FILE_NOT_READABLE', `cannot read ${settings.env.apiKeyFile}`, {
26
+ cause,
27
+ });
28
+ }
29
+ const key = text.trim();
30
+ if (!key)
31
+ throw new InputError('INVALID_ARGUMENT', `${settings.env.apiKeyFile} is empty`);
32
+ return key;
33
+ })();
34
+ cached.catch(() => {
35
+ cached = undefined;
36
+ });
37
+ return cached;
38
+ };
39
+ }
40
+ function checkNumber(value, name, min) {
41
+ if (value !== undefined && (!Number.isFinite(value) || value < min)) {
42
+ throw new InputError('INVALID_ARGUMENT', `${name} must be a number >= ${min}`);
43
+ }
44
+ }
45
+ /**
46
+ * API client. Create one and reuse it.
47
+ *
48
+ * ```ts
49
+ * const client = new Client({ apiKey: 'YOUR_API_KEY' })
50
+ * const result = await client.verify.bankByPayload(payload, { checkDuplicate: true })
51
+ * ```
52
+ */
53
+ export class Client {
54
+ /** v2 slip verification. */
55
+ verify;
56
+ /** Supported banks. */
57
+ banks;
58
+ /** Registered receiving accounts. */
59
+ bankAccounts;
60
+ /** Async verification jobs. */
61
+ jobs;
62
+ /** The v1 API. */
63
+ v1;
64
+ /** v2 base URL in use. */
65
+ v2BaseUrl;
66
+ /** v1 base URL in use. */
67
+ v1BaseUrl;
68
+ /** Per-attempt timeout in milliseconds. */
69
+ timeout;
70
+ /** Retries after the first attempt. */
71
+ maxRetries;
72
+ #transport;
73
+ constructor(options = {}) {
74
+ checkNumber(options.timeout, 'timeout', 1);
75
+ checkNumber(options.maxRetries, 'maxRetries', 0);
76
+ let apiKey;
77
+ const key = options.apiKey ?? readEnv(settings.env.apiKey);
78
+ if (key !== undefined) {
79
+ if (typeof key !== 'string' || key.trim() === '') {
80
+ throw new InputError('INVALID_ARGUMENT', 'apiKey must be a non-empty string');
81
+ }
82
+ const value = key.trim();
83
+ apiKey = () => Promise.resolve(value);
84
+ }
85
+ else {
86
+ const file = readEnv(settings.env.apiKeyFile);
87
+ if (!file) {
88
+ throw new InputError('INVALID_ARGUMENT', `no API key: pass apiKey or set ${settings.env.apiKey} or ${settings.env.apiKeyFile}`);
89
+ }
90
+ apiKey = keyFromFile(file);
91
+ }
92
+ if (!options.fetch && typeof globalThis.fetch !== 'function') {
93
+ throw new InputError('INVALID_ARGUMENT', 'no fetch: pass options.fetch');
94
+ }
95
+ this.v2BaseUrl =
96
+ options.v2BaseUrl ?? readEnv(settings.env.v2BaseUrl) ?? settings.baseUrls.v2;
97
+ this.v1BaseUrl =
98
+ options.v1BaseUrl ?? readEnv(settings.env.v1BaseUrl) ?? settings.baseUrls.v1;
99
+ this.timeout = options.timeout ?? 30_000;
100
+ this.maxRetries = Math.floor(options.maxRetries ?? 2);
101
+ this.#transport = new Transport({
102
+ v1BaseUrl: this.v1BaseUrl,
103
+ v2BaseUrl: this.v2BaseUrl,
104
+ timeout: this.timeout,
105
+ maxRetries: this.maxRetries,
106
+ userAgent: `${settings.userAgentProduct}/${VERSION} ${runtimeToken()}`,
107
+ fetch: options.fetch ?? ((input, init) => globalThis.fetch(input, init)),
108
+ sleep: options.sleep ?? sleep,
109
+ random: options.random ?? Math.random,
110
+ apiKey,
111
+ });
112
+ this.verify = new Verify(this.#transport);
113
+ this.banks = new Banks(this.#transport);
114
+ this.bankAccounts = new BankAccounts(this.#transport);
115
+ this.jobs = new Jobs(this.#transport);
116
+ this.v1 = new V1(this.#transport);
117
+ }
118
+ /** The User-Agent header this client sends. */
119
+ get userAgent() {
120
+ return this.#transport.config.userAgent;
121
+ }
122
+ /** Application, branch, quota and account details of the API key. */
123
+ async getInfo(options) {
124
+ return call(this.#transport, 'Info', {
125
+ ...requestOptions(options),
126
+ api: 'v2',
127
+ method: 'GET',
128
+ path: '/info',
129
+ retry: 'safe',
130
+ });
131
+ }
132
+ toJSON() {
133
+ return {
134
+ v2BaseUrl: this.v2BaseUrl,
135
+ v1BaseUrl: this.v1BaseUrl,
136
+ timeout: this.timeout,
137
+ maxRetries: this.maxRetries,
138
+ };
139
+ }
140
+ toString() {
141
+ return `Client(${this.v2BaseUrl})`;
142
+ }
143
+ [Symbol.for('nodejs.util.inspect.custom')]() {
144
+ return `Client ${JSON.stringify(this.toJSON())}`;
145
+ }
146
+ }
@@ -0,0 +1,18 @@
1
+ import { type ModelName, parseModel } from '../models.js';
2
+ import type { PreparedFile } from './files.js';
3
+ import type { RequestOptions, RequestSpec, Transport } from './http.js';
4
+ import { type WithMeta } from './meta.js';
5
+ type Models = {
6
+ [N in ModelName]: ReturnType<typeof parseModel<N>>;
7
+ };
8
+ /** Sends `spec` and decodes `data` into the named model, with `meta` attached. */
9
+ export declare function call<N extends ModelName>(transport: Transport, model: N, spec: RequestSpec): Promise<WithMeta<Models[N]>>;
10
+ /** Copies the per-call request options out of a merged options object. */
11
+ export declare function requestOptions(options: RequestOptions | undefined): RequestOptions;
12
+ /** Copies the listed keys that are set (not undefined). Explicit nulls are kept. */
13
+ export declare function defined<T extends object, K extends keyof T>(source: T | undefined, keys: readonly K[]): Partial<Pick<T, K>>;
14
+ /** Multipart form with the image part and string fields (`true`/`false`, plain numbers). */
15
+ export declare function imageForm(field: string, file: PreparedFile, fields: Record<string, string | number | boolean>): FormData;
16
+ export declare function requireString(value: unknown, name: string): string;
17
+ export declare function requireId(value: unknown, name?: string): number;
18
+ export {};
@@ -0,0 +1,52 @@
1
+ import { parseModel } from '../models.js';
2
+ import { InputError } from './errors.js';
3
+ import { attachMeta } from './meta.js';
4
+ /** Sends `spec` and decodes `data` into the named model, with `meta` attached. */
5
+ export async function call(transport, model, spec) {
6
+ const { data, meta } = await transport.request(spec);
7
+ return attachMeta(parseModel(model, data), meta);
8
+ }
9
+ /** Copies the per-call request options out of a merged options object. */
10
+ export function requestOptions(options) {
11
+ if (!options)
12
+ return {};
13
+ const out = {};
14
+ if (options.signal !== undefined)
15
+ out.signal = options.signal;
16
+ if (options.timeout !== undefined)
17
+ out.timeout = options.timeout;
18
+ if (options.maxRetries !== undefined)
19
+ out.maxRetries = options.maxRetries;
20
+ return out;
21
+ }
22
+ /** Copies the listed keys that are set (not undefined). Explicit nulls are kept. */
23
+ export function defined(source, keys) {
24
+ const out = {};
25
+ if (!source)
26
+ return out;
27
+ for (const key of keys) {
28
+ if (source[key] !== undefined)
29
+ out[key] = source[key];
30
+ }
31
+ return out;
32
+ }
33
+ /** Multipart form with the image part and string fields (`true`/`false`, plain numbers). */
34
+ export function imageForm(field, file, fields) {
35
+ const form = new FormData();
36
+ for (const [key, value] of Object.entries(fields))
37
+ form.append(key, String(value));
38
+ form.append(field, new Blob([file.bytes], { type: file.contentType }), file.filename);
39
+ return form;
40
+ }
41
+ export function requireString(value, name) {
42
+ if (typeof value !== 'string' || value.trim() === '') {
43
+ throw new InputError('INVALID_ARGUMENT', `${name} must be a non-empty string`);
44
+ }
45
+ return value;
46
+ }
47
+ export function requireId(value, name = 'id') {
48
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {
49
+ throw new InputError('INVALID_ARGUMENT', `${name} must be a positive integer`);
50
+ }
51
+ return value;
52
+ }
@@ -0,0 +1,8 @@
1
+ import type { ApiErrorClassName } from './errors.js';
2
+ /** API error code to error class, per API version. */
3
+ export declare const errorCodes: {
4
+ readonly v1: Readonly<Record<string, ApiErrorClassName>>;
5
+ readonly v2: Readonly<Record<string, ApiErrorClassName>>;
6
+ };
7
+ /** Error class by HTTP status when the code is unknown. */
8
+ export declare const statusFallback: Readonly<Record<number, ApiErrorClassName>>;
@@ -0,0 +1,84 @@
1
+ /** API error code to error class, per API version. */
2
+ export const errorCodes = {
3
+ v1: {
4
+ unauthorized: 'AuthenticationError',
5
+ access_denied: 'PermissionDeniedError',
6
+ account_not_verified: 'PermissionDeniedError',
7
+ application_expired: 'PermissionDeniedError',
8
+ application_deactivated: 'PermissionDeniedError',
9
+ quota_exceeded: 'QuotaExceededError',
10
+ invalid_payload: 'InvalidRequestError',
11
+ invalid_check_duplicate: 'InvalidRequestError',
12
+ invalid_request: 'InvalidRequestError',
13
+ invalid_type: 'InvalidRequestError',
14
+ invalid_transaction_id: 'InvalidRequestError',
15
+ invalid_sender_name: 'InvalidRequestError',
16
+ invalid_receiver_name: 'InvalidRequestError',
17
+ invalid_receiver_phone: 'InvalidRequestError',
18
+ invalid_date: 'InvalidRequestError',
19
+ invalid_amount: 'InvalidRequestError',
20
+ invalid_image: 'InvalidImageError',
21
+ invalid_wallet_qr: 'InvalidImageError',
22
+ invalid_base64: 'InvalidImageError',
23
+ image_size_too_large: 'InvalidImageError',
24
+ invalid_url: 'InvalidUrlError',
25
+ url_unreachable: 'InvalidUrlError',
26
+ duplicate_slip: 'DuplicateSlipError',
27
+ slip_not_found: 'SlipNotFoundError',
28
+ qrcode_not_found: 'SlipNotFoundError',
29
+ slip_pending: 'SlipPendingError',
30
+ not_found: 'NotFoundError',
31
+ rate_limit_exceeded: 'RateLimitError',
32
+ server_error: 'ServerError',
33
+ api_server_error: 'ServerError',
34
+ renewal_temporarily_unavailable: 'ServiceUnavailableError',
35
+ },
36
+ v2: {
37
+ MISSING_API_KEY: 'AuthenticationError',
38
+ INVALID_API_KEY: 'AuthenticationError',
39
+ BRANCH_INACTIVE: 'PermissionDeniedError',
40
+ SERVICE_BANNED: 'PermissionDeniedError',
41
+ SERVICE_DELETED: 'PermissionDeniedError',
42
+ USER_BANNED: 'PermissionDeniedError',
43
+ IP_NOT_ALLOWED: 'PermissionDeniedError',
44
+ SERVICE_EXPIRED: 'PermissionDeniedError',
45
+ QUOTA_EXCEEDED: 'QuotaExceededError',
46
+ VALIDATION_ERROR: 'InvalidRequestError',
47
+ INVALID_BANK_CODE: 'InvalidRequestError',
48
+ INVALID_EXTRA_VERIFY: 'InvalidRequestError',
49
+ INVALID_MATCH_MODE: 'InvalidRequestError',
50
+ IMAGE_SIZE_TOO_LARGE: 'InvalidImageError',
51
+ INVALID_IMAGE_FORMAT: 'InvalidImageError',
52
+ INVALID_IMAGE_TYPE: 'InvalidImageError',
53
+ INVALID_IMAGE: 'InvalidImageError',
54
+ INVALID_WALLET_QR: 'InvalidImageError',
55
+ URL_PROTOCOL_NOT_ALLOWED: 'InvalidUrlError',
56
+ URL_INVALID_IP_RANGE: 'InvalidUrlError',
57
+ IMAGE_URL_UNREACHABLE: 'InvalidUrlError',
58
+ INVALID_CALLBACK_URL: 'InvalidUrlError',
59
+ SLIP_NOT_FOUND: 'SlipNotFoundError',
60
+ SLIP_PENDING: 'SlipPendingError',
61
+ BANK_ACCOUNT_NOT_FOUND: 'NotFoundError',
62
+ JOB_NOT_FOUND: 'NotFoundError',
63
+ NOT_FOUND: 'NotFoundError',
64
+ BANK_ACCOUNT_DUPLICATE: 'ConflictError',
65
+ RATE_LIMIT_EXCEEDED: 'RateLimitError',
66
+ API_SERVER_ERROR: 'ServerError',
67
+ INTERNAL_SERVER_ERROR: 'ServerError',
68
+ RENEWAL_TEMPORARILY_UNAVAILABLE: 'ServiceUnavailableError',
69
+ CALLBACK_UNAVAILABLE: 'ServiceUnavailableError',
70
+ },
71
+ };
72
+ /** Error class by HTTP status when the code is unknown. */
73
+ export const statusFallback = {
74
+ 400: 'InvalidRequestError',
75
+ 401: 'AuthenticationError',
76
+ 403: 'PermissionDeniedError',
77
+ 404: 'NotFoundError',
78
+ 409: 'ConflictError',
79
+ 429: 'RateLimitError',
80
+ 500: 'ServerError',
81
+ 502: 'ServerError',
82
+ 503: 'ServiceUnavailableError',
83
+ 504: 'ServerError',
84
+ };