@billionaire-sh/node-sdk 0.0.0-stage → 0.1.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.
@@ -0,0 +1,313 @@
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 PlatformInvoicesResource extends BaseResource {
173
+ constructor(tokenManager, baseUrl) {
174
+ super(tokenManager, baseUrl, "/invoices");
175
+ }
176
+ rootPath() {
177
+ return "/platform";
178
+ }
179
+ /**
180
+ * Hand over what the platform invoiced one of its customers; the entity
181
+ * issues its own invoice for it. Idempotent on `stripeInvoiceId`.
182
+ * @param request - The platform's invoice, its lines and its customer
183
+ * @returns What became of it, and the entity's invoice once issued
184
+ */
185
+ async process(request) {
186
+ return this.request("POST", "", request);
187
+ }
188
+ /**
189
+ * The tax the entity puts on what the platform charges each of these
190
+ * customers — by country and whether it is a consumer — so the payment
191
+ * provider charges exactly what the entity's invoice will say. The
192
+ * platform computes no tax of its own.
193
+ * @param request - The customers, each with the platform's own key
194
+ * @returns Each key's tax, null where the entity charges none
195
+ */
196
+ async chargeTaxes(request) {
197
+ return this.request(
198
+ "POST",
199
+ "/charge-taxes",
200
+ request
201
+ );
202
+ }
203
+ /**
204
+ * Preview the invoice the entity would issue for what the platform is
205
+ * about to charge — composed by billionaire's invoicing engine exactly as
206
+ * `process` issues it, nothing issued.
207
+ * @param request - The lines to charge, their currency, the day and the
208
+ * total the payment provider will charge
209
+ * @returns The invoice's net, VAT per rate, gross and lines — or why the
210
+ * entity would issue none
211
+ */
212
+ async preview(request) {
213
+ return this.request(
214
+ "POST",
215
+ "/preview",
216
+ request
217
+ );
218
+ }
219
+ /**
220
+ * The platform's invoices the entity's books still show as unpaid, the
221
+ * oldest first, a page at a time — for a follow-up that asks the payment
222
+ * provider about each and hands a payment or void it missed back through
223
+ * `processPayment` / `processVoid`.
224
+ * @param request - The platform (`filters.platform`) and the page
225
+ * @returns Each invoice with the payment provider's id of the platform's
226
+ * invoice it documents
227
+ */
228
+ async listOpen(request) {
229
+ return this.request(
230
+ "POST",
231
+ "/open",
232
+ request
233
+ );
234
+ }
235
+ /**
236
+ * Get the entity's invoice for a platform invoice.
237
+ * @param stripeInvoiceId - The payment provider's id of the platform's invoice
238
+ * @returns The invoice's number, state and amounts
239
+ */
240
+ async get(stripeInvoiceId) {
241
+ return this.request(
242
+ "GET",
243
+ `/${encodeURIComponent(stripeInvoiceId)}`
244
+ );
245
+ }
246
+ /**
247
+ * Hand over that a platform invoice was paid; the entity records the
248
+ * money and settles its invoice. Idempotent on `stripeInvoiceId`.
249
+ * @param stripeInvoiceId - The payment provider's id of the paid invoice
250
+ * @param request - When it was paid, and how much
251
+ */
252
+ async processPayment(stripeInvoiceId, request) {
253
+ return this.request(
254
+ "POST",
255
+ `/${encodeURIComponent(stripeInvoiceId)}/payments`,
256
+ request
257
+ );
258
+ }
259
+ /**
260
+ * Hand over that the payment provider voided a platform invoice; the
261
+ * entity cancels its invoice for it.
262
+ * @param stripeInvoiceId - The payment provider's id of the voided invoice
263
+ * @param request - When it was voided
264
+ */
265
+ async processVoid(stripeInvoiceId, request) {
266
+ return this.request(
267
+ "POST",
268
+ `/${encodeURIComponent(stripeInvoiceId)}/void`,
269
+ request
270
+ );
271
+ }
272
+ /**
273
+ * Hand over a credit note the payment provider issued for a platform
274
+ * invoice — money back to the card, a credit on the customer's balance.
275
+ * One for all of it cancels the entity's invoice, and what the customer
276
+ * had paid becomes their credit; one for part of it is answered
277
+ * `partial_credit` and changes nothing.
278
+ * @param stripeInvoiceId - The payment provider's id of the credited invoice
279
+ * @param request - The credit note, when it was issued and what it takes back
280
+ */
281
+ async processCredit(stripeInvoiceId, request) {
282
+ return this.request(
283
+ "POST",
284
+ `/${encodeURIComponent(stripeInvoiceId)}/credit`,
285
+ request
286
+ );
287
+ }
288
+ }
289
+
290
+ var __defProp = Object.defineProperty;
291
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
292
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
293
+ class BLNRClient {
294
+ constructor(config) {
295
+ __publicField(this, "platformInvoices");
296
+ __publicField(this, "baseUrl");
297
+ __publicField(this, "tokenManager");
298
+ this.baseUrl = config.baseUrl || "https://billionaire.sh/api";
299
+ const tokenUrl = config.tokenUrl || `${this.baseUrl}/m2m/token`;
300
+ this.tokenManager = new TokenManager(
301
+ config.clientId,
302
+ config.clientSecret,
303
+ tokenUrl,
304
+ config.entityId
305
+ );
306
+ this.platformInvoices = new PlatformInvoicesResource(
307
+ this.tokenManager,
308
+ this.baseUrl
309
+ );
310
+ }
311
+ }
312
+
313
+ export { BLNRClient };