@billionaire-sh/node-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.
@@ -0,0 +1,406 @@
1
+ var __defProp$1 = Object.defineProperty;
2
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+ class TokenManager {
5
+ constructor(clientId, clientSecret, tokenEndpoint, userEntityId) {
6
+ this.clientId = clientId;
7
+ this.clientSecret = clientSecret;
8
+ this.tokenEndpoint = tokenEndpoint;
9
+ this.userEntityId = userEntityId;
10
+ __publicField$1(this, "accessToken", null);
11
+ __publicField$1(this, "tokenExpiresAt", 0);
12
+ __publicField$1(this, "refreshPromise", null);
13
+ __publicField$1(this, "defaultEntityId");
14
+ }
15
+ async initialize() {
16
+ await this.refreshToken();
17
+ }
18
+ async getToken() {
19
+ if (this.accessToken && Date.now() < this.tokenExpiresAt - 3e5) {
20
+ return this.accessToken;
21
+ }
22
+ return this.refreshToken();
23
+ }
24
+ getEntityId() {
25
+ if (this.userEntityId) {
26
+ return this.userEntityId;
27
+ }
28
+ if (!this.defaultEntityId) {
29
+ throw new Error(
30
+ "No entity ID available. The robot account may not be associated with any entities."
31
+ );
32
+ }
33
+ return this.defaultEntityId;
34
+ }
35
+ /**
36
+ * Async counterpart to {@link getEntityId}. Fetches the token if it
37
+ * hasn't been loaded yet (which is what populates `defaultEntityId` via
38
+ * `setDefaultEntityId`), then returns the entity id.
39
+ *
40
+ * Prefer this over `getEntityId()` from request paths — a cold SDK
41
+ * instance will otherwise synchronously throw "No entity ID available"
42
+ * before the token has had a chance to load.
43
+ */
44
+ async getEntityIdAsync() {
45
+ if (this.userEntityId) {
46
+ return this.userEntityId;
47
+ }
48
+ if (!this.defaultEntityId) {
49
+ await this.getToken();
50
+ }
51
+ return this.getEntityId();
52
+ }
53
+ async refreshToken() {
54
+ if (this.refreshPromise) return this.refreshPromise;
55
+ this.refreshPromise = fetch(this.tokenEndpoint, {
56
+ method: "POST",
57
+ headers: { "Content-Type": "application/json" },
58
+ body: JSON.stringify({
59
+ clientId: this.clientId,
60
+ clientSecret: this.clientSecret
61
+ }),
62
+ signal: AbortSignal.timeout(36e4)
63
+ }).then(async (response) => {
64
+ if (!response.ok) {
65
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
66
+ }
67
+ return response.json();
68
+ }).then((data) => {
69
+ this.accessToken = data.accessToken;
70
+ this.tokenExpiresAt = Date.now() + data.expiresIn * 1e3;
71
+ this.setDefaultEntityId();
72
+ return this.accessToken;
73
+ }).catch((error) => {
74
+ throw error;
75
+ }).finally(() => {
76
+ this.refreshPromise = null;
77
+ });
78
+ return this.refreshPromise;
79
+ }
80
+ setDefaultEntityId() {
81
+ if (this.userEntityId || !this.accessToken) return;
82
+ try {
83
+ const [, payload] = this.accessToken.split(".");
84
+ const decoded = JSON.parse(
85
+ Buffer.from(payload, "base64").toString()
86
+ );
87
+ if (!decoded.entities || decoded.entities.length === 0) {
88
+ this.defaultEntityId = void 0;
89
+ return;
90
+ }
91
+ this.defaultEntityId = decoded.entities[0];
92
+ } catch {
93
+ throw new Error("Failed to parse entity ID from token");
94
+ }
95
+ }
96
+ }
97
+
98
+ class BaseResource {
99
+ constructor(tokenManager, baseUrl, resourcePath) {
100
+ this.tokenManager = tokenManager;
101
+ this.baseUrl = baseUrl;
102
+ this.resourcePath = resourcePath;
103
+ }
104
+ /**
105
+ * What the resource's path hangs below: the robot's entity
106
+ * (`/entities/{entityId}`). A resource of the platform's own API, which
107
+ * acts for the entity that owns the platform, overrides it (KLVR-2229).
108
+ * Read after the token is fetched — the entity id comes with it.
109
+ */
110
+ rootPath() {
111
+ return `/entities/${this.tokenManager.getEntityId()}`;
112
+ }
113
+ async request(method, path, data, cacheOptions) {
114
+ const token = await this.tokenManager.getToken();
115
+ const url = `${this.baseUrl}${this.rootPath()}${this.resourcePath}${path}`;
116
+ const init = {
117
+ method,
118
+ headers: {
119
+ Authorization: `Bearer ${token}`,
120
+ "Content-Type": "application/json"
121
+ },
122
+ body: data ? JSON.stringify(data) : void 0,
123
+ signal: AbortSignal.timeout(36e4),
124
+ cache: cacheOptions?.cache ?? "no-store",
125
+ ...cacheOptions?.next ? { next: cacheOptions.next } : {}
126
+ };
127
+ const response = await fetch(url, init);
128
+ if (!response.ok) {
129
+ let body = "";
130
+ try {
131
+ body = await response.text();
132
+ } catch {
133
+ }
134
+ throw new Error(
135
+ `HTTP ${response.status}: ${response.statusText}${body ? ` \u2014 ${body}` : ""}`
136
+ );
137
+ }
138
+ return response.json();
139
+ }
140
+ /**
141
+ * Multipart counterpart to `request`. Skips the JSON Content-Type
142
+ * default — `fetch` sets `multipart/form-data; boundary=…`
143
+ * automatically when the body is a `FormData`. Use for binary uploads.
144
+ */
145
+ async requestMultipart(method, path, formData) {
146
+ const token = await this.tokenManager.getToken();
147
+ const url = `${this.baseUrl}${this.rootPath()}${this.resourcePath}${path}`;
148
+ const response = await fetch(url, {
149
+ method,
150
+ headers: {
151
+ Authorization: `Bearer ${token}`
152
+ // Intentionally NO Content-Type — fetch sets the boundary.
153
+ },
154
+ body: formData,
155
+ cache: "no-store",
156
+ signal: AbortSignal.timeout(36e4)
157
+ });
158
+ if (!response.ok) {
159
+ let body = "";
160
+ try {
161
+ body = await response.text();
162
+ } catch {
163
+ }
164
+ throw new Error(
165
+ `HTTP ${response.status}: ${response.statusText}${body ? ` \u2014 ${body}` : ""}`
166
+ );
167
+ }
168
+ return response.json();
169
+ }
170
+ }
171
+
172
+ class PlatformCustomersResource extends BaseResource {
173
+ constructor(tokenManager, baseUrl) {
174
+ super(tokenManager, baseUrl, "/customers");
175
+ }
176
+ rootPath() {
177
+ return "/platform";
178
+ }
179
+ /**
180
+ * Hand over a paying customer's details as they stand after a change;
181
+ * the entity's party for the customer takes them, or is filed with them.
182
+ * Idempotent: the same details again change nothing.
183
+ * @param request - The platform's name and its customer's details
184
+ * @returns The party the customer is in the entity's books
185
+ */
186
+ async process(request) {
187
+ return this.request("POST", "", request);
188
+ }
189
+ /**
190
+ * Read back the party a customer is in the entity's books, as the books
191
+ * keep it today (BLNR-1979). Throws `HTTP 404` where the platform has
192
+ * handed over no customer of the reference.
193
+ * @param customer - The platform, as it names itself, and its own
194
+ * reference of its customer
195
+ * @returns The party: its name, email, VAT ID, tax number and billing
196
+ * address
197
+ */
198
+ async get({
199
+ platform,
200
+ reference
201
+ }) {
202
+ return this.request(
203
+ "GET",
204
+ `/${encodeURIComponent(reference)}?${new URLSearchParams({ platform })}`
205
+ );
206
+ }
207
+ }
208
+
209
+ class PlatformInvoicesResource extends BaseResource {
210
+ constructor(tokenManager, baseUrl) {
211
+ super(tokenManager, baseUrl, "/invoices");
212
+ }
213
+ rootPath() {
214
+ return "/platform";
215
+ }
216
+ /**
217
+ * Hand over what the platform invoiced one of its customers; the entity
218
+ * issues its own invoice for it. Idempotent on `stripeInvoiceId`.
219
+ * @param request - The platform's invoice, its lines and its customer
220
+ * @returns What became of it, and the entity's invoice once issued
221
+ */
222
+ async process(request) {
223
+ return this.request("POST", "", request);
224
+ }
225
+ /**
226
+ * The tax the entity puts on what the platform charges each of these
227
+ * customers — by country and whether it is a consumer — so the payment
228
+ * provider charges exactly what the entity's invoice will say. The
229
+ * platform computes no tax of its own.
230
+ * @param request - The customers, each with the platform's own key
231
+ * @returns Each key's tax, null where the entity charges none
232
+ */
233
+ async chargeTaxes(request) {
234
+ return this.request(
235
+ "POST",
236
+ "/charge-taxes",
237
+ request
238
+ );
239
+ }
240
+ /**
241
+ * Preview the invoice the entity would issue for what the platform is
242
+ * about to charge — composed by billionaire's invoicing engine exactly as
243
+ * `process` issues it, nothing issued.
244
+ * @param request - The lines to charge, their currency, the day and the
245
+ * total the payment provider will charge
246
+ * @returns The invoice's net, VAT per rate, gross and lines — or why the
247
+ * entity would issue none
248
+ */
249
+ async preview(request) {
250
+ return this.request(
251
+ "POST",
252
+ "/preview",
253
+ request
254
+ );
255
+ }
256
+ /**
257
+ * The platform's invoices the entity's books still show as unpaid, the
258
+ * oldest first, a page at a time — for a follow-up that asks the payment
259
+ * provider about each and hands a payment or void it missed back through
260
+ * `processPayment` / `processVoid`.
261
+ * @param request - The platform (`filters.platform`) and the page
262
+ * @returns Each invoice with the payment provider's id of the platform's
263
+ * invoice it documents
264
+ */
265
+ async listOpen(request) {
266
+ return this.request(
267
+ "POST",
268
+ "/open",
269
+ request
270
+ );
271
+ }
272
+ /**
273
+ * The invoices the entity issued to the tenants of one of the platform's
274
+ * accounts, the newest first — what the platform shows the account as its
275
+ * invoices (BLNR-626).
276
+ * @param request - The platform (`filters.platform`) and its own ids of
277
+ * the account's tenants (`filters.tenantIds`)
278
+ * @returns Each invoice's number, dates, amount, state, the tenant it is
279
+ * addressed to, and whether its PDF is kept
280
+ */
281
+ async listForCustomers(request) {
282
+ return this.request(
283
+ "POST",
284
+ "/customers",
285
+ request
286
+ );
287
+ }
288
+ /**
289
+ * What the entity invoiced the platform's customers since a day, summed
290
+ * per month of issue, currency and state (KLVR-2470) — what the
291
+ * platform's Revenue tab shows of the entity's books.
292
+ * @param request - The platform (`filters.platform`) and the first day of
293
+ * issue read (`filters.since`)
294
+ * @returns Per month, currency and state what was invoiced, tax included
295
+ */
296
+ async listMonths(request) {
297
+ return this.request(
298
+ "POST",
299
+ "/months",
300
+ request
301
+ );
302
+ }
303
+ /**
304
+ * A link to the PDF of an invoice the entity issued to one of these
305
+ * tenants, valid for a few minutes — asked for the moment the account
306
+ * opens it (BLNR-626). An invoice of any other tenant answers 404.
307
+ * @param stripeInvoiceId - The payment provider's id of the platform's invoice
308
+ * @param request - The platform and its own ids of the account's tenants
309
+ */
310
+ async documentUrl(stripeInvoiceId, request) {
311
+ return this.request(
312
+ "POST",
313
+ `/${encodeURIComponent(stripeInvoiceId)}/document`,
314
+ request
315
+ );
316
+ }
317
+ /**
318
+ * Get the entity's invoice for a platform invoice.
319
+ * @param stripeInvoiceId - The payment provider's id of the platform's invoice
320
+ * @returns The invoice's number, state and amounts
321
+ */
322
+ async get(stripeInvoiceId) {
323
+ return this.request(
324
+ "GET",
325
+ `/${encodeURIComponent(stripeInvoiceId)}`
326
+ );
327
+ }
328
+ /**
329
+ * Hand over that a platform invoice was paid; the entity records the
330
+ * money and settles its invoice. Idempotent on `stripeInvoiceId`.
331
+ * @param stripeInvoiceId - The payment provider's id of the paid invoice
332
+ * @param request - When it was paid, and how much
333
+ */
334
+ async processPayment(stripeInvoiceId, request) {
335
+ return this.request(
336
+ "POST",
337
+ `/${encodeURIComponent(stripeInvoiceId)}/payments`,
338
+ request
339
+ );
340
+ }
341
+ /**
342
+ * Hand over that the payment provider voided a platform invoice; the
343
+ * entity cancels its invoice for it.
344
+ * @param stripeInvoiceId - The payment provider's id of the voided invoice
345
+ * @param request - When it was voided
346
+ */
347
+ async processVoid(stripeInvoiceId, request) {
348
+ return this.request(
349
+ "POST",
350
+ `/${encodeURIComponent(stripeInvoiceId)}/void`,
351
+ request
352
+ );
353
+ }
354
+ /**
355
+ * Hand over a credit note the payment provider issued for a platform
356
+ * invoice — money back to the card, a credit on the customer's balance.
357
+ * One for all of it cancels the entity's invoice, and what the customer
358
+ * had paid becomes their credit; one for part of it corrects the invoice
359
+ * by the lines it takes back, by a correction invoice of its own
360
+ * (`corrected`). One whose lines do not say which part it takes back is
361
+ * answered `partial_credit` and changes nothing. What it sent back to the
362
+ * card (`refundedAmount`, with the `paymentProviderAccount` it left) is
363
+ * recorded as an outgoing payment on the money account of that balance
364
+ * and pays back the customer's credit; `refund` answers what became of
365
+ * it.
366
+ * @param stripeInvoiceId - The payment provider's id of the credited invoice
367
+ * @param request - The credit note, when it was issued, what it takes back and what it refunded
368
+ */
369
+ async processCredit(stripeInvoiceId, request) {
370
+ return this.request(
371
+ "POST",
372
+ `/${encodeURIComponent(stripeInvoiceId)}/credit`,
373
+ request
374
+ );
375
+ }
376
+ }
377
+
378
+ var __defProp = Object.defineProperty;
379
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
380
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
381
+ class BLNRClient {
382
+ constructor(config) {
383
+ __publicField(this, "platformCustomers");
384
+ __publicField(this, "platformInvoices");
385
+ __publicField(this, "baseUrl");
386
+ __publicField(this, "tokenManager");
387
+ this.baseUrl = config.baseUrl || "https://billionaire.sh/api";
388
+ const tokenUrl = config.tokenUrl || `${this.baseUrl}/m2m/token`;
389
+ this.tokenManager = new TokenManager(
390
+ config.clientId,
391
+ config.clientSecret,
392
+ tokenUrl,
393
+ config.entityId
394
+ );
395
+ this.platformCustomers = new PlatformCustomersResource(
396
+ this.tokenManager,
397
+ this.baseUrl
398
+ );
399
+ this.platformInvoices = new PlatformInvoicesResource(
400
+ this.tokenManager,
401
+ this.baseUrl
402
+ );
403
+ }
404
+ }
405
+
406
+ export { BLNRClient };