@rawdash/connector-bill 0.28.2

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.
package/README.md ADDED
@@ -0,0 +1,156 @@
1
+ <!-- This file is generated from connector metadata by scripts/generate-connector-docs.ts. Do not edit by hand. -->
2
+
3
+ # @rawdash/connector-bill
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@rawdash/connector-bill)](https://www.npmjs.com/package/@rawdash/connector-bill)
6
+ [![license](https://img.shields.io/npm/l/@rawdash/connector-bill)](https://github.com/rawdash/rawdash/blob/main/LICENSE)
7
+
8
+ Sync accounts-payable bills, vendors, and vendor payments from BILL (Bill.com) for AP aging, bills-pending, and vendor-spend dashboards.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ npm install @rawdash/connector-bill
14
+ ```
15
+
16
+ ## Authentication
17
+
18
+ Session-based sign in against the BILL v3 API. The connector signs in with a developer key, username, password, and organization ID to obtain a session, then reuses it for the rest of the sync.
19
+
20
+ 1. Request a BILL developer key from the BILL Developer portal and note the key value.
21
+ 2. Create or choose a BILL user with access to the organization you want to sync.
22
+ 3. Find the organization ID for that organization (visible in the app URL or via the List Organizations API).
23
+ 4. Store the developer key and the user password as rawdash secrets and reference them from the connector config as `devKey: secret("BILL_DEV_KEY")` and `password: secret("BILL_PASSWORD")`.
24
+
25
+ ## Configuration
26
+
27
+ | Field | Type | Required | Description |
28
+ | ----------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------------- |
29
+ | `devKey` | secret | Yes | BILL developer key that authorizes API access for your app. Find it in the BILL Developer portal under your app. |
30
+ | `username` | string | Yes | Email address of the BILL user the API signs in as. This user must have access to the organization you are syncing. |
31
+ | `password` | secret | Yes | Password for the BILL user. Stored as a secret. |
32
+ | `orgId` | string | Yes | BILL organization ID to sync. Find it in the BILL app URL or via the List Organizations API. |
33
+ | `resources` | array | No | Which BILL resources to sync. Omit to sync all of them (bills, vendors, payments). |
34
+
35
+ ## Resources
36
+
37
+ - **`bill_vendor`** _(entity)_ - Vendors (suppliers) with name, contact details, account number, and archived state.
38
+ - Endpoint: `GET /v3/vendors`
39
+ - Incremental syncs filter on updatedTime and sort ascending so resumable pages stay ordered.
40
+ - `name`: Vendor display name.
41
+ - `email`: Vendor contact email, if set.
42
+ - `accountNumber`: Your account number with the vendor, if set.
43
+ - `phone`: Vendor phone number, if set.
44
+ - `archived`: Whether the vendor has been archived.
45
+ - `billCurrency`: Default bill currency for the vendor (ISO code).
46
+ - `createdAt`: When the vendor was created (Unix ms).
47
+ - **`bill_bill`** _(entity)_ - Accounts-payable bills with vendor, invoice number, invoice and due dates, amount, and payment status.
48
+ - Endpoint: `GET /v3/bills`
49
+ - Amounts are in the bill currency major units (e.g. dollars). Incremental syncs filter on updatedTime so status transitions are re-fetched.
50
+ - `vendorId`: Vendor the bill is owed to.
51
+ - `invoiceNumber`: Vendor invoice number, if set.
52
+ - `invoiceDate`: Invoice date (Unix ms), if set.
53
+ - `dueDate`: Payment due date (Unix ms), if set.
54
+ - `amount`: Bill total in the bill currency major units.
55
+ - `paymentStatus`: Payment status (UNPAID, PARTIALLY_PAID, PAID, ...).
56
+ - `approvalStatus`: Approval status (UNASSIGNED, APPROVED, ...), if set.
57
+ - `archived`: Whether the bill has been archived.
58
+ - `createdAt`: When the bill was created (Unix ms).
59
+ - **`bill_payment`** _(event)_ - Vendor payments (money sent to vendors), one event per payment timestamped at its process date.
60
+ - Endpoint: `GET /v3/payments`
61
+ - `id`: BILL payment id.
62
+ - `vendorId`: Vendor paid, if set.
63
+ - `billId`: Bill the payment applies to, if set.
64
+ - `amount`: Payment amount in the payment currency major units.
65
+ - `status`: Payment status (SCHEDULED, PAID, CANCELED).
66
+ - `description`: Payment description, if set.
67
+ - `processDate`: Scheduled or actual process date (Unix ms), if set.
68
+
69
+ ## Example
70
+
71
+ ```ts
72
+ import {
73
+ defineConfig,
74
+ defineDashboard,
75
+ defineMetric,
76
+ secret,
77
+ } from '@rawdash/core';
78
+
79
+ const bill = {
80
+ name: 'bill',
81
+ connectorId: 'bill',
82
+ config: {
83
+ devKey: secret('BILL_DEV_KEY'),
84
+ username: 'api-user@example.com',
85
+ password: secret('BILL_PASSWORD'),
86
+ orgId: '00801ABCDEFGHIJKLMNO',
87
+ resources: ['bills', 'vendors', 'payments'],
88
+ },
89
+ };
90
+
91
+ export default defineConfig({
92
+ connectors: [bill],
93
+ dashboards: {
94
+ payables: defineDashboard({
95
+ widgets: {
96
+ bills_pending: {
97
+ kind: 'stat',
98
+ title: 'Bills pending',
99
+ metric: defineMetric({
100
+ connector: bill,
101
+ shape: 'entity',
102
+ entityType: 'bill_bill',
103
+ fn: 'count',
104
+ filter: [{ field: 'paymentStatus', op: 'eq', value: 'UNPAID' }],
105
+ }),
106
+ },
107
+ ap_balance: {
108
+ kind: 'stat',
109
+ title: 'AP balance (unpaid)',
110
+ metric: defineMetric({
111
+ connector: bill,
112
+ shape: 'entity',
113
+ entityType: 'bill_bill',
114
+ field: 'amount',
115
+ fn: 'sum',
116
+ filter: [{ field: 'paymentStatus', op: 'eq', value: 'UNPAID' }],
117
+ }),
118
+ },
119
+ payments_30d: {
120
+ kind: 'timeseries',
121
+ title: 'Vendor payments (30d)',
122
+ window: '30d',
123
+ metric: defineMetric({
124
+ connector: bill,
125
+ shape: 'event',
126
+ name: 'bill_payment',
127
+ field: 'amount',
128
+ fn: 'sum',
129
+ }),
130
+ },
131
+ },
132
+ }),
133
+ },
134
+ });
135
+ ```
136
+
137
+ ## Rate limits
138
+
139
+ BILL does not publish standard rate-limit response headers; the shared HTTP client retries 429 responses with exponential backoff. Sessions expire after 35 minutes of inactivity and are transparently re-established on a 401.
140
+
141
+ ## Limitations
142
+
143
+ - Monetary amounts are stored in major currency units (e.g. dollars), matching the BILL API, not in the smallest unit.
144
+ - Incremental syncs filter on updatedTime, so status transitions (a bill moving from UNPAID to PAID) are picked up on the next run.
145
+ - The set of synced resources is controlled by the `resources` config field; omit it to sync all of them.
146
+ - Bill line items and approval workflow detail are out of scope; only the header-level bill, its vendor, and vendor payments are synced.
147
+
148
+ ## Links
149
+
150
+ - [Rawdash docs](https://rawdash.dev/docs/connectors)
151
+ - [Bill.com API docs](https://developer.bill.com/docs/home)
152
+ - [GitHub](https://github.com/rawdash/rawdash)
153
+
154
+ ## License
155
+
156
+ Apache-2.0
@@ -0,0 +1,464 @@
1
+ import { BaseConnector, ConnectorContext, SyncOptions, StorageHandle, SyncResult, ConnectorDoc } from '@rawdash/core';
2
+ import { z } from 'zod';
3
+
4
+ declare const configFields: z.ZodObject<{
5
+ devKey: z.ZodObject<{
6
+ $secret: z.ZodString;
7
+ }, z.core.$strip>;
8
+ username: z.ZodString;
9
+ password: z.ZodObject<{
10
+ $secret: z.ZodString;
11
+ }, z.core.$strip>;
12
+ orgId: z.ZodString;
13
+ resources: z.ZodOptional<z.ZodArray<z.ZodEnum<{
14
+ bills: "bills";
15
+ vendors: "vendors";
16
+ payments: "payments";
17
+ }>>>;
18
+ }, z.core.$strip>;
19
+ declare const doc: ConnectorDoc;
20
+ type BillResource = 'bills' | 'vendors' | 'payments';
21
+ interface BillSettings {
22
+ orgId: string;
23
+ resources?: readonly BillResource[];
24
+ }
25
+ declare const billCredentials: {
26
+ devKey: {
27
+ description: string;
28
+ auth: "required";
29
+ };
30
+ username: {
31
+ description: string;
32
+ auth: "required";
33
+ };
34
+ password: {
35
+ description: string;
36
+ auth: "required";
37
+ };
38
+ };
39
+ type BillCredentials = typeof billCredentials;
40
+ declare const billResources: {
41
+ readonly bill_vendor: {
42
+ readonly shape: "entity";
43
+ readonly filterable: [{
44
+ readonly field: "archived";
45
+ readonly ops: ["eq"];
46
+ readonly values: ["true", "false"];
47
+ }];
48
+ readonly description: "Vendors (suppliers) with name, contact details, account number, and archived state.";
49
+ readonly endpoint: "GET /v3/vendors";
50
+ readonly notes: "Incremental syncs filter on updatedTime and sort ascending so resumable pages stay ordered.";
51
+ readonly fields: [{
52
+ readonly name: "name";
53
+ readonly description: "Vendor display name.";
54
+ }, {
55
+ readonly name: "email";
56
+ readonly description: "Vendor contact email, if set.";
57
+ }, {
58
+ readonly name: "accountNumber";
59
+ readonly description: "Your account number with the vendor, if set.";
60
+ }, {
61
+ readonly name: "phone";
62
+ readonly description: "Vendor phone number, if set.";
63
+ }, {
64
+ readonly name: "archived";
65
+ readonly description: "Whether the vendor has been archived.";
66
+ }, {
67
+ readonly name: "billCurrency";
68
+ readonly description: "Default bill currency for the vendor (ISO code).";
69
+ }, {
70
+ readonly name: "createdAt";
71
+ readonly description: "When the vendor was created (Unix ms).";
72
+ }];
73
+ readonly responses: {
74
+ readonly login: z.ZodObject<{
75
+ sessionId: z.ZodString;
76
+ organizationId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
77
+ userId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
78
+ }, z.core.$strip>;
79
+ readonly vendors: z.ZodObject<{
80
+ results: z.ZodArray<z.ZodObject<{
81
+ id: z.ZodString;
82
+ name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
83
+ email: z.ZodOptional<z.ZodNullable<z.ZodString>>;
84
+ accountNumber: z.ZodOptional<z.ZodNullable<z.ZodString>>;
85
+ phone: z.ZodOptional<z.ZodNullable<z.ZodString>>;
86
+ archived: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
87
+ billCurrency: z.ZodOptional<z.ZodNullable<z.ZodString>>;
88
+ createdTime: z.ZodOptional<z.ZodNullable<z.ZodString>>;
89
+ updatedTime: z.ZodOptional<z.ZodNullable<z.ZodString>>;
90
+ }, z.core.$strip>>;
91
+ nextPage: z.ZodOptional<z.ZodNullable<z.ZodString>>;
92
+ prevPage: z.ZodOptional<z.ZodNullable<z.ZodString>>;
93
+ }, z.core.$strip>;
94
+ };
95
+ };
96
+ readonly bill_bill: {
97
+ readonly shape: "entity";
98
+ readonly filterable: [{
99
+ readonly field: "paymentStatus";
100
+ readonly ops: ["eq"];
101
+ readonly values: ["UNPAID", "PARTIALLY_PAID", "PAID", "SCHEDULED", "PARTIALLY_SCHEDULED"];
102
+ }];
103
+ readonly description: "Accounts-payable bills with vendor, invoice number, invoice and due dates, amount, and payment status.";
104
+ readonly endpoint: "GET /v3/bills";
105
+ readonly notes: "Amounts are in the bill currency major units (e.g. dollars). Incremental syncs filter on updatedTime so status transitions are re-fetched.";
106
+ readonly fields: [{
107
+ readonly name: "vendorId";
108
+ readonly description: "Vendor the bill is owed to.";
109
+ }, {
110
+ readonly name: "invoiceNumber";
111
+ readonly description: "Vendor invoice number, if set.";
112
+ }, {
113
+ readonly name: "invoiceDate";
114
+ readonly description: "Invoice date (Unix ms), if set.";
115
+ }, {
116
+ readonly name: "dueDate";
117
+ readonly description: "Payment due date (Unix ms), if set.";
118
+ }, {
119
+ readonly name: "amount";
120
+ readonly description: "Bill total in the bill currency major units.";
121
+ }, {
122
+ readonly name: "paymentStatus";
123
+ readonly description: "Payment status (UNPAID, PARTIALLY_PAID, PAID, ...).";
124
+ }, {
125
+ readonly name: "approvalStatus";
126
+ readonly description: "Approval status (UNASSIGNED, APPROVED, ...), if set.";
127
+ }, {
128
+ readonly name: "archived";
129
+ readonly description: "Whether the bill has been archived.";
130
+ }, {
131
+ readonly name: "createdAt";
132
+ readonly description: "When the bill was created (Unix ms).";
133
+ }];
134
+ readonly responses: {
135
+ readonly bills: z.ZodObject<{
136
+ results: z.ZodArray<z.ZodObject<{
137
+ id: z.ZodString;
138
+ vendorId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
139
+ amount: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
140
+ dueDate: z.ZodOptional<z.ZodNullable<z.ZodString>>;
141
+ invoice: z.ZodOptional<z.ZodNullable<z.ZodObject<{
142
+ invoiceNumber: z.ZodOptional<z.ZodNullable<z.ZodString>>;
143
+ invoiceDate: z.ZodOptional<z.ZodNullable<z.ZodString>>;
144
+ }, z.core.$strip>>>;
145
+ paymentStatus: z.ZodOptional<z.ZodNullable<z.ZodString>>;
146
+ approvalStatus: z.ZodOptional<z.ZodNullable<z.ZodString>>;
147
+ archived: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
148
+ createdTime: z.ZodOptional<z.ZodNullable<z.ZodString>>;
149
+ updatedTime: z.ZodOptional<z.ZodNullable<z.ZodString>>;
150
+ }, z.core.$strip>>;
151
+ nextPage: z.ZodOptional<z.ZodNullable<z.ZodString>>;
152
+ prevPage: z.ZodOptional<z.ZodNullable<z.ZodString>>;
153
+ }, z.core.$strip>;
154
+ };
155
+ };
156
+ readonly bill_payment: {
157
+ readonly shape: "event";
158
+ readonly filterable: [{
159
+ readonly field: "status";
160
+ readonly ops: ["eq"];
161
+ readonly values: ["SCHEDULED", "PAID", "CANCELED"];
162
+ }];
163
+ readonly description: "Vendor payments (money sent to vendors), one event per payment timestamped at its process date.";
164
+ readonly endpoint: "GET /v3/payments";
165
+ readonly fields: [{
166
+ readonly name: "id";
167
+ readonly description: "BILL payment id.";
168
+ }, {
169
+ readonly name: "vendorId";
170
+ readonly description: "Vendor paid, if set.";
171
+ }, {
172
+ readonly name: "billId";
173
+ readonly description: "Bill the payment applies to, if set.";
174
+ }, {
175
+ readonly name: "amount";
176
+ readonly description: "Payment amount in the payment currency major units.";
177
+ }, {
178
+ readonly name: "status";
179
+ readonly description: "Payment status (SCHEDULED, PAID, CANCELED).";
180
+ }, {
181
+ readonly name: "description";
182
+ readonly description: "Payment description, if set.";
183
+ }, {
184
+ readonly name: "processDate";
185
+ readonly description: "Scheduled or actual process date (Unix ms), if set.";
186
+ }];
187
+ readonly responses: {
188
+ readonly payments: z.ZodObject<{
189
+ results: z.ZodArray<z.ZodObject<{
190
+ id: z.ZodString;
191
+ vendorId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
192
+ billId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
193
+ amount: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
194
+ processDate: z.ZodOptional<z.ZodNullable<z.ZodString>>;
195
+ status: z.ZodOptional<z.ZodNullable<z.ZodString>>;
196
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
197
+ createdTime: z.ZodOptional<z.ZodNullable<z.ZodString>>;
198
+ updatedTime: z.ZodOptional<z.ZodNullable<z.ZodString>>;
199
+ }, z.core.$strip>>;
200
+ nextPage: z.ZodOptional<z.ZodNullable<z.ZodString>>;
201
+ prevPage: z.ZodOptional<z.ZodNullable<z.ZodString>>;
202
+ }, z.core.$strip>;
203
+ };
204
+ };
205
+ };
206
+ declare const id = "bill";
207
+ declare class BillConnector extends BaseConnector<BillSettings, BillCredentials> {
208
+ static readonly id = "bill";
209
+ static readonly resources: {
210
+ readonly bill_vendor: {
211
+ readonly shape: "entity";
212
+ readonly filterable: [{
213
+ readonly field: "archived";
214
+ readonly ops: ["eq"];
215
+ readonly values: ["true", "false"];
216
+ }];
217
+ readonly description: "Vendors (suppliers) with name, contact details, account number, and archived state.";
218
+ readonly endpoint: "GET /v3/vendors";
219
+ readonly notes: "Incremental syncs filter on updatedTime and sort ascending so resumable pages stay ordered.";
220
+ readonly fields: [{
221
+ readonly name: "name";
222
+ readonly description: "Vendor display name.";
223
+ }, {
224
+ readonly name: "email";
225
+ readonly description: "Vendor contact email, if set.";
226
+ }, {
227
+ readonly name: "accountNumber";
228
+ readonly description: "Your account number with the vendor, if set.";
229
+ }, {
230
+ readonly name: "phone";
231
+ readonly description: "Vendor phone number, if set.";
232
+ }, {
233
+ readonly name: "archived";
234
+ readonly description: "Whether the vendor has been archived.";
235
+ }, {
236
+ readonly name: "billCurrency";
237
+ readonly description: "Default bill currency for the vendor (ISO code).";
238
+ }, {
239
+ readonly name: "createdAt";
240
+ readonly description: "When the vendor was created (Unix ms).";
241
+ }];
242
+ readonly responses: {
243
+ readonly login: z.ZodObject<{
244
+ sessionId: z.ZodString;
245
+ organizationId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
246
+ userId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
247
+ }, z.core.$strip>;
248
+ readonly vendors: z.ZodObject<{
249
+ results: z.ZodArray<z.ZodObject<{
250
+ id: z.ZodString;
251
+ name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
252
+ email: z.ZodOptional<z.ZodNullable<z.ZodString>>;
253
+ accountNumber: z.ZodOptional<z.ZodNullable<z.ZodString>>;
254
+ phone: z.ZodOptional<z.ZodNullable<z.ZodString>>;
255
+ archived: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
256
+ billCurrency: z.ZodOptional<z.ZodNullable<z.ZodString>>;
257
+ createdTime: z.ZodOptional<z.ZodNullable<z.ZodString>>;
258
+ updatedTime: z.ZodOptional<z.ZodNullable<z.ZodString>>;
259
+ }, z.core.$strip>>;
260
+ nextPage: z.ZodOptional<z.ZodNullable<z.ZodString>>;
261
+ prevPage: z.ZodOptional<z.ZodNullable<z.ZodString>>;
262
+ }, z.core.$strip>;
263
+ };
264
+ };
265
+ readonly bill_bill: {
266
+ readonly shape: "entity";
267
+ readonly filterable: [{
268
+ readonly field: "paymentStatus";
269
+ readonly ops: ["eq"];
270
+ readonly values: ["UNPAID", "PARTIALLY_PAID", "PAID", "SCHEDULED", "PARTIALLY_SCHEDULED"];
271
+ }];
272
+ readonly description: "Accounts-payable bills with vendor, invoice number, invoice and due dates, amount, and payment status.";
273
+ readonly endpoint: "GET /v3/bills";
274
+ readonly notes: "Amounts are in the bill currency major units (e.g. dollars). Incremental syncs filter on updatedTime so status transitions are re-fetched.";
275
+ readonly fields: [{
276
+ readonly name: "vendorId";
277
+ readonly description: "Vendor the bill is owed to.";
278
+ }, {
279
+ readonly name: "invoiceNumber";
280
+ readonly description: "Vendor invoice number, if set.";
281
+ }, {
282
+ readonly name: "invoiceDate";
283
+ readonly description: "Invoice date (Unix ms), if set.";
284
+ }, {
285
+ readonly name: "dueDate";
286
+ readonly description: "Payment due date (Unix ms), if set.";
287
+ }, {
288
+ readonly name: "amount";
289
+ readonly description: "Bill total in the bill currency major units.";
290
+ }, {
291
+ readonly name: "paymentStatus";
292
+ readonly description: "Payment status (UNPAID, PARTIALLY_PAID, PAID, ...).";
293
+ }, {
294
+ readonly name: "approvalStatus";
295
+ readonly description: "Approval status (UNASSIGNED, APPROVED, ...), if set.";
296
+ }, {
297
+ readonly name: "archived";
298
+ readonly description: "Whether the bill has been archived.";
299
+ }, {
300
+ readonly name: "createdAt";
301
+ readonly description: "When the bill was created (Unix ms).";
302
+ }];
303
+ readonly responses: {
304
+ readonly bills: z.ZodObject<{
305
+ results: z.ZodArray<z.ZodObject<{
306
+ id: z.ZodString;
307
+ vendorId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
308
+ amount: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
309
+ dueDate: z.ZodOptional<z.ZodNullable<z.ZodString>>;
310
+ invoice: z.ZodOptional<z.ZodNullable<z.ZodObject<{
311
+ invoiceNumber: z.ZodOptional<z.ZodNullable<z.ZodString>>;
312
+ invoiceDate: z.ZodOptional<z.ZodNullable<z.ZodString>>;
313
+ }, z.core.$strip>>>;
314
+ paymentStatus: z.ZodOptional<z.ZodNullable<z.ZodString>>;
315
+ approvalStatus: z.ZodOptional<z.ZodNullable<z.ZodString>>;
316
+ archived: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
317
+ createdTime: z.ZodOptional<z.ZodNullable<z.ZodString>>;
318
+ updatedTime: z.ZodOptional<z.ZodNullable<z.ZodString>>;
319
+ }, z.core.$strip>>;
320
+ nextPage: z.ZodOptional<z.ZodNullable<z.ZodString>>;
321
+ prevPage: z.ZodOptional<z.ZodNullable<z.ZodString>>;
322
+ }, z.core.$strip>;
323
+ };
324
+ };
325
+ readonly bill_payment: {
326
+ readonly shape: "event";
327
+ readonly filterable: [{
328
+ readonly field: "status";
329
+ readonly ops: ["eq"];
330
+ readonly values: ["SCHEDULED", "PAID", "CANCELED"];
331
+ }];
332
+ readonly description: "Vendor payments (money sent to vendors), one event per payment timestamped at its process date.";
333
+ readonly endpoint: "GET /v3/payments";
334
+ readonly fields: [{
335
+ readonly name: "id";
336
+ readonly description: "BILL payment id.";
337
+ }, {
338
+ readonly name: "vendorId";
339
+ readonly description: "Vendor paid, if set.";
340
+ }, {
341
+ readonly name: "billId";
342
+ readonly description: "Bill the payment applies to, if set.";
343
+ }, {
344
+ readonly name: "amount";
345
+ readonly description: "Payment amount in the payment currency major units.";
346
+ }, {
347
+ readonly name: "status";
348
+ readonly description: "Payment status (SCHEDULED, PAID, CANCELED).";
349
+ }, {
350
+ readonly name: "description";
351
+ readonly description: "Payment description, if set.";
352
+ }, {
353
+ readonly name: "processDate";
354
+ readonly description: "Scheduled or actual process date (Unix ms), if set.";
355
+ }];
356
+ readonly responses: {
357
+ readonly payments: z.ZodObject<{
358
+ results: z.ZodArray<z.ZodObject<{
359
+ id: z.ZodString;
360
+ vendorId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
361
+ billId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
362
+ amount: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
363
+ processDate: z.ZodOptional<z.ZodNullable<z.ZodString>>;
364
+ status: z.ZodOptional<z.ZodNullable<z.ZodString>>;
365
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
366
+ createdTime: z.ZodOptional<z.ZodNullable<z.ZodString>>;
367
+ updatedTime: z.ZodOptional<z.ZodNullable<z.ZodString>>;
368
+ }, z.core.$strip>>;
369
+ nextPage: z.ZodOptional<z.ZodNullable<z.ZodString>>;
370
+ prevPage: z.ZodOptional<z.ZodNullable<z.ZodString>>;
371
+ }, z.core.$strip>;
372
+ };
373
+ };
374
+ };
375
+ static readonly schemas: {
376
+ readonly login: z.ZodObject<{
377
+ sessionId: z.ZodString;
378
+ organizationId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
379
+ userId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
380
+ }, z.core.$strip>;
381
+ readonly vendors: z.ZodObject<{
382
+ results: z.ZodArray<z.ZodObject<{
383
+ id: z.ZodString;
384
+ name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
385
+ email: z.ZodOptional<z.ZodNullable<z.ZodString>>;
386
+ accountNumber: z.ZodOptional<z.ZodNullable<z.ZodString>>;
387
+ phone: z.ZodOptional<z.ZodNullable<z.ZodString>>;
388
+ archived: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
389
+ billCurrency: z.ZodOptional<z.ZodNullable<z.ZodString>>;
390
+ createdTime: z.ZodOptional<z.ZodNullable<z.ZodString>>;
391
+ updatedTime: z.ZodOptional<z.ZodNullable<z.ZodString>>;
392
+ }, z.core.$strip>>;
393
+ nextPage: z.ZodOptional<z.ZodNullable<z.ZodString>>;
394
+ prevPage: z.ZodOptional<z.ZodNullable<z.ZodString>>;
395
+ }, z.core.$strip>;
396
+ } & {
397
+ readonly bills: z.ZodObject<{
398
+ results: z.ZodArray<z.ZodObject<{
399
+ id: z.ZodString;
400
+ vendorId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
401
+ amount: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
402
+ dueDate: z.ZodOptional<z.ZodNullable<z.ZodString>>;
403
+ invoice: z.ZodOptional<z.ZodNullable<z.ZodObject<{
404
+ invoiceNumber: z.ZodOptional<z.ZodNullable<z.ZodString>>;
405
+ invoiceDate: z.ZodOptional<z.ZodNullable<z.ZodString>>;
406
+ }, z.core.$strip>>>;
407
+ paymentStatus: z.ZodOptional<z.ZodNullable<z.ZodString>>;
408
+ approvalStatus: z.ZodOptional<z.ZodNullable<z.ZodString>>;
409
+ archived: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
410
+ createdTime: z.ZodOptional<z.ZodNullable<z.ZodString>>;
411
+ updatedTime: z.ZodOptional<z.ZodNullable<z.ZodString>>;
412
+ }, z.core.$strip>>;
413
+ nextPage: z.ZodOptional<z.ZodNullable<z.ZodString>>;
414
+ prevPage: z.ZodOptional<z.ZodNullable<z.ZodString>>;
415
+ }, z.core.$strip>;
416
+ } & {
417
+ readonly payments: z.ZodObject<{
418
+ results: z.ZodArray<z.ZodObject<{
419
+ id: z.ZodString;
420
+ vendorId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
421
+ billId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
422
+ amount: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
423
+ processDate: z.ZodOptional<z.ZodNullable<z.ZodString>>;
424
+ status: z.ZodOptional<z.ZodNullable<z.ZodString>>;
425
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
426
+ createdTime: z.ZodOptional<z.ZodNullable<z.ZodString>>;
427
+ updatedTime: z.ZodOptional<z.ZodNullable<z.ZodString>>;
428
+ }, z.core.$strip>>;
429
+ nextPage: z.ZodOptional<z.ZodNullable<z.ZodString>>;
430
+ prevPage: z.ZodOptional<z.ZodNullable<z.ZodString>>;
431
+ }, z.core.$strip>;
432
+ } & Readonly<Record<string, z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>>;
433
+ static create(input: unknown, ctx?: ConnectorContext): BillConnector;
434
+ readonly id = "bill";
435
+ readonly credentials: {
436
+ devKey: {
437
+ description: string;
438
+ auth: "required";
439
+ };
440
+ username: {
441
+ description: string;
442
+ auth: "required";
443
+ };
444
+ password: {
445
+ description: string;
446
+ auth: "required";
447
+ };
448
+ };
449
+ private sessionId;
450
+ private baseHeaders;
451
+ private refreshSession;
452
+ private getSession;
453
+ private apiGet;
454
+ private buildListUrl;
455
+ private fetchPage;
456
+ private writeVendors;
457
+ private writeBills;
458
+ private writePayments;
459
+ private writePhase;
460
+ private clearScopeOnFirstPage;
461
+ sync(options: SyncOptions, storage: StorageHandle, signal?: AbortSignal): Promise<SyncResult>;
462
+ }
463
+
464
+ export { BillConnector, type BillResource, type BillSettings, configFields, BillConnector as default, doc, id, billResources as resources };
package/dist/index.js ADDED
@@ -0,0 +1,514 @@
1
+ // ../../connector-shared/dist/index.js
2
+ var HTTP_CLIENT_VERSION = "0.0.0";
3
+ var DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;
4
+ function connectorUserAgent(connectorId) {
5
+ return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;
6
+ }
7
+ function parseEpoch(value, unit) {
8
+ if (value === null || value === void 0) {
9
+ return null;
10
+ }
11
+ if (unit === "iso") {
12
+ if (typeof value !== "string") {
13
+ return null;
14
+ }
15
+ const ms = new Date(value).getTime();
16
+ return Number.isFinite(ms) ? ms : null;
17
+ }
18
+ if (typeof value === "string" && value.trim() === "") {
19
+ return null;
20
+ }
21
+ const n = typeof value === "number" ? value : Number(value);
22
+ if (!Number.isFinite(n)) {
23
+ return null;
24
+ }
25
+ const result = unit === "s" ? n * 1e3 : n;
26
+ return Number.isFinite(result) ? result : null;
27
+ }
28
+
29
+ // src/bill.ts
30
+ import {
31
+ BaseConnector,
32
+ defineConfigFields,
33
+ defineConnectorDoc,
34
+ defineResources,
35
+ makeChunkedCursorGuard,
36
+ paginateChunked,
37
+ schemasFromResources,
38
+ selectActivePhases
39
+ } from "@rawdash/core";
40
+ import { z } from "zod";
41
+ var configFields = defineConfigFields(
42
+ z.object({
43
+ devKey: z.object({ $secret: z.string().min(1) }).meta({
44
+ label: "Developer key",
45
+ description: "BILL developer key that authorizes API access for your app. Find it in the BILL Developer portal under your app.",
46
+ placeholder: "BILL_DEV_KEY",
47
+ secret: true
48
+ }),
49
+ username: z.string().min(1).meta({
50
+ label: "Username",
51
+ description: "Email address of the BILL user the API signs in as. This user must have access to the organization you are syncing.",
52
+ placeholder: "api-user@example.com"
53
+ }),
54
+ password: z.object({ $secret: z.string().min(1) }).meta({
55
+ label: "Password",
56
+ description: "Password for the BILL user. Stored as a secret.",
57
+ placeholder: "BILL_PASSWORD",
58
+ secret: true
59
+ }),
60
+ orgId: z.string().min(1).meta({
61
+ label: "Organization ID",
62
+ description: "BILL organization ID to sync. Find it in the BILL app URL or via the List Organizations API.",
63
+ placeholder: "00801ABCDEFGHIJKLMNO"
64
+ }),
65
+ resources: z.array(z.enum(["bills", "vendors", "payments"])).nonempty().optional().meta({
66
+ label: "Resources",
67
+ description: "Which BILL resources to sync. Omit to sync all of them (bills, vendors, payments)."
68
+ })
69
+ })
70
+ );
71
+ var doc = defineConnectorDoc({
72
+ displayName: "Bill.com",
73
+ category: "finance",
74
+ brandColor: "#005DAA",
75
+ tagline: "Sync accounts-payable bills, vendors, and vendor payments from BILL (Bill.com) for AP aging, bills-pending, and vendor-spend dashboards.",
76
+ vendor: {
77
+ name: "Bill.com",
78
+ domain: "bill.com",
79
+ apiDocs: "https://developer.bill.com/docs/home",
80
+ website: "https://www.bill.com"
81
+ },
82
+ auth: {
83
+ summary: "Session-based sign in against the BILL v3 API. The connector signs in with a developer key, username, password, and organization ID to obtain a session, then reuses it for the rest of the sync.",
84
+ setup: [
85
+ "Request a BILL developer key from the BILL Developer portal and note the key value.",
86
+ "Create or choose a BILL user with access to the organization you want to sync.",
87
+ "Find the organization ID for that organization (visible in the app URL or via the List Organizations API).",
88
+ 'Store the developer key and the user password as rawdash secrets and reference them from the connector config as `devKey: secret("BILL_DEV_KEY")` and `password: secret("BILL_PASSWORD")`.'
89
+ ]
90
+ },
91
+ rateLimit: "BILL does not publish standard rate-limit response headers; the shared HTTP client retries 429 responses with exponential backoff. Sessions expire after 35 minutes of inactivity and are transparently re-established on a 401.",
92
+ limitations: [
93
+ "Monetary amounts are stored in major currency units (e.g. dollars), matching the BILL API, not in the smallest unit.",
94
+ "Incremental syncs filter on updatedTime, so status transitions (a bill moving from UNPAID to PAID) are picked up on the next run.",
95
+ "The set of synced resources is controlled by the `resources` config field; omit it to sync all of them.",
96
+ "Bill line items and approval workflow detail are out of scope; only the header-level bill, its vendor, and vendor payments are synced."
97
+ ]
98
+ });
99
+ var billCredentials = {
100
+ devKey: {
101
+ description: "BILL developer key",
102
+ auth: "required"
103
+ },
104
+ username: {
105
+ description: "BILL user email",
106
+ auth: "required"
107
+ },
108
+ password: {
109
+ description: "BILL user password",
110
+ auth: "required"
111
+ }
112
+ };
113
+ var API_BASE = "https://gateway.prod.bill.com/connect/v3";
114
+ var PAGE_SIZE = 100;
115
+ var PHASE_ORDER = ["vendors", "bills", "payments"];
116
+ var isBillSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);
117
+ var VENDOR_ENTITY = "bill_vendor";
118
+ var BILL_ENTITY = "bill_bill";
119
+ var PAYMENT_EVENT = "bill_payment";
120
+ var ENDPOINT_BY_PHASE = {
121
+ vendors: "vendors",
122
+ bills: "bills",
123
+ payments: "payments"
124
+ };
125
+ function isAuthError(err) {
126
+ return err instanceof Error && err.kind === "auth";
127
+ }
128
+ var idString = z.string().min(1);
129
+ var loginSchema = z.object({
130
+ sessionId: idString,
131
+ organizationId: z.string().nullish(),
132
+ userId: z.string().nullish()
133
+ });
134
+ var vendorSchema = z.object({
135
+ id: idString,
136
+ name: z.string().nullish(),
137
+ email: z.string().nullish(),
138
+ accountNumber: z.string().nullish(),
139
+ phone: z.string().nullish(),
140
+ archived: z.boolean().nullish(),
141
+ billCurrency: z.string().nullish(),
142
+ createdTime: z.string().nullish(),
143
+ updatedTime: z.string().nullish()
144
+ });
145
+ var billSchema = z.object({
146
+ id: idString,
147
+ vendorId: z.string().nullish(),
148
+ amount: z.number().nullish(),
149
+ dueDate: z.string().nullish(),
150
+ invoice: z.object({
151
+ invoiceNumber: z.string().nullish(),
152
+ invoiceDate: z.string().nullish()
153
+ }).nullish(),
154
+ paymentStatus: z.string().nullish(),
155
+ approvalStatus: z.string().nullish(),
156
+ archived: z.boolean().nullish(),
157
+ createdTime: z.string().nullish(),
158
+ updatedTime: z.string().nullish()
159
+ });
160
+ var paymentSchema = z.object({
161
+ id: idString,
162
+ vendorId: z.string().nullish(),
163
+ billId: z.string().nullish(),
164
+ amount: z.number().nullish(),
165
+ processDate: z.string().nullish(),
166
+ status: z.string().nullish(),
167
+ description: z.string().nullish(),
168
+ createdTime: z.string().nullish(),
169
+ updatedTime: z.string().nullish()
170
+ });
171
+ var listResponseSchema = (item) => z.object({
172
+ results: z.array(item),
173
+ nextPage: z.string().nullish(),
174
+ prevPage: z.string().nullish()
175
+ });
176
+ var vendorsListSchema = listResponseSchema(vendorSchema);
177
+ var billsListSchema = listResponseSchema(billSchema);
178
+ var paymentsListSchema = listResponseSchema(paymentSchema);
179
+ var billResources = defineResources({
180
+ [VENDOR_ENTITY]: {
181
+ shape: "entity",
182
+ filterable: [{ field: "archived", ops: ["eq"], values: ["true", "false"] }],
183
+ description: "Vendors (suppliers) with name, contact details, account number, and archived state.",
184
+ endpoint: "GET /v3/vendors",
185
+ notes: "Incremental syncs filter on updatedTime and sort ascending so resumable pages stay ordered.",
186
+ fields: [
187
+ { name: "name", description: "Vendor display name." },
188
+ { name: "email", description: "Vendor contact email, if set." },
189
+ {
190
+ name: "accountNumber",
191
+ description: "Your account number with the vendor, if set."
192
+ },
193
+ { name: "phone", description: "Vendor phone number, if set." },
194
+ {
195
+ name: "archived",
196
+ description: "Whether the vendor has been archived."
197
+ },
198
+ {
199
+ name: "billCurrency",
200
+ description: "Default bill currency for the vendor (ISO code)."
201
+ },
202
+ {
203
+ name: "createdAt",
204
+ description: "When the vendor was created (Unix ms)."
205
+ }
206
+ ],
207
+ responses: {
208
+ login: loginSchema,
209
+ vendors: vendorsListSchema
210
+ }
211
+ },
212
+ [BILL_ENTITY]: {
213
+ shape: "entity",
214
+ filterable: [
215
+ {
216
+ field: "paymentStatus",
217
+ ops: ["eq"],
218
+ values: [
219
+ "UNPAID",
220
+ "PARTIALLY_PAID",
221
+ "PAID",
222
+ "SCHEDULED",
223
+ "PARTIALLY_SCHEDULED"
224
+ ]
225
+ }
226
+ ],
227
+ description: "Accounts-payable bills with vendor, invoice number, invoice and due dates, amount, and payment status.",
228
+ endpoint: "GET /v3/bills",
229
+ notes: "Amounts are in the bill currency major units (e.g. dollars). Incremental syncs filter on updatedTime so status transitions are re-fetched.",
230
+ fields: [
231
+ { name: "vendorId", description: "Vendor the bill is owed to." },
232
+ { name: "invoiceNumber", description: "Vendor invoice number, if set." },
233
+ {
234
+ name: "invoiceDate",
235
+ description: "Invoice date (Unix ms), if set."
236
+ },
237
+ { name: "dueDate", description: "Payment due date (Unix ms), if set." },
238
+ {
239
+ name: "amount",
240
+ description: "Bill total in the bill currency major units."
241
+ },
242
+ {
243
+ name: "paymentStatus",
244
+ description: "Payment status (UNPAID, PARTIALLY_PAID, PAID, ...)."
245
+ },
246
+ {
247
+ name: "approvalStatus",
248
+ description: "Approval status (UNASSIGNED, APPROVED, ...), if set."
249
+ },
250
+ { name: "archived", description: "Whether the bill has been archived." },
251
+ {
252
+ name: "createdAt",
253
+ description: "When the bill was created (Unix ms)."
254
+ }
255
+ ],
256
+ responses: { bills: billsListSchema }
257
+ },
258
+ [PAYMENT_EVENT]: {
259
+ shape: "event",
260
+ filterable: [
261
+ {
262
+ field: "status",
263
+ ops: ["eq"],
264
+ values: ["SCHEDULED", "PAID", "CANCELED"]
265
+ }
266
+ ],
267
+ description: "Vendor payments (money sent to vendors), one event per payment timestamped at its process date.",
268
+ endpoint: "GET /v3/payments",
269
+ fields: [
270
+ { name: "id", description: "BILL payment id." },
271
+ { name: "vendorId", description: "Vendor paid, if set." },
272
+ { name: "billId", description: "Bill the payment applies to, if set." },
273
+ {
274
+ name: "amount",
275
+ description: "Payment amount in the payment currency major units."
276
+ },
277
+ {
278
+ name: "status",
279
+ description: "Payment status (SCHEDULED, PAID, CANCELED)."
280
+ },
281
+ { name: "description", description: "Payment description, if set." },
282
+ {
283
+ name: "processDate",
284
+ description: "Scheduled or actual process date (Unix ms), if set."
285
+ }
286
+ ],
287
+ responses: { payments: paymentsListSchema }
288
+ }
289
+ });
290
+ var id = "bill";
291
+ var BillConnector = class _BillConnector extends BaseConnector {
292
+ static id = id;
293
+ static resources = billResources;
294
+ static schemas = schemasFromResources(billResources);
295
+ static create(input, ctx) {
296
+ const parsed = configFields.parse(input);
297
+ return new _BillConnector(
298
+ { orgId: parsed.orgId, resources: parsed.resources },
299
+ {
300
+ devKey: parsed.devKey,
301
+ username: parsed.username,
302
+ password: parsed.password
303
+ },
304
+ ctx
305
+ );
306
+ }
307
+ id = id;
308
+ credentials = billCredentials;
309
+ sessionId = null;
310
+ baseHeaders() {
311
+ return {
312
+ Accept: "application/json",
313
+ "Content-Type": "application/json",
314
+ "User-Agent": connectorUserAgent("bill")
315
+ };
316
+ }
317
+ async refreshSession(signal) {
318
+ const res = await this.post(`${API_BASE}/login`, {
319
+ resource: "login",
320
+ headers: this.baseHeaders(),
321
+ body: JSON.stringify({
322
+ username: this.creds.username,
323
+ password: this.creds.password,
324
+ organizationId: this.settings.orgId,
325
+ devKey: this.creds.devKey
326
+ }),
327
+ signal
328
+ });
329
+ const sessionId = res.body.sessionId;
330
+ if (!sessionId) {
331
+ throw new Error("BILL login did not return a sessionId");
332
+ }
333
+ this.sessionId = sessionId;
334
+ return sessionId;
335
+ }
336
+ async getSession(signal) {
337
+ if (this.sessionId) {
338
+ return this.sessionId;
339
+ }
340
+ return this.refreshSession(signal);
341
+ }
342
+ async apiGet(url, resource, signal, retried = false) {
343
+ const sessionId = await this.getSession(signal);
344
+ try {
345
+ return await this.get(url, {
346
+ resource,
347
+ headers: {
348
+ ...this.baseHeaders(),
349
+ sessionId,
350
+ devKey: this.creds.devKey
351
+ },
352
+ signal
353
+ });
354
+ } catch (err) {
355
+ if (!retried && isAuthError(err)) {
356
+ this.sessionId = null;
357
+ return this.apiGet(url, resource, signal, true);
358
+ }
359
+ throw err;
360
+ }
361
+ }
362
+ buildListUrl(phase, page, options) {
363
+ const url = new URL(`${API_BASE}/${ENDPOINT_BY_PHASE[phase]}`);
364
+ url.searchParams.set("max", String(PAGE_SIZE));
365
+ if (page) {
366
+ url.searchParams.set("page", page);
367
+ return url.toString();
368
+ }
369
+ url.searchParams.set("sort", "updatedTime:asc");
370
+ if (options.since) {
371
+ const iso = new Date(options.since).toISOString();
372
+ url.searchParams.set("filters", `updatedTime:gte:"${iso}"`);
373
+ }
374
+ return url.toString();
375
+ }
376
+ async fetchPage(phase, page, options, signal) {
377
+ const url = this.buildListUrl(phase, page, options);
378
+ const res = await this.apiGet(
379
+ url,
380
+ phase,
381
+ signal
382
+ );
383
+ const results = res.body.results ?? [];
384
+ const nextPage = res.body.nextPage ?? null;
385
+ const next = nextPage && results.length > 0 ? nextPage : null;
386
+ return { items: results, next };
387
+ }
388
+ async writeVendors(storage, items) {
389
+ for (const v of items) {
390
+ const createdMs = parseEpoch(v.createdTime ?? null, "iso");
391
+ const updatedMs = parseEpoch(v.updatedTime ?? null, "iso");
392
+ await storage.entity({
393
+ type: VENDOR_ENTITY,
394
+ id: v.id,
395
+ attributes: {
396
+ name: v.name ?? null,
397
+ email: v.email ?? null,
398
+ accountNumber: v.accountNumber ?? null,
399
+ phone: v.phone ?? null,
400
+ archived: v.archived ?? false,
401
+ billCurrency: v.billCurrency ?? null,
402
+ createdAt: createdMs
403
+ },
404
+ updated_at: updatedMs ?? createdMs ?? 0
405
+ });
406
+ }
407
+ }
408
+ async writeBills(storage, items) {
409
+ for (const b of items) {
410
+ const createdMs = parseEpoch(b.createdTime ?? null, "iso");
411
+ const updatedMs = parseEpoch(b.updatedTime ?? null, "iso");
412
+ await storage.entity({
413
+ type: BILL_ENTITY,
414
+ id: b.id,
415
+ attributes: {
416
+ vendorId: b.vendorId ?? null,
417
+ invoiceNumber: b.invoice?.invoiceNumber ?? null,
418
+ invoiceDate: parseEpoch(b.invoice?.invoiceDate ?? null, "iso"),
419
+ dueDate: parseEpoch(b.dueDate ?? null, "iso"),
420
+ amount: b.amount ?? null,
421
+ paymentStatus: b.paymentStatus ?? null,
422
+ approvalStatus: b.approvalStatus ?? null,
423
+ archived: b.archived ?? false,
424
+ createdAt: createdMs
425
+ },
426
+ updated_at: updatedMs ?? createdMs ?? 0
427
+ });
428
+ }
429
+ }
430
+ async writePayments(storage, items) {
431
+ for (const p of items) {
432
+ const createdMs = parseEpoch(p.createdTime ?? null, "iso");
433
+ const processMs = parseEpoch(p.processDate ?? null, "iso");
434
+ const ts = processMs ?? createdMs;
435
+ if (ts === null) {
436
+ continue;
437
+ }
438
+ await storage.event({
439
+ name: PAYMENT_EVENT,
440
+ start_ts: ts,
441
+ end_ts: null,
442
+ attributes: {
443
+ id: p.id,
444
+ vendorId: p.vendorId ?? null,
445
+ billId: p.billId ?? null,
446
+ amount: p.amount ?? null,
447
+ status: p.status ?? null,
448
+ description: p.description ?? null,
449
+ processDate: processMs
450
+ }
451
+ });
452
+ }
453
+ }
454
+ async writePhase(storage, phase, items) {
455
+ switch (phase) {
456
+ case "vendors":
457
+ return this.writeVendors(storage, items);
458
+ case "bills":
459
+ return this.writeBills(storage, items);
460
+ case "payments":
461
+ return this.writePayments(storage, items);
462
+ }
463
+ }
464
+ async clearScopeOnFirstPage(storage, phase, isFull) {
465
+ if (!isFull) {
466
+ return;
467
+ }
468
+ switch (phase) {
469
+ case "vendors":
470
+ await storage.entities([], { types: [VENDOR_ENTITY] });
471
+ return;
472
+ case "bills":
473
+ await storage.entities([], { types: [BILL_ENTITY] });
474
+ return;
475
+ case "payments":
476
+ await storage.events([], { names: [PAYMENT_EVENT] });
477
+ return;
478
+ }
479
+ }
480
+ async sync(options, storage, signal) {
481
+ const cursor = isBillSyncCursor(options.cursor) ? options.cursor : void 0;
482
+ const isFull = options.mode === "full";
483
+ const phases = selectActivePhases(
484
+ (r) => r,
485
+ PHASE_ORDER,
486
+ this.settings.resources
487
+ );
488
+ return paginateChunked({
489
+ phases,
490
+ cursor,
491
+ signal,
492
+ logger: this.logger,
493
+ fetchPage: (phase, page, sig) => this.fetchPage(phase, page, options, sig),
494
+ writeBatch: async (phase, items, page) => {
495
+ if (page === null) {
496
+ await this.clearScopeOnFirstPage(storage, phase, isFull);
497
+ }
498
+ await this.writePhase(storage, phase, items);
499
+ }
500
+ });
501
+ }
502
+ };
503
+
504
+ // src/index.ts
505
+ var index_default = BillConnector;
506
+ export {
507
+ BillConnector,
508
+ configFields,
509
+ index_default as default,
510
+ doc,
511
+ id,
512
+ billResources as resources
513
+ };
514
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/map-concurrent.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/bill.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from './types';\n\nexport type HttpErrorKind =\n | 'transient'\n | 'rate_limit'\n | 'auth'\n | 'upstream_bug'\n | 'client_bug';\n\nexport abstract class HttpClientError extends Error {\n abstract readonly kind: HttpErrorKind;\n readonly response?: HttpResponse;\n\n constructor(message: string, response?: HttpResponse) {\n super(message);\n this.name = new.target.name;\n this.response = response;\n }\n}\n\nexport class TransientError extends HttpClientError {\n readonly kind = 'transient' as const;\n}\n\nexport class RateLimitError extends HttpClientError {\n readonly kind = 'rate_limit' as const;\n readonly retryAfter?: Date;\n\n constructor(message: string, response?: HttpResponse, retryAfter?: Date) {\n super(message, response);\n this.retryAfter = retryAfter;\n }\n}\n\nexport class AuthError extends HttpClientError {\n readonly kind = 'auth' as const;\n}\n\nexport class UpstreamBugError extends HttpClientError {\n readonly kind = 'upstream_bug' as const;\n}\n\nexport class ClientBugError extends HttpClientError {\n readonly kind = 'client_bug' as const;\n}\n\nexport function classifyStatus(status: number): HttpErrorKind {\n if (status === 429) {\n return 'rate_limit';\n }\n if (status === 401 || status === 403) {\n return 'auth';\n }\n if (status === 408) {\n return 'transient';\n }\n if (status >= 500) {\n return 'upstream_bug';\n }\n if (status >= 400) {\n return 'client_bug';\n }\n return 'client_bug';\n}\n\nexport function errorForStatus(\n message: string,\n response: HttpResponse,\n retryAfter?: Date,\n): HttpClientError {\n const kind = classifyStatus(response.status);\n switch (kind) {\n case 'rate_limit':\n return new RateLimitError(message, response, retryAfter);\n case 'auth':\n return new AuthError(message, response);\n case 'transient':\n return new TransientError(message, response);\n case 'upstream_bug':\n return new UpstreamBugError(message, response);\n case 'client_bug':\n return new ClientBugError(message, response);\n }\n}\n","import { HttpClientError, RateLimitError, TransientError } from './errors';\n\nexport interface RetryPolicy {\n maxAttempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n retryOn?: (status: number | null, err?: Error) => boolean;\n}\n\nexport const defaultRetryOn = (status: number | null, err?: Error): boolean => {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof TransientError) {\n return true;\n }\n if (status === null) {\n return err instanceof Error && !(err instanceof HttpClientError);\n }\n if (status === 408 || status === 429) {\n return true;\n }\n if (status >= 500) {\n return true;\n }\n return false;\n};\n\nexport function backoffDelayMs(\n attempt: number,\n policy: Required<Pick<RetryPolicy, 'initialDelayMs' | 'maxDelayMs'>>,\n): number {\n const base = policy.initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, policy.maxDelayMs);\n}\n\nexport function parseRetryAfter(\n headerValue: string | null,\n now: Date = new Date(),\n): Date | undefined {\n if (!headerValue) {\n return undefined;\n }\n const trimmed = headerValue.trim();\n if (/^\\d+$/.test(trimmed)) {\n return new Date(now.getTime() + Number(trimmed) * 1000);\n }\n const parsed = Date.parse(trimmed);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return new Date(parsed);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(signal.reason ?? new Error('Aborted'));\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal!.reason ?? new Error('Aborted'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","export const HTTP_CLIENT_VERSION = '0.0.0';\n\nexport const DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n\nexport function connectorUserAgent(connectorId: string): string {\n return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n}\n","import {\n AuthError,\n ClientBugError,\n HttpClientError,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n errorForStatus,\n} from './errors';\nimport { defaultRetryOn, parseRetryAfter, sleep } from './retry';\nimport type { FetchLike, HttpMethod, HttpRequest, HttpResponse } from './types';\nimport { DEFAULT_USER_AGENT } from './version';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 60_000;\nconst OBSERVER_TIMEOUT_MS = 250;\n\nexport interface RequestObservation {\n url: string;\n method: HttpMethod;\n status: number;\n resource: string;\n requestId: string;\n body: unknown;\n}\n\nexport type RequestObserver = (\n event: RequestObservation,\n) => void | Promise<void>;\n\nexport interface RequestOptions {\n fetch?: FetchLike;\n observer?: RequestObserver;\n resource: string;\n requestId?: string;\n}\n\nasync function notifyObserver(\n observer: RequestObserver,\n event: RequestObservation,\n): Promise<void> {\n let result: void | Promise<void>;\n try {\n result = observer(event);\n } catch (err) {\n console.warn('[connector-shared] request observer threw:', err);\n return;\n }\n if (!(result instanceof Promise)) {\n return;\n }\n const guarded = result.catch((err) => {\n console.warn('[connector-shared] request observer rejected:', err);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);\n });\n try {\n await Promise.race([guarded, timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\nfunction newRequestId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction mergeHeaders(\n defaults: Record<string, string>,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n for (const [k, v] of Object.entries(defaults)) {\n merged[k.toLowerCase()] = v;\n }\n if (overrides) {\n for (const [k, v] of Object.entries(overrides)) {\n merged[k.toLowerCase()] = v;\n }\n }\n return merged;\n}\n\nfunction linkTimeoutSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; cancel: () => void } {\n const controller = new AbortController();\n const onParentAbort = () => {\n controller.abort(parent?.reason);\n };\n if (parent) {\n if (parent.aborted) {\n controller.abort(parent.reason);\n } else {\n parent.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n const timer = setTimeout(() => {\n controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n if (parent) {\n parent.removeEventListener('abort', onParentAbort);\n }\n },\n };\n}\n\nasync function readBody(\n res: Response,\n parseJson: boolean,\n binary: boolean,\n): Promise<unknown> {\n if (res.status === 204 || res.status === 205) {\n return null;\n }\n if (binary) {\n return new Uint8Array(await res.arrayBuffer());\n }\n const contentType = res.headers.get('content-type') ?? '';\n if (parseJson && contentType.includes('application/json')) {\n const text = await res.text();\n if (text.length === 0) {\n return null;\n }\n return JSON.parse(text);\n }\n return res.text();\n}\n\nexport async function request<T = unknown>(\n req: HttpRequest,\n options: RequestOptions,\n): Promise<HttpResponse<T>> {\n const fetchImpl: FetchLike = options.fetch ?? (globalThis.fetch as FetchLike);\n const retry = req.retry ?? {};\n const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const parseJson = req.parseJson ?? true;\n const binary = req.binary ?? false;\n\n const headers = mergeHeaders(\n {\n 'User-Agent': DEFAULT_USER_AGENT,\n Accept: 'application/json',\n },\n req.headers,\n );\n\n let lastErr: Error | undefined;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n req.signal?.throwIfAborted();\n\n const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);\n let res: Response;\n try {\n res = await fetchImpl(req.url, {\n method: req.method ?? 'GET',\n headers,\n body: req.body as RequestInit['body'],\n signal,\n });\n } catch (err) {\n cancel();\n if (req.signal?.aborted) {\n throw req.signal.reason ?? err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n lastErr = error;\n if (attempt < maxAttempts - 1 && retryOn(null, error)) {\n const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n await sleep(delay, req.signal);\n continue;\n }\n throw new TransientError(error.message);\n }\n cancel();\n\n const body = await readBody(res, parseJson, binary);\n const httpResponse: HttpResponse<T> = {\n status: res.status,\n headers: res.headers,\n body: body as T,\n };\n if (req.rateLimit) {\n const state = req.rateLimit.parse(res.headers);\n if (state) {\n httpResponse.rateLimitState = state;\n }\n }\n\n if (options.observer) {\n await notifyObserver(options.observer, {\n url: req.url,\n method: req.method ?? 'GET',\n status: res.status,\n resource: options.resource,\n requestId: options.requestId ?? newRequestId(),\n body,\n });\n }\n\n if (res.ok) {\n return httpResponse;\n }\n\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? 'GET'} ${req.url}`;\n const err = errorForStatus(message, httpResponse, retryAfter);\n\n if (\n attempt < maxAttempts - 1 &&\n retryOn(res.status, err) &&\n !(err instanceof AuthError) &&\n !(err instanceof ClientBugError)\n ) {\n lastErr = err;\n let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n if (err instanceof RateLimitError && retryAfter) {\n const wait = retryAfter.getTime() - Date.now();\n if (wait > 0) {\n delay = Math.min(wait, maxDelayMs);\n }\n }\n await sleep(delay, req.signal);\n continue;\n }\n\n throw err;\n }\n\n throw lastErr ?? new UpstreamBugError('Exhausted retry attempts');\n}\n\nfunction computeDelay(\n attempt: number,\n initialDelayMs: number,\n maxDelayMs: number,\n): number {\n const base = initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, maxDelayMs);\n}\n\nexport { HttpClientError };\n","export interface RateLimitState {\n remaining: number;\n resetAt: Date;\n}\n\nexport interface RateLimitPolicy {\n parse(headers: Headers): RateLimitState | null;\n}\n\nexport interface StandardRateLimitPolicyConfig {\n remainingHeader: string;\n resetHeader: string;\n resetUnit: 's' | 'ms';\n resetFallbackMs?: number;\n}\n\nexport function standardRateLimitPolicy(\n config: StandardRateLimitPolicyConfig,\n): RateLimitPolicy {\n const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;\n const multiplier = resetUnit === 's' ? 1000 : 1;\n return {\n parse(h) {\n const remainingRaw = h.get(remainingHeader);\n if (remainingRaw === null || remainingRaw.trim() === '') {\n return null;\n }\n const remaining = Number(remainingRaw);\n if (!Number.isFinite(remaining)) {\n return null;\n }\n const resetRaw = h.get(resetHeader);\n if (resetRaw === null) {\n if (resetFallbackMs === undefined) {\n return null;\n }\n return {\n remaining,\n resetAt: new Date(Date.now() + resetFallbackMs),\n };\n }\n if (resetRaw.trim() === '') {\n return null;\n }\n const reset = Number(resetRaw);\n if (!Number.isFinite(reset) || reset < 0) {\n return null;\n }\n const resetMs = reset * multiplier;\n if (!Number.isFinite(resetMs)) {\n return null;\n }\n return { remaining, resetAt: new Date(resetMs) };\n },\n };\n}\n","export async function mapWithConcurrency<T, R>(\n items: readonly T[],\n concurrency: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n if (items.length === 0) {\n return results;\n }\n const normalized = Number.isFinite(concurrency) ? Math.floor(concurrency) : 1;\n const limit = Math.max(1, Math.min(normalized, items.length));\n let next = 0;\n let failed = false;\n\n async function worker(): Promise<void> {\n while (!failed) {\n const i = next++;\n if (i >= items.length) {\n return;\n }\n try {\n results[i] = await fn(items[i]!, i);\n } catch (err) {\n failed = true;\n throw err;\n }\n }\n }\n\n const workers: Promise<void>[] = [];\n for (let w = 0; w < limit; w++) {\n workers.push(worker());\n }\n await Promise.all(workers);\n return results;\n}\n","export interface SanitizeAllowedUrlOptions {\n url: string | null;\n host: string;\n pathname: string;\n protocol?: 'https:' | 'http:';\n}\n\nexport function sanitizeAllowedUrl(\n options: SanitizeAllowedUrlOptions,\n): string | null {\n const { url, host, pathname, protocol = 'https:' } = options;\n if (url === null) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n}\n","export type EpochUnit = 'ms' | 's' | 'iso';\n\nexport function parseEpoch(\n value: number | string | null | undefined,\n unit: EpochUnit,\n): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (unit === 'iso') {\n if (typeof value !== 'string') {\n return null;\n }\n const ms = new Date(value).getTime();\n return Number.isFinite(ms) ? ms : null;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) {\n return null;\n }\n const result = unit === 's' ? n * 1000 : n;\n return Number.isFinite(result) ? result : null;\n}\n","import { request } from './request';\nimport type { HttpRequest } from './types';\n\nexport function parseLinkHeader(header: string | null): Record<string, string> {\n if (!header) {\n return {};\n }\n const result: Record<string, string> = {};\n for (const part of header.split(',')) {\n const match = part.match(/<([^>]+)>\\s*;\\s*rel=\"([^\"]+)\"/);\n if (match) {\n result[match[2]!] = match[1]!;\n }\n }\n return result;\n}\n\nexport async function* paginateLink<T>(\n initial: HttpRequest,\n parse: (body: unknown) => T[],\n options: { resource: string },\n): AsyncIterable<T> {\n let next: string | null = initial.url;\n while (next) {\n const res: Awaited<ReturnType<typeof request>> = await request(\n {\n ...initial,\n url: next,\n },\n { resource: options.resource },\n );\n for (const item of parse(res.body)) {\n yield item;\n }\n const links = parseLinkHeader(res.headers.get('link'));\n next = links['next'] ?? null;\n }\n}\n\nexport async function* paginateCursor<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; nextCursor: string | null },\n buildNext: (req: HttpRequest, cursor: string) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let req: HttpRequest = initial;\n while (true) {\n const res = await request(req, { resource: options.resource });\n const { items, nextCursor } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!nextCursor) {\n return;\n }\n req = buildNext(req, nextCursor);\n }\n}\n\nexport async function* paginatePage<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; hasMore: boolean },\n buildPage: (req: HttpRequest, page: number) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let page = 1;\n while (true) {\n const req = page === 1 ? initial : buildPage(initial, page);\n const res = await request(req, { resource: options.resource });\n const { items, hasMore } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!hasMore || items.length === 0) {\n return;\n }\n page++;\n }\n}\n","export type LogFields = Record<string, unknown>;\n\nexport interface ConnectorLogger {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n}\n\nexport interface ConnectorLoggerOptions {\n scope: string;\n}\n\nconst MAX_VALUE_LEN = 120;\n\nfunction truncate(s: string, max = MAX_VALUE_LEN): string {\n if (s.length <= max) {\n return s;\n }\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return '';\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (typeof value === 'string') {\n const t = truncate(value);\n if (/[\\s\"=]/.test(t)) {\n return JSON.stringify(t);\n }\n return t;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n return truncate(json ?? String(value));\n}\n\nexport function formatLogFields(fields?: LogFields): string {\n if (!fields) {\n return '';\n }\n const parts: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${formatValue(v)}`);\n }\n return parts.length > 0 ? ` ${parts.join(' ')}` : '';\n}\n\nexport function formatLogLine(\n scope: string,\n event: string,\n fields?: LogFields,\n): string {\n return `[${scope}] ${event}${formatLogFields(fields)}`;\n}\n\nexport function createDefaultConnectorLogger(\n opts: ConnectorLoggerOptions,\n): ConnectorLogger {\n return {\n info(event, fields) {\n console.info(formatLogLine(opts.scope, event, fields));\n },\n warn(event, fields) {\n console.warn(formatLogLine(opts.scope, event, fields));\n },\n };\n}\n\nconst NOOP_LOGGER: ConnectorLogger = {\n info() {},\n warn() {},\n};\n\nexport function noopConnectorLogger(): ConnectorLogger {\n return NOOP_LOGGER;\n}\n","import {\n type HttpResponse,\n connectorUserAgent,\n parseEpoch,\n} from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type ConnectorDoc,\n type CredentialsSchema,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n defineConnectorDoc,\n defineResources,\n makeChunkedCursorGuard,\n paginateChunked,\n schemasFromResources,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\nexport const configFields = defineConfigFields(\n z.object({\n devKey: z.object({ $secret: z.string().min(1) }).meta({\n label: 'Developer key',\n description:\n 'BILL developer key that authorizes API access for your app. Find it in the BILL Developer portal under your app.',\n placeholder: 'BILL_DEV_KEY',\n secret: true,\n }),\n username: z.string().min(1).meta({\n label: 'Username',\n description:\n 'Email address of the BILL user the API signs in as. This user must have access to the organization you are syncing.',\n placeholder: 'api-user@example.com',\n }),\n password: z.object({ $secret: z.string().min(1) }).meta({\n label: 'Password',\n description: 'Password for the BILL user. Stored as a secret.',\n placeholder: 'BILL_PASSWORD',\n secret: true,\n }),\n orgId: z.string().min(1).meta({\n label: 'Organization ID',\n description:\n 'BILL organization ID to sync. Find it in the BILL app URL or via the List Organizations API.',\n placeholder: '00801ABCDEFGHIJKLMNO',\n }),\n resources: z\n .array(z.enum(['bills', 'vendors', 'payments']))\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which BILL resources to sync. Omit to sync all of them (bills, vendors, payments).',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'Bill.com',\n category: 'finance',\n brandColor: '#005DAA',\n tagline:\n 'Sync accounts-payable bills, vendors, and vendor payments from BILL (Bill.com) for AP aging, bills-pending, and vendor-spend dashboards.',\n vendor: {\n name: 'Bill.com',\n domain: 'bill.com',\n apiDocs: 'https://developer.bill.com/docs/home',\n website: 'https://www.bill.com',\n },\n auth: {\n summary:\n 'Session-based sign in against the BILL v3 API. The connector signs in with a developer key, username, password, and organization ID to obtain a session, then reuses it for the rest of the sync.',\n setup: [\n 'Request a BILL developer key from the BILL Developer portal and note the key value.',\n 'Create or choose a BILL user with access to the organization you want to sync.',\n 'Find the organization ID for that organization (visible in the app URL or via the List Organizations API).',\n 'Store the developer key and the user password as rawdash secrets and reference them from the connector config as `devKey: secret(\"BILL_DEV_KEY\")` and `password: secret(\"BILL_PASSWORD\")`.',\n ],\n },\n rateLimit:\n 'BILL does not publish standard rate-limit response headers; the shared HTTP client retries 429 responses with exponential backoff. Sessions expire after 35 minutes of inactivity and are transparently re-established on a 401.',\n limitations: [\n 'Monetary amounts are stored in major currency units (e.g. dollars), matching the BILL API, not in the smallest unit.',\n 'Incremental syncs filter on updatedTime, so status transitions (a bill moving from UNPAID to PAID) are picked up on the next run.',\n 'The set of synced resources is controlled by the `resources` config field; omit it to sync all of them.',\n 'Bill line items and approval workflow detail are out of scope; only the header-level bill, its vendor, and vendor payments are synced.',\n ],\n});\n\nexport type BillResource = 'bills' | 'vendors' | 'payments';\n\nexport interface BillSettings {\n orgId: string;\n resources?: readonly BillResource[];\n}\n\nconst billCredentials = {\n devKey: {\n description: 'BILL developer key',\n auth: 'required' as const,\n },\n username: {\n description: 'BILL user email',\n auth: 'required' as const,\n },\n password: {\n description: 'BILL user password',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype BillCredentials = typeof billCredentials;\n\nconst API_BASE = 'https://gateway.prod.bill.com/connect/v3';\nconst PAGE_SIZE = 100;\n\nconst PHASE_ORDER = ['vendors', 'bills', 'payments'] as const;\n\ntype BillPhase = (typeof PHASE_ORDER)[number];\n\ntype BillSyncCursor = ChunkedSyncCursor<BillPhase, string>;\n\nconst isBillSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\nconst VENDOR_ENTITY = 'bill_vendor';\nconst BILL_ENTITY = 'bill_bill';\nconst PAYMENT_EVENT = 'bill_payment';\n\nconst ENDPOINT_BY_PHASE: Record<BillPhase, string> = {\n vendors: 'vendors',\n bills: 'bills',\n payments: 'payments',\n};\n\nfunction isAuthError(err: unknown): boolean {\n return err instanceof Error && (err as { kind?: unknown }).kind === 'auth';\n}\n\nconst idString = z.string().min(1);\n\nconst loginSchema = z.object({\n sessionId: idString,\n organizationId: z.string().nullish(),\n userId: z.string().nullish(),\n});\n\nconst vendorSchema = z.object({\n id: idString,\n name: z.string().nullish(),\n email: z.string().nullish(),\n accountNumber: z.string().nullish(),\n phone: z.string().nullish(),\n archived: z.boolean().nullish(),\n billCurrency: z.string().nullish(),\n createdTime: z.string().nullish(),\n updatedTime: z.string().nullish(),\n});\n\nconst billSchema = z.object({\n id: idString,\n vendorId: z.string().nullish(),\n amount: z.number().nullish(),\n dueDate: z.string().nullish(),\n invoice: z\n .object({\n invoiceNumber: z.string().nullish(),\n invoiceDate: z.string().nullish(),\n })\n .nullish(),\n paymentStatus: z.string().nullish(),\n approvalStatus: z.string().nullish(),\n archived: z.boolean().nullish(),\n createdTime: z.string().nullish(),\n updatedTime: z.string().nullish(),\n});\n\nconst paymentSchema = z.object({\n id: idString,\n vendorId: z.string().nullish(),\n billId: z.string().nullish(),\n amount: z.number().nullish(),\n processDate: z.string().nullish(),\n status: z.string().nullish(),\n description: z.string().nullish(),\n createdTime: z.string().nullish(),\n updatedTime: z.string().nullish(),\n});\n\nconst listResponseSchema = <T extends z.ZodTypeAny>(item: T) =>\n z.object({\n results: z.array(item),\n nextPage: z.string().nullish(),\n prevPage: z.string().nullish(),\n });\n\nconst vendorsListSchema = listResponseSchema(vendorSchema);\nconst billsListSchema = listResponseSchema(billSchema);\nconst paymentsListSchema = listResponseSchema(paymentSchema);\n\nexport const billResources = defineResources({\n [VENDOR_ENTITY]: {\n shape: 'entity',\n filterable: [{ field: 'archived', ops: ['eq'], values: ['true', 'false'] }],\n description:\n 'Vendors (suppliers) with name, contact details, account number, and archived state.',\n endpoint: 'GET /v3/vendors',\n notes:\n 'Incremental syncs filter on updatedTime and sort ascending so resumable pages stay ordered.',\n fields: [\n { name: 'name', description: 'Vendor display name.' },\n { name: 'email', description: 'Vendor contact email, if set.' },\n {\n name: 'accountNumber',\n description: 'Your account number with the vendor, if set.',\n },\n { name: 'phone', description: 'Vendor phone number, if set.' },\n {\n name: 'archived',\n description: 'Whether the vendor has been archived.',\n },\n {\n name: 'billCurrency',\n description: 'Default bill currency for the vendor (ISO code).',\n },\n {\n name: 'createdAt',\n description: 'When the vendor was created (Unix ms).',\n },\n ],\n responses: {\n login: loginSchema,\n vendors: vendorsListSchema,\n },\n },\n [BILL_ENTITY]: {\n shape: 'entity',\n filterable: [\n {\n field: 'paymentStatus',\n ops: ['eq'],\n values: [\n 'UNPAID',\n 'PARTIALLY_PAID',\n 'PAID',\n 'SCHEDULED',\n 'PARTIALLY_SCHEDULED',\n ],\n },\n ],\n description:\n 'Accounts-payable bills with vendor, invoice number, invoice and due dates, amount, and payment status.',\n endpoint: 'GET /v3/bills',\n notes:\n 'Amounts are in the bill currency major units (e.g. dollars). Incremental syncs filter on updatedTime so status transitions are re-fetched.',\n fields: [\n { name: 'vendorId', description: 'Vendor the bill is owed to.' },\n { name: 'invoiceNumber', description: 'Vendor invoice number, if set.' },\n {\n name: 'invoiceDate',\n description: 'Invoice date (Unix ms), if set.',\n },\n { name: 'dueDate', description: 'Payment due date (Unix ms), if set.' },\n {\n name: 'amount',\n description: 'Bill total in the bill currency major units.',\n },\n {\n name: 'paymentStatus',\n description: 'Payment status (UNPAID, PARTIALLY_PAID, PAID, ...).',\n },\n {\n name: 'approvalStatus',\n description: 'Approval status (UNASSIGNED, APPROVED, ...), if set.',\n },\n { name: 'archived', description: 'Whether the bill has been archived.' },\n {\n name: 'createdAt',\n description: 'When the bill was created (Unix ms).',\n },\n ],\n responses: { bills: billsListSchema },\n },\n [PAYMENT_EVENT]: {\n shape: 'event',\n filterable: [\n {\n field: 'status',\n ops: ['eq'],\n values: ['SCHEDULED', 'PAID', 'CANCELED'],\n },\n ],\n description:\n 'Vendor payments (money sent to vendors), one event per payment timestamped at its process date.',\n endpoint: 'GET /v3/payments',\n fields: [\n { name: 'id', description: 'BILL payment id.' },\n { name: 'vendorId', description: 'Vendor paid, if set.' },\n { name: 'billId', description: 'Bill the payment applies to, if set.' },\n {\n name: 'amount',\n description: 'Payment amount in the payment currency major units.',\n },\n {\n name: 'status',\n description: 'Payment status (SCHEDULED, PAID, CANCELED).',\n },\n { name: 'description', description: 'Payment description, if set.' },\n {\n name: 'processDate',\n description: 'Scheduled or actual process date (Unix ms), if set.',\n },\n ],\n responses: { payments: paymentsListSchema },\n },\n});\n\nexport const id = 'bill';\n\ntype BillLogin = z.infer<typeof loginSchema>;\ntype BillVendor = z.infer<typeof vendorSchema>;\ntype BillBill = z.infer<typeof billSchema>;\ntype BillPayment = z.infer<typeof paymentSchema>;\n\ninterface BillListResponse<T> {\n results: T[];\n nextPage?: string | null;\n prevPage?: string | null;\n}\n\nexport class BillConnector extends BaseConnector<\n BillSettings,\n BillCredentials\n> {\n static readonly id = id;\n\n static readonly resources = billResources;\n\n static readonly schemas = schemasFromResources(billResources);\n\n static create(input: unknown, ctx?: ConnectorContext): BillConnector {\n const parsed = configFields.parse(input);\n return new BillConnector(\n { orgId: parsed.orgId, resources: parsed.resources },\n {\n devKey: parsed.devKey,\n username: parsed.username,\n password: parsed.password,\n },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = billCredentials;\n\n private sessionId: string | null = null;\n\n private baseHeaders(): Record<string, string> {\n return {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'User-Agent': connectorUserAgent('bill'),\n };\n }\n\n private async refreshSession(signal?: AbortSignal): Promise<string> {\n const res = await this.post<BillLogin>(`${API_BASE}/login`, {\n resource: 'login',\n headers: this.baseHeaders(),\n body: JSON.stringify({\n username: this.creds.username,\n password: this.creds.password,\n organizationId: this.settings.orgId,\n devKey: this.creds.devKey,\n }),\n signal,\n });\n const sessionId = res.body.sessionId;\n if (!sessionId) {\n throw new Error('BILL login did not return a sessionId');\n }\n this.sessionId = sessionId;\n return sessionId;\n }\n\n private async getSession(signal?: AbortSignal): Promise<string> {\n if (this.sessionId) {\n return this.sessionId;\n }\n return this.refreshSession(signal);\n }\n\n private async apiGet<T>(\n url: string,\n resource: string,\n signal?: AbortSignal,\n retried = false,\n ): Promise<HttpResponse<T>> {\n const sessionId = await this.getSession(signal);\n try {\n return await this.get<T>(url, {\n resource,\n headers: {\n ...this.baseHeaders(),\n sessionId,\n devKey: this.creds.devKey,\n },\n signal,\n });\n } catch (err) {\n if (!retried && isAuthError(err)) {\n this.sessionId = null;\n return this.apiGet<T>(url, resource, signal, true);\n }\n throw err;\n }\n }\n\n private buildListUrl(\n phase: BillPhase,\n page: string | null,\n options: SyncOptions,\n ): string {\n const url = new URL(`${API_BASE}/${ENDPOINT_BY_PHASE[phase]}`);\n url.searchParams.set('max', String(PAGE_SIZE));\n if (page) {\n url.searchParams.set('page', page);\n return url.toString();\n }\n url.searchParams.set('sort', 'updatedTime:asc');\n if (options.since) {\n const iso = new Date(options.since).toISOString();\n url.searchParams.set('filters', `updatedTime:gte:\"${iso}\"`);\n }\n return url.toString();\n }\n\n private async fetchPage(\n phase: BillPhase,\n page: string | null,\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<{ items: unknown[]; next: string | null }> {\n const url = this.buildListUrl(phase, page, options);\n const res = await this.apiGet<BillListResponse<{ id: string }>>(\n url,\n phase,\n signal,\n );\n const results = res.body.results ?? [];\n const nextPage = res.body.nextPage ?? null;\n const next = nextPage && results.length > 0 ? nextPage : null;\n return { items: results, next };\n }\n\n private async writeVendors(\n storage: StorageHandle,\n items: BillVendor[],\n ): Promise<void> {\n for (const v of items) {\n const createdMs = parseEpoch(v.createdTime ?? null, 'iso');\n const updatedMs = parseEpoch(v.updatedTime ?? null, 'iso');\n await storage.entity({\n type: VENDOR_ENTITY,\n id: v.id,\n attributes: {\n name: v.name ?? null,\n email: v.email ?? null,\n accountNumber: v.accountNumber ?? null,\n phone: v.phone ?? null,\n archived: v.archived ?? false,\n billCurrency: v.billCurrency ?? null,\n createdAt: createdMs,\n },\n updated_at: updatedMs ?? createdMs ?? 0,\n });\n }\n }\n\n private async writeBills(\n storage: StorageHandle,\n items: BillBill[],\n ): Promise<void> {\n for (const b of items) {\n const createdMs = parseEpoch(b.createdTime ?? null, 'iso');\n const updatedMs = parseEpoch(b.updatedTime ?? null, 'iso');\n await storage.entity({\n type: BILL_ENTITY,\n id: b.id,\n attributes: {\n vendorId: b.vendorId ?? null,\n invoiceNumber: b.invoice?.invoiceNumber ?? null,\n invoiceDate: parseEpoch(b.invoice?.invoiceDate ?? null, 'iso'),\n dueDate: parseEpoch(b.dueDate ?? null, 'iso'),\n amount: b.amount ?? null,\n paymentStatus: b.paymentStatus ?? null,\n approvalStatus: b.approvalStatus ?? null,\n archived: b.archived ?? false,\n createdAt: createdMs,\n },\n updated_at: updatedMs ?? createdMs ?? 0,\n });\n }\n }\n\n private async writePayments(\n storage: StorageHandle,\n items: BillPayment[],\n ): Promise<void> {\n for (const p of items) {\n const createdMs = parseEpoch(p.createdTime ?? null, 'iso');\n const processMs = parseEpoch(p.processDate ?? null, 'iso');\n const ts = processMs ?? createdMs;\n if (ts === null) {\n continue;\n }\n await storage.event({\n name: PAYMENT_EVENT,\n start_ts: ts,\n end_ts: null,\n attributes: {\n id: p.id,\n vendorId: p.vendorId ?? null,\n billId: p.billId ?? null,\n amount: p.amount ?? null,\n status: p.status ?? null,\n description: p.description ?? null,\n processDate: processMs,\n },\n });\n }\n }\n\n private async writePhase(\n storage: StorageHandle,\n phase: BillPhase,\n items: unknown[],\n ): Promise<void> {\n switch (phase) {\n case 'vendors':\n return this.writeVendors(storage, items as BillVendor[]);\n case 'bills':\n return this.writeBills(storage, items as BillBill[]);\n case 'payments':\n return this.writePayments(storage, items as BillPayment[]);\n }\n }\n\n private async clearScopeOnFirstPage(\n storage: StorageHandle,\n phase: BillPhase,\n isFull: boolean,\n ): Promise<void> {\n if (!isFull) {\n return;\n }\n switch (phase) {\n case 'vendors':\n await storage.entities([], { types: [VENDOR_ENTITY] });\n return;\n case 'bills':\n await storage.entities([], { types: [BILL_ENTITY] });\n return;\n case 'payments':\n await storage.events([], { names: [PAYMENT_EVENT] });\n return;\n }\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor: BillSyncCursor | undefined = isBillSyncCursor(options.cursor)\n ? options.cursor\n : undefined;\n const isFull = options.mode === 'full';\n\n const phases = selectActivePhases<BillResource, BillPhase>(\n (r) => r,\n PHASE_ORDER,\n this.settings.resources,\n );\n\n return paginateChunked<BillPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: (phase, page, sig) =>\n this.fetchPage(phase, page, options, sig),\n writeBatch: async (phase, items, page) => {\n if (page === null) {\n await this.clearScopeOnFirstPage(storage, phase, isFull);\n }\n await this.writePhase(storage, phase, items);\n },\n });\n }\n}\n","import { BillConnector } from './bill';\n\nexport {\n configFields,\n doc,\n id,\n billResources as resources,\n BillConnector,\n} from './bill';\nexport type { BillResource, BillSettings } from './bill';\nexport default BillConnector;\n"],"mappings":";AEAO,IAAM,s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AACA,YAAQ,OAAO;AAAA,MACb,KAAK;AACH,cAAM,QAAQ,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,aAAa,EAAE,CAAC;AACrD;AAAA,MACF,KAAK;AACH,cAAM,QAAQ,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,WAAW,EAAE,CAAC;AACnD;AAAA,MACF,KAAK;AACH,cAAM,QAAQ,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,aAAa,EAAE,CAAC;AACnD;AAAA,IACJ;AAAA,EACF;AAAA,EAEA,MAAM,KACJ,SACA,SACA,QACqB;AACrB,UAAM,SAAqC,iBAAiB,QAAQ,MAAM,IACtE,QAAQ,SACR;AACJ,UAAM,SAAS,QAAQ,SAAS;AAEhC,UAAM,SAAS;AAAA,MACb,CAAC,MAAM;AAAA,MACP;AAAA,MACA,KAAK,SAAS;AAAA,IAChB;AAEA,WAAO,gBAAmC;AAAA,MACxC;AAAA,MACA;AAAA,MACA;AAAA,MACA,QAAQ,KAAK;AAAA,MACb,WAAW,CAAC,OAAO,MAAM,QACvB,KAAK,UAAU,OAAO,MAAM,SAAS,GAAG;AAAA,MAC1C,YAAY,OAAO,OAAO,OAAO,SAAS;AACxC,YAAI,SAAS,MAAM;AACjB,gBAAM,KAAK,sBAAsB,SAAS,OAAO,MAAM;AAAA,QACzD;AACA,cAAM,KAAK,WAAW,SAAS,OAAO,KAAK;AAAA,MAC7C;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;ACplBA,IAAO,gBAAQ;","names":[]}
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@rawdash/connector-bill",
3
+ "version": "0.28.2",
4
+ "description": "Rawdash connector for BILL (Bill.com) — accounts payable bills, vendors, and payments",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/rawdash/rawdash.git",
11
+ "directory": "packages/connectors/bill"
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "exports": {
19
+ ".": {
20
+ "@rawdash/source": "./src/index.ts",
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js"
23
+ }
24
+ },
25
+ "scripts": {
26
+ "build": "tsup",
27
+ "typecheck": "tsc --noEmit",
28
+ "lint": "eslint src",
29
+ "test": "vitest run"
30
+ },
31
+ "dependencies": {
32
+ "@rawdash/core": "workspace:*",
33
+ "zod": "^4.4.3"
34
+ },
35
+ "devDependencies": {
36
+ "@rawdash/connector-shared": "workspace:*",
37
+ "@rawdash/connector-test-utils": "workspace:*",
38
+ "fast-check": "^4.8.0",
39
+ "tsup": "^8.0.0",
40
+ "typescript": "^5.7.2",
41
+ "vitest": "^4.1.4"
42
+ }
43
+ }