@easyslip/sdk 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CHANGELOG.md +8 -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,228 @@
1
+ // Response models. Field presence follows the API: an optional field (`?`) can
2
+ // be absent, `| null` can be null, and the two are kept apart when a model is serialized again.
3
+ // Enum-like fields are open strings: the known values are listed, unknown values still parse.
4
+ /** Known values of {@link MatchedAccount.type}. */
5
+ export const MatchedAccountType = {
6
+ Personal: 'PERSONAL',
7
+ Natural: 'NATURAL',
8
+ Juristic: 'JURISTIC',
9
+ };
10
+ /** `GET /banks`. Iterable; serializes to the plain array the API sends. */
11
+ export class BankList {
12
+ /** The banks, ordered by code. */
13
+ items;
14
+ constructor(items) {
15
+ this.items = items;
16
+ }
17
+ /** Number of entries. */
18
+ get length() {
19
+ return this.items.length;
20
+ }
21
+ /** Finds an entry by code, for example `004`. */
22
+ find(code) {
23
+ return this.items.find((bank) => bank.code === code);
24
+ }
25
+ [Symbol.iterator]() {
26
+ return this.items[Symbol.iterator]();
27
+ }
28
+ toJSON() {
29
+ return this.items;
30
+ }
31
+ }
32
+ /** Known values of {@link BankAccount.type}. */
33
+ export const BankAccountType = {
34
+ Natural: 'NATURAL',
35
+ Juristic: 'JURISTIC',
36
+ };
37
+ /** Known values of {@link BankAccount.matchMode}. */
38
+ export const MatchMode = {
39
+ Name: 'NAME',
40
+ Number: 'NUMBER',
41
+ NameNumber: 'NAME_NUMBER',
42
+ };
43
+ /** Known values of {@link Job.status}. */
44
+ export const JobStatus = {
45
+ Queued: 'queued',
46
+ Processing: 'processing',
47
+ Retrying: 'retrying',
48
+ Done: 'done',
49
+ Failed: 'failed',
50
+ };
51
+ export function pick(spec, raw) {
52
+ if (spec === 0 || raw === null || typeof raw !== 'object')
53
+ return raw;
54
+ if (Array.isArray(spec)) {
55
+ const item = spec[0];
56
+ return Array.isArray(raw) ? raw.map((value) => pick(item, value)) : raw;
57
+ }
58
+ if (Array.isArray(raw))
59
+ return raw;
60
+ const shape = spec;
61
+ const out = {};
62
+ for (const [key, value] of Object.entries(raw)) {
63
+ const child = shape[key];
64
+ if (child !== undefined && Object.hasOwn(shape, key))
65
+ out[key] = pick(child, value);
66
+ }
67
+ return out;
68
+ }
69
+ const autoRenew = { expired: 0, quota: 0, createdAt: 0, expiresAt: 0 };
70
+ const applicationQuota = { used: 0, max: 0, remaining: 0, totalUsed: 0 };
71
+ const infoShape = {
72
+ application: { name: 0, autoRenew, quota: applicationQuota },
73
+ branch: {
74
+ name: 0,
75
+ isActive: 0,
76
+ quota: { used: 0, totalUsed: 0 },
77
+ },
78
+ account: { email: 0, credit: 0 },
79
+ product: { name: 0 },
80
+ };
81
+ const accountNumber = { type: 0, account: 0 };
82
+ const slipAccount = {
83
+ name: { th: 0, en: 0 },
84
+ bank: accountNumber,
85
+ proxy: accountNumber,
86
+ };
87
+ const slipBank = { id: 0, name: 0, short: 0 };
88
+ const slipParty = { bank: slipBank, account: slipAccount };
89
+ const bankSlipShape = {
90
+ payload: 0,
91
+ transRef: 0,
92
+ date: 0,
93
+ countryCode: 0,
94
+ amount: {
95
+ amount: 0,
96
+ local: { amount: 0, currency: 0 },
97
+ },
98
+ fee: 0,
99
+ ref1: 0,
100
+ ref2: 0,
101
+ ref3: 0,
102
+ sender: slipParty,
103
+ receiver: { ...slipParty, merchantId: 0 },
104
+ };
105
+ const matchedAccount = {
106
+ bank: { nameTh: 0, nameEn: 0, code: 0, shortCode: 0 },
107
+ nameTh: 0,
108
+ nameEn: 0,
109
+ type: 0,
110
+ bankNumber: 0,
111
+ };
112
+ const bankSlipResultShape = {
113
+ remark: 0,
114
+ isDuplicate: 0,
115
+ matchedAccount,
116
+ amountInOrder: 0,
117
+ amountInSlip: 0,
118
+ isAmountMatched: 0,
119
+ rawSlip: bankSlipShape,
120
+ };
121
+ const trueWalletSlipShape = {
122
+ transactionId: 0,
123
+ date: 0,
124
+ amount: 0,
125
+ sender: { name: 0 },
126
+ receiver: { name: 0, phone: 0 },
127
+ };
128
+ const trueWalletResultShape = {
129
+ ...bankSlipResultShape,
130
+ rawSlip: trueWalletSlipShape,
131
+ };
132
+ const bankShape = {
133
+ code: 0,
134
+ nameTh: 0,
135
+ nameEn: 0,
136
+ shortCode: 0,
137
+ swiftCode: 0,
138
+ extraVerify: [{ value: 0, label: 0 }],
139
+ };
140
+ const bankAccountShape = {
141
+ id: 0,
142
+ bankCode: 0,
143
+ bankNumber: 0,
144
+ nameTh: 0,
145
+ nameEn: 0,
146
+ type: 0,
147
+ extraVerify: 0,
148
+ matchMode: 0,
149
+ createdAt: 0,
150
+ updatedAt: 0,
151
+ deletedAt: 0,
152
+ };
153
+ const bankAccountPageShape = {
154
+ items: [bankAccountShape],
155
+ total: 0,
156
+ page: 0,
157
+ limit: 0,
158
+ };
159
+ const jobShape = {
160
+ jobId: 0,
161
+ batchId: 0,
162
+ status: 0,
163
+ result: { status: 0, data: bankSlipResultShape },
164
+ error: {
165
+ code: 0,
166
+ message: 0,
167
+ webhook: 0,
168
+ url: 0,
169
+ status: 0,
170
+ at: 0,
171
+ },
172
+ attempts: 0,
173
+ createdAt: 0,
174
+ updatedAt: 0,
175
+ branchId: 0,
176
+ serviceId: 0,
177
+ callbackEventId: 0,
178
+ callbackProtocol: 0,
179
+ callbackDelivery: { state: 0, httpStatus: 0 },
180
+ };
181
+ const webhookEventShape = {
182
+ jobId: 0,
183
+ batchId: 0,
184
+ status: 0,
185
+ data: bankSlipResultShape,
186
+ error: { code: 0, message: 0 },
187
+ timestamp: 0,
188
+ };
189
+ /** Model name to shape, for every model a response can decode into. */
190
+ export const shapes = {
191
+ Info: infoShape,
192
+ BankSlip: bankSlipShape,
193
+ BankSlipResult: bankSlipResultShape,
194
+ TrueWalletSlip: trueWalletSlipShape,
195
+ TrueWalletResult: trueWalletResultShape,
196
+ BankAccount: bankAccountShape,
197
+ BankAccountPage: bankAccountPageShape,
198
+ LinkResult: { linked: 0 },
199
+ UnlinkResult: { unlinked: 0 },
200
+ JobSubmission: { jobId: 0 },
201
+ BatchSubmission: {
202
+ batchId: 0,
203
+ jobs: [{ jobId: 0, index: 0 }],
204
+ },
205
+ Job: jobShape,
206
+ WebhookEvent: webhookEventShape,
207
+ V1Me: {
208
+ application: 0,
209
+ usedQuota: 0,
210
+ maxQuota: 0,
211
+ remainingQuota: 0,
212
+ expiredAt: 0,
213
+ currentCredit: 0,
214
+ },
215
+ QrCode: { image: 0, mime: 0, payload: 0 },
216
+ };
217
+ /** Builds a model from decoded JSON, keeping only the fields the model knows. */
218
+ export function parseModel(name, raw) {
219
+ if (name === 'BankList') {
220
+ const items = Array.isArray(raw) ? pick([bankShape], raw) : [];
221
+ return new BankList(items);
222
+ }
223
+ const value = pick(shapes[name], raw);
224
+ if (value === null || typeof value !== 'object') {
225
+ return {};
226
+ }
227
+ return value;
228
+ }
@@ -0,0 +1 @@
1
+ {"type":"module"}
@@ -0,0 +1,63 @@
1
+ import type { RequestOptions, Transport } from '../core/http.js';
2
+ import type { WithMeta } from '../core/meta.js';
3
+ import type { BankAccount, BankAccountPage, BankAccountType, LinkResult, MatchMode, Open, UnlinkResult } from '../models.js';
4
+ /** The receiving account types a request may send: `NATURAL` or `JURISTIC`. */
5
+ export type AccountType = (typeof BankAccountType)[keyof typeof BankAccountType];
6
+ type AccountMatchMode = Open<(typeof MatchMode)[keyof typeof MatchMode]>;
7
+ /** Filters and paging for the list calls. */
8
+ export interface ListBankAccountsParams {
9
+ /** `NATURAL` or `JURISTIC`. */
10
+ type?: AccountType;
11
+ /** Only accounts at this bank code. */
12
+ bankCode?: string;
13
+ /** Page number, from 1. */
14
+ page?: number;
15
+ /** Page size, 1 to 100. The API default is 20. */
16
+ limit?: number;
17
+ }
18
+ export interface CreateBankAccountParams {
19
+ /** A code from `client.banks.list()`. */
20
+ bankCode: string;
21
+ bankNumber: string;
22
+ nameTh: string;
23
+ nameEn: string;
24
+ type: AccountType;
25
+ /** One of the bank's `extraVerify[].value` options. */
26
+ extraVerify?: string;
27
+ /** PromptPay accounts only: `NAME`, `NUMBER` or `NAME_NUMBER`. */
28
+ matchMode?: AccountMatchMode;
29
+ }
30
+ export interface UpdateBankAccountParams {
31
+ bankCode?: string;
32
+ bankNumber?: string;
33
+ nameTh?: string;
34
+ nameEn?: string;
35
+ type?: AccountType;
36
+ /** Leave out to keep, a string to set, `null` to clear. */
37
+ extraVerify?: string | null;
38
+ matchMode?: AccountMatchMode;
39
+ }
40
+ /** Receiving bank accounts used by `matchAccount` (`client.bankAccounts`). */
41
+ export declare class BankAccounts {
42
+ #private;
43
+ constructor(transport: Transport);
44
+ /** One page of the accounts linked to this branch. */
45
+ list(params?: ListBankAccountsParams, options?: RequestOptions): Promise<WithMeta<BankAccountPage>>;
46
+ /** One page of every active account of the service, linked to this branch or not. */
47
+ listAll(params?: ListBankAccountsParams, options?: RequestOptions): Promise<WithMeta<BankAccountPage>>;
48
+ /** Gets one account linked to this branch. */
49
+ get(id: number, options?: RequestOptions): Promise<WithMeta<BankAccount>>;
50
+ /** Registers an account on the service and links it to this branch. */
51
+ create(params: CreateBankAccountParams, options?: RequestOptions): Promise<WithMeta<BankAccount>>;
52
+ /** Changes the fields you pass. Pass `extraVerify: null` to clear it. */
53
+ update(id: number, params: UpdateBankAccountParams, options?: RequestOptions): Promise<WithMeta<BankAccount>>;
54
+ /** Links an existing service account to this branch. Linking twice is fine. */
55
+ link(id: number, options?: RequestOptions): Promise<WithMeta<LinkResult>>;
56
+ /** Unlinks an account from this branch. The account stays on the service. */
57
+ unlink(id: number, options?: RequestOptions): Promise<WithMeta<UnlinkResult>>;
58
+ /** Walks every page of {@link list}, one request per page (100 accounts by default). */
59
+ iterate(params?: ListBankAccountsParams, options?: RequestOptions): AsyncGenerator<BankAccount>;
60
+ /** Walks every page of {@link listAll}. */
61
+ iterateAll(params?: ListBankAccountsParams, options?: RequestOptions): AsyncGenerator<BankAccount>;
62
+ }
63
+ export {};
@@ -0,0 +1,122 @@
1
+ import { call, defined, requestOptions, requireId } from '../core/call.js';
2
+ const CREATE_KEYS = [
3
+ 'bankCode',
4
+ 'bankNumber',
5
+ 'nameTh',
6
+ 'nameEn',
7
+ 'type',
8
+ 'extraVerify',
9
+ 'matchMode',
10
+ ];
11
+ function listQuery(params) {
12
+ return {
13
+ type: params?.type,
14
+ bankCode: params?.bankCode,
15
+ page: params?.page === undefined ? undefined : String(params.page),
16
+ limit: params?.limit === undefined ? undefined : String(params.limit),
17
+ };
18
+ }
19
+ /** Receiving bank accounts used by `matchAccount` (`client.bankAccounts`). */
20
+ export class BankAccounts {
21
+ #t;
22
+ constructor(transport) {
23
+ this.#t = transport;
24
+ }
25
+ /** One page of the accounts linked to this branch. */
26
+ async list(params, options) {
27
+ return call(this.#t, 'BankAccountPage', {
28
+ ...requestOptions(options),
29
+ api: 'v2',
30
+ method: 'GET',
31
+ path: '/bank-accounts',
32
+ query: listQuery(params),
33
+ retry: 'safe',
34
+ });
35
+ }
36
+ /** One page of every active account of the service, linked to this branch or not. */
37
+ async listAll(params, options) {
38
+ return call(this.#t, 'BankAccountPage', {
39
+ ...requestOptions(options),
40
+ api: 'v2',
41
+ method: 'GET',
42
+ path: '/bank-accounts/all',
43
+ query: listQuery(params),
44
+ retry: 'safe',
45
+ });
46
+ }
47
+ /** Gets one account linked to this branch. */
48
+ async get(id, options) {
49
+ requireId(id);
50
+ return call(this.#t, 'BankAccount', {
51
+ ...requestOptions(options),
52
+ api: 'v2',
53
+ method: 'GET',
54
+ path: `/bank-accounts/${id}`,
55
+ retry: 'safe',
56
+ });
57
+ }
58
+ /** Registers an account on the service and links it to this branch. */
59
+ async create(params, options) {
60
+ return call(this.#t, 'BankAccount', {
61
+ ...requestOptions(options),
62
+ api: 'v2',
63
+ method: 'POST',
64
+ path: '/bank-accounts',
65
+ json: defined(params, CREATE_KEYS),
66
+ retry: 'write',
67
+ });
68
+ }
69
+ /** Changes the fields you pass. Pass `extraVerify: null` to clear it. */
70
+ async update(id, params, options) {
71
+ requireId(id);
72
+ return call(this.#t, 'BankAccount', {
73
+ ...requestOptions(options),
74
+ api: 'v2',
75
+ method: 'PATCH',
76
+ path: `/bank-accounts/${id}`,
77
+ json: defined(params, CREATE_KEYS),
78
+ retry: 'write',
79
+ });
80
+ }
81
+ /** Links an existing service account to this branch. Linking twice is fine. */
82
+ async link(id, options) {
83
+ requireId(id);
84
+ return call(this.#t, 'LinkResult', {
85
+ ...requestOptions(options),
86
+ api: 'v2',
87
+ method: 'POST',
88
+ path: `/bank-accounts/${id}/link`,
89
+ retry: 'safe',
90
+ });
91
+ }
92
+ /** Unlinks an account from this branch. The account stays on the service. */
93
+ async unlink(id, options) {
94
+ requireId(id);
95
+ return call(this.#t, 'UnlinkResult', {
96
+ ...requestOptions(options),
97
+ api: 'v2',
98
+ method: 'DELETE',
99
+ path: `/bank-accounts/${id}/link`,
100
+ retry: 'write',
101
+ });
102
+ }
103
+ /** Walks every page of {@link list}, one request per page (100 accounts by default). */
104
+ iterate(params, options) {
105
+ return this.#walk((p) => this.list(p, options), params);
106
+ }
107
+ /** Walks every page of {@link listAll}. */
108
+ iterateAll(params, options) {
109
+ return this.#walk((p) => this.listAll(p, options), params);
110
+ }
111
+ async *#walk(fetchPage, params) {
112
+ let page = params?.page ?? 1;
113
+ const limit = params?.limit ?? 100;
114
+ while (true) {
115
+ const result = await fetchPage({ ...params, page, limit });
116
+ yield* result.items;
117
+ if (result.items.length === 0 || page * limit >= result.total)
118
+ return;
119
+ page++;
120
+ }
121
+ }
122
+ }
@@ -0,0 +1,10 @@
1
+ import type { RequestOptions, Transport } from '../core/http.js';
2
+ import type { WithMeta } from '../core/meta.js';
3
+ import type { BankList } from '../models.js';
4
+ /** Supported banks and receiving kinds (`client.banks`). */
5
+ export declare class Banks {
6
+ #private;
7
+ constructor(transport: Transport);
8
+ /** Lists the bank codes you can register accounts with, and their `extraVerify` options. */
9
+ list(options?: RequestOptions): Promise<WithMeta<BankList>>;
10
+ }
@@ -0,0 +1,18 @@
1
+ import { call, requestOptions } from '../core/call.js';
2
+ /** Supported banks and receiving kinds (`client.banks`). */
3
+ export class Banks {
4
+ #t;
5
+ constructor(transport) {
6
+ this.#t = transport;
7
+ }
8
+ /** Lists the bank codes you can register accounts with, and their `extraVerify` options. */
9
+ async list(options) {
10
+ return call(this.#t, 'BankList', {
11
+ ...requestOptions(options),
12
+ api: 'v2',
13
+ method: 'GET',
14
+ path: '/banks',
15
+ retry: 'safe',
16
+ });
17
+ }
18
+ }
@@ -0,0 +1,64 @@
1
+ import type { RequestOptions, Transport } from '../core/http.js';
2
+ import type { WithMeta } from '../core/meta.js';
3
+ import type { BatchSubmission, Job, JobSubmission } from '../models.js';
4
+ import { type VerifyOptions } from './verify.js';
5
+ /** Most slips one batch call accepts. {@link Jobs.submitBankMany} splits larger lists. */
6
+ export declare const BATCH_MAX = 100;
7
+ /** Options of an async verify call. */
8
+ export interface AsyncVerifyOptions extends VerifyOptions {
9
+ /**
10
+ * https URL the result webhook is posted to, up to 255 characters. Required unless the
11
+ * branch has a default webhook URL.
12
+ */
13
+ callbackUrl?: string;
14
+ }
15
+ /** One slip of a batch. */
16
+ export interface BatchSlip extends VerifyOptions {
17
+ /** QR payload string. */
18
+ payload: string;
19
+ }
20
+ export interface BatchOptions extends RequestOptions {
21
+ /** https URL every job's webhook is posted to. */
22
+ callbackUrl?: string;
23
+ }
24
+ export interface WaitForJobOptions {
25
+ /** Time between polls in milliseconds. Default 2000, minimum 500. */
26
+ interval?: number;
27
+ /**
28
+ * Give up after this many milliseconds. Default 600000 (10 minutes). One deadline for the
29
+ * whole wait: requests still running at the deadline are cancelled, and an answer that
30
+ * arrives after it is not returned.
31
+ */
32
+ timeout?: number;
33
+ /** Stops waiting; the call then rejects with the signal's reason. */
34
+ signal?: AbortSignal;
35
+ }
36
+ /**
37
+ * Async bank slip verification (`client.jobs`). Submits are billed when the job verifies the
38
+ * slip; like the sync calls they are never retried once the request may have arrived.
39
+ */
40
+ export declare class Jobs {
41
+ #private;
42
+ constructor(transport: Transport);
43
+ /** Queues one QR payload. The result arrives on the webhook or through {@link get}. */
44
+ submitBank(payload: string, options?: AsyncVerifyOptions & RequestOptions): Promise<WithMeta<JobSubmission>>;
45
+ /** Queues 1 to 100 payloads in one call. Each slip becomes its own job. */
46
+ submitBankBatch(slips: readonly BatchSlip[], options?: BatchOptions): Promise<WithMeta<BatchSubmission>>;
47
+ /**
48
+ * Queues any number of payloads, 100 per call, one call after another. Quota is the same as
49
+ * one big batch: each slip is billed when its job verifies it. If a call fails, the batches
50
+ * already accepted keep running and {@link BatchSubmitError} lists them.
51
+ */
52
+ submitBankMany(slips: readonly BatchSlip[], options?: BatchOptions): Promise<BatchSubmission[]>;
53
+ /** Gets a job by id. */
54
+ get(jobId: string, options?: RequestOptions): Promise<WithMeta<Job>>;
55
+ /**
56
+ * Polls a job until its status is `done` or `failed` and returns it. A failed job is
57
+ * returned, not thrown. `timeout` is one deadline for the whole wait: each
58
+ * poll and its retries get only the time left, a request still running at the deadline is
59
+ * cancelled, and an answer that arrives after the deadline is not returned. Then it throws
60
+ * {@link JobWaitTimeoutError} with the last job received in time. Aborting `signal` rejects
61
+ * with the signal's reason instead.
62
+ */
63
+ waitForJob(jobId: string, options?: WaitForJobOptions): Promise<WithMeta<Job>>;
64
+ }
@@ -0,0 +1,173 @@
1
+ import { call, defined, requestOptions, requireString } from '../core/call.js';
2
+ import { BatchSubmitError, InputError, JobWaitTimeoutError, RequestTimeoutError, } from '../core/errors.js';
3
+ import { verifyFields } from './verify.js';
4
+ /** Most slips one batch call accepts. {@link Jobs.submitBankMany} splits larger lists. */
5
+ export const BATCH_MAX = 100;
6
+ const SLIP_KEYS = ['payload', 'remark', 'matchAccount', 'matchAmount', 'checkDuplicate'];
7
+ /**
8
+ * Async bank slip verification (`client.jobs`). Submits are billed when the job verifies the
9
+ * slip; like the sync calls they are never retried once the request may have arrived.
10
+ */
11
+ export class Jobs {
12
+ #t;
13
+ #sleep;
14
+ #timeout;
15
+ constructor(transport) {
16
+ this.#t = transport;
17
+ this.#sleep = transport.config.sleep;
18
+ this.#timeout = transport.config.timeout;
19
+ }
20
+ /** Queues one QR payload. The result arrives on the webhook or through {@link get}. */
21
+ async submitBank(payload, options) {
22
+ requireString(payload, 'payload');
23
+ const json = { payload, ...verifyFields(options) };
24
+ if (options?.callbackUrl !== undefined)
25
+ json.callbackUrl = options.callbackUrl;
26
+ return call(this.#t, 'JobSubmission', {
27
+ ...requestOptions(options),
28
+ api: 'v2',
29
+ method: 'POST',
30
+ path: '/verify/bank/async',
31
+ json,
32
+ retry: 'billed',
33
+ });
34
+ }
35
+ /** Queues 1 to 100 payloads in one call. Each slip becomes its own job. */
36
+ async submitBankBatch(slips, options) {
37
+ if (!Array.isArray(slips) || slips.length === 0) {
38
+ throw new InputError('EMPTY_BATCH', 'slips must contain at least one slip');
39
+ }
40
+ if (slips.length > BATCH_MAX) {
41
+ throw new InputError('BATCH_TOO_LARGE', `a batch takes at most ${BATCH_MAX} slips; use submitBankMany for more`);
42
+ }
43
+ for (const slip of slips)
44
+ requireString(slip?.payload, 'slip payload');
45
+ const json = {};
46
+ if (options?.callbackUrl !== undefined)
47
+ json.callbackUrl = options.callbackUrl;
48
+ json.slips = slips.map((slip) => defined(slip, SLIP_KEYS));
49
+ return call(this.#t, 'BatchSubmission', {
50
+ ...requestOptions(options),
51
+ api: 'v2',
52
+ method: 'POST',
53
+ path: '/verify/bank/batch',
54
+ json,
55
+ retry: 'billed',
56
+ });
57
+ }
58
+ /**
59
+ * Queues any number of payloads, 100 per call, one call after another. Quota is the same as
60
+ * one big batch: each slip is billed when its job verifies it. If a call fails, the batches
61
+ * already accepted keep running and {@link BatchSubmitError} lists them.
62
+ */
63
+ async submitBankMany(slips, options) {
64
+ if (!Array.isArray(slips) || slips.length === 0) {
65
+ throw new InputError('EMPTY_BATCH', 'slips must contain at least one slip');
66
+ }
67
+ const submitted = [];
68
+ for (let start = 0, chunk = 0; start < slips.length; start += BATCH_MAX, chunk++) {
69
+ try {
70
+ submitted.push(await this.submitBankBatch(slips.slice(start, start + BATCH_MAX), options));
71
+ }
72
+ catch (cause) {
73
+ throw new BatchSubmitError(submitted, chunk, cause);
74
+ }
75
+ }
76
+ return submitted;
77
+ }
78
+ /** Gets a job by id. */
79
+ async get(jobId, options) {
80
+ requireString(jobId, 'jobId');
81
+ return call(this.#t, 'Job', {
82
+ ...requestOptions(options),
83
+ api: 'v2',
84
+ method: 'GET',
85
+ path: `/verify/bank/jobs/${encodeURIComponent(jobId)}`,
86
+ retry: 'safe',
87
+ });
88
+ }
89
+ /**
90
+ * Polls a job until its status is `done` or `failed` and returns it. A failed job is
91
+ * returned, not thrown. `timeout` is one deadline for the whole wait: each
92
+ * poll and its retries get only the time left, a request still running at the deadline is
93
+ * cancelled, and an answer that arrives after the deadline is not returned. Then it throws
94
+ * {@link JobWaitTimeoutError} with the last job received in time. Aborting `signal` rejects
95
+ * with the signal's reason instead.
96
+ */
97
+ async waitForJob(jobId, options) {
98
+ requireString(jobId, 'jobId');
99
+ const interval = Math.max(500, options?.interval ?? 2000);
100
+ const timeout = options?.timeout ?? 600_000;
101
+ if (!Number.isFinite(timeout) || timeout < 0) {
102
+ throw new InputError('INVALID_ARGUMENT', 'timeout must be a number >= 0');
103
+ }
104
+ const caller = options?.signal;
105
+ caller?.throwIfAborted();
106
+ const deadline = Date.now() + timeout;
107
+ let last = null;
108
+ const expired = () => new JobWaitTimeoutError(`job ${jobId} ${last ? `still ${last.status}` : 'not read'} after ${timeout} ms`, last);
109
+ // One signal for every request and wait: aborted by the caller or at the deadline.
110
+ const budget = new AbortController();
111
+ const reason = new Error('waitForJob deadline');
112
+ const timer = setTimeout(() => budget.abort(reason), timeout);
113
+ const onAbort = () => budget.abort(caller?.reason);
114
+ caller?.addEventListener('abort', onAbort, { once: true });
115
+ const deadlinePassed = () => budget.signal.reason === reason && !caller?.aborted;
116
+ // Settles when the budget is aborted, so a custom fetch or sleep that ignores the signal
117
+ // cannot hold the call past the deadline.
118
+ const stopped = new Promise((_, reject) => {
119
+ budget.signal.addEventListener('abort', () => reject(budget.signal.reason), {
120
+ once: true,
121
+ });
122
+ });
123
+ stopped.catch(() => { });
124
+ try {
125
+ while (true) {
126
+ const left = deadline - Date.now();
127
+ if (left <= 0)
128
+ throw expired();
129
+ // The attempt timeout is cut to the time left, so its timeout is the deadline too.
130
+ const capped = left < this.#timeout;
131
+ let job;
132
+ try {
133
+ job = await Promise.race([
134
+ this.get(jobId, {
135
+ signal: budget.signal,
136
+ timeout: Math.max(1, Math.min(this.#timeout, left)),
137
+ }),
138
+ stopped,
139
+ ]);
140
+ }
141
+ catch (error) {
142
+ if (deadlinePassed())
143
+ throw expired();
144
+ if (capped && error instanceof RequestTimeoutError && !caller?.aborted) {
145
+ throw expired();
146
+ }
147
+ throw error;
148
+ }
149
+ // A request that ignored cancellation can still answer late: do not return it.
150
+ if (Date.now() >= deadline)
151
+ throw expired();
152
+ last = job;
153
+ if (job.status === 'done' || job.status === 'failed')
154
+ return job;
155
+ const wait = Math.min(interval, deadline - Date.now());
156
+ if (wait <= 0)
157
+ throw expired();
158
+ try {
159
+ await Promise.race([this.#sleep(wait, budget.signal), stopped]);
160
+ }
161
+ catch (error) {
162
+ if (deadlinePassed())
163
+ throw expired();
164
+ throw error;
165
+ }
166
+ }
167
+ }
168
+ finally {
169
+ clearTimeout(timer);
170
+ caller?.removeEventListener('abort', onAbort);
171
+ }
172
+ }
173
+ }