@superdurable/connector-intuit-quickbooks 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +91 -2
- package/dex-connector.json +559 -0
- package/dist/chunk-MBZ23PGI.js +514 -0
- package/dist/connection-yvzYeBut.d.ts +681 -0
- package/dist/index.d.ts +660 -0
- package/dist/index.js +1755 -0
- package/dist/mock.d.ts +190 -0
- package/dist/mock.js +455 -0
- package/package.json +63 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1755 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ConfigSchema,
|
|
3
|
+
Connection,
|
|
4
|
+
ConnectorID,
|
|
5
|
+
CreateCustomerBranch,
|
|
6
|
+
CreateCustomerBranchCreated,
|
|
7
|
+
CreateCustomerBranchDefect,
|
|
8
|
+
CreateCustomerBranchNameConflict,
|
|
9
|
+
CreateCustomerBranchProviderRejected,
|
|
10
|
+
CreateCustomerBranchUncertain,
|
|
11
|
+
CreateCustomerDefinition,
|
|
12
|
+
CreateCustomerInputSchema,
|
|
13
|
+
CreateCustomerMetadata,
|
|
14
|
+
CreateCustomerOutputSchema,
|
|
15
|
+
CreateInvoiceBranch,
|
|
16
|
+
CreateInvoiceBranchCreated,
|
|
17
|
+
CreateInvoiceBranchDefect,
|
|
18
|
+
CreateInvoiceBranchProviderRejected,
|
|
19
|
+
CreateInvoiceBranchUncertain,
|
|
20
|
+
CreateInvoiceDefinition,
|
|
21
|
+
CreateInvoiceInputSchema,
|
|
22
|
+
CreateInvoiceMetadata,
|
|
23
|
+
CreateInvoiceOutputSchema,
|
|
24
|
+
CustomerSchema,
|
|
25
|
+
FindCustomerBranch,
|
|
26
|
+
FindCustomerBranchAmbiguous,
|
|
27
|
+
FindCustomerBranchDefect,
|
|
28
|
+
FindCustomerBranchFound,
|
|
29
|
+
FindCustomerBranchInvalidResponse,
|
|
30
|
+
FindCustomerBranchNotFound,
|
|
31
|
+
FindCustomerBranchProviderRejected,
|
|
32
|
+
FindCustomerDefinition,
|
|
33
|
+
FindCustomerInputSchema,
|
|
34
|
+
FindCustomerMetadata,
|
|
35
|
+
FindCustomerOutputSchema,
|
|
36
|
+
GetInvoiceBranch,
|
|
37
|
+
GetInvoiceBranchDefect,
|
|
38
|
+
GetInvoiceBranchFound,
|
|
39
|
+
GetInvoiceBranchInvalidResponse,
|
|
40
|
+
GetInvoiceBranchNotFound,
|
|
41
|
+
GetInvoiceBranchProviderRejected,
|
|
42
|
+
GetInvoiceDefinition,
|
|
43
|
+
GetInvoiceInputSchema,
|
|
44
|
+
GetInvoiceMetadata,
|
|
45
|
+
InvoiceLineInputSchema,
|
|
46
|
+
InvoiceLineSchema,
|
|
47
|
+
InvoicePageSchema,
|
|
48
|
+
InvoiceSchema,
|
|
49
|
+
ListInvoicesBranch,
|
|
50
|
+
ListInvoicesBranchDefect,
|
|
51
|
+
ListInvoicesBranchInvalidResponse,
|
|
52
|
+
ListInvoicesBranchListed,
|
|
53
|
+
ListInvoicesBranchProviderRejected,
|
|
54
|
+
ListInvoicesDefinition,
|
|
55
|
+
ListInvoicesInputSchema,
|
|
56
|
+
ListInvoicesMetadata,
|
|
57
|
+
PaymentApplicationSchema,
|
|
58
|
+
PaymentSchema,
|
|
59
|
+
ProviderID,
|
|
60
|
+
RecordPaymentBranch,
|
|
61
|
+
RecordPaymentBranchDefect,
|
|
62
|
+
RecordPaymentBranchProviderRejected,
|
|
63
|
+
RecordPaymentBranchRecorded,
|
|
64
|
+
RecordPaymentBranchUncertain,
|
|
65
|
+
RecordPaymentDefinition,
|
|
66
|
+
RecordPaymentInputSchema,
|
|
67
|
+
RecordPaymentMetadata,
|
|
68
|
+
SendInvoiceBranch,
|
|
69
|
+
SendInvoiceBranchDefect,
|
|
70
|
+
SendInvoiceBranchProviderRejected,
|
|
71
|
+
SendInvoiceBranchSent,
|
|
72
|
+
SendInvoiceBranchUncertain,
|
|
73
|
+
SendInvoiceDefinition,
|
|
74
|
+
SendInvoiceInputSchema,
|
|
75
|
+
SendInvoiceMetadata,
|
|
76
|
+
decodeCredentials,
|
|
77
|
+
decodeSharedCredentials,
|
|
78
|
+
newConnection,
|
|
79
|
+
newConnectionWithOperations,
|
|
80
|
+
newProjectConnection,
|
|
81
|
+
newProjectCredentialProvider
|
|
82
|
+
} from "./chunk-MBZ23PGI.js";
|
|
83
|
+
|
|
84
|
+
// src/client.ts
|
|
85
|
+
import { BodyTooLargeError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest } from "@superdurable/connectors-sdk/providerhttp";
|
|
86
|
+
import { isIP as isIP2 } from "net";
|
|
87
|
+
import { ManifestCredentialRefreshDriver } from "@superdurable/connectors-sdk/oauthtoken";
|
|
88
|
+
import { ReauthorizationRequiredError, defaultTriggerLogger, resolveCredential, resolveCredentialAfterRejection } from "@superdurable/connectors-sdk";
|
|
89
|
+
|
|
90
|
+
// src/generated/refresh.ts
|
|
91
|
+
var Authorization = {
|
|
92
|
+
"fields": [
|
|
93
|
+
{
|
|
94
|
+
"name": "client_id",
|
|
95
|
+
"required": true,
|
|
96
|
+
"type": "string"
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
"name": "client_secret",
|
|
100
|
+
"required": true,
|
|
101
|
+
"type": "secretString"
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
"name": "access_token",
|
|
105
|
+
"required": true,
|
|
106
|
+
"type": "secretString"
|
|
107
|
+
},
|
|
108
|
+
{
|
|
109
|
+
"name": "refresh_token",
|
|
110
|
+
"required": true,
|
|
111
|
+
"type": "secretString"
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
"name": "id_token",
|
|
115
|
+
"required": false,
|
|
116
|
+
"type": "secretString"
|
|
117
|
+
}
|
|
118
|
+
],
|
|
119
|
+
"oauth2": {
|
|
120
|
+
"clientIDCredential": "client_id",
|
|
121
|
+
"clientSecretCredential": "client_secret",
|
|
122
|
+
"credentialMappings": [
|
|
123
|
+
{
|
|
124
|
+
"credential": "access_token",
|
|
125
|
+
"source": "access_token"
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
"credential": "refresh_token",
|
|
129
|
+
"source": "refresh_token"
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
"credential": "id_token",
|
|
133
|
+
"source": "id_token"
|
|
134
|
+
}
|
|
135
|
+
],
|
|
136
|
+
"refresh": {
|
|
137
|
+
"grants": [
|
|
138
|
+
{
|
|
139
|
+
"credentialMappings": [
|
|
140
|
+
{
|
|
141
|
+
"credential": "access_token",
|
|
142
|
+
"source": "access_token"
|
|
143
|
+
},
|
|
144
|
+
{
|
|
145
|
+
"credential": "refresh_token",
|
|
146
|
+
"source": "refresh_token"
|
|
147
|
+
}
|
|
148
|
+
],
|
|
149
|
+
"refreshTokenCredential": "refresh_token"
|
|
150
|
+
}
|
|
151
|
+
],
|
|
152
|
+
"missingExpiry": "reject",
|
|
153
|
+
"requiredScopes": [
|
|
154
|
+
"com.intuit.quickbooks.accounting"
|
|
155
|
+
],
|
|
156
|
+
"scopeSeparators": "whitespaceAndComma",
|
|
157
|
+
"storedMissingExpiry": "refresh",
|
|
158
|
+
"terminalErrorCodes": [
|
|
159
|
+
"invalid_grant",
|
|
160
|
+
"invalid_client",
|
|
161
|
+
"unauthorized_client",
|
|
162
|
+
"unsupported_grant_type"
|
|
163
|
+
],
|
|
164
|
+
"tokenExchangeTimeout": "8s"
|
|
165
|
+
},
|
|
166
|
+
"scopes": [
|
|
167
|
+
"com.intuit.quickbooks.accounting",
|
|
168
|
+
"openid"
|
|
169
|
+
],
|
|
170
|
+
"tokenEndpoint": "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer",
|
|
171
|
+
"tokenEndpointAuthMethod": "client_secret_basic"
|
|
172
|
+
},
|
|
173
|
+
"refreshable": true,
|
|
174
|
+
"type": "oauth2"
|
|
175
|
+
};
|
|
176
|
+
var CredentialFields = {
|
|
177
|
+
"access_token": "accessToken",
|
|
178
|
+
"client_id": "clientId",
|
|
179
|
+
"client_secret": "clientSecret",
|
|
180
|
+
"id_token": "idToken",
|
|
181
|
+
"refresh_token": "refreshToken"
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
// src/operations.ts
|
|
185
|
+
import { newMutationBranch, newMutationRetry, newMutationUncertain, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
|
|
186
|
+
import { isIP } from "net";
|
|
187
|
+
var entityID = /^[0-9]{1,20}$/;
|
|
188
|
+
var currencyCode = /^[A-Z]{3}$/;
|
|
189
|
+
var zeroCustomer = { customerId: "", displayName: "", isActive: false };
|
|
190
|
+
var zeroInvoice = { invoiceId: "", customerId: "", lines: [], totalAmount: "", balance: "" };
|
|
191
|
+
var zeroPayment = { paymentId: "", customerId: "", totalAmount: "" };
|
|
192
|
+
function object(value) {
|
|
193
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("response is not a JSON object");
|
|
194
|
+
return value;
|
|
195
|
+
}
|
|
196
|
+
function string(value) {
|
|
197
|
+
if (value === void 0 || value === null) return "";
|
|
198
|
+
if (typeof value !== "string") throw new TypeError("provider field is not a string");
|
|
199
|
+
return value;
|
|
200
|
+
}
|
|
201
|
+
function array(value) {
|
|
202
|
+
if (value == null) return [];
|
|
203
|
+
if (!Array.isArray(value)) throw new TypeError("provider field is not a list");
|
|
204
|
+
return value;
|
|
205
|
+
}
|
|
206
|
+
function reference(value) {
|
|
207
|
+
return value == null ? "" : string(object(value).value);
|
|
208
|
+
}
|
|
209
|
+
function optional(condition, key, value) {
|
|
210
|
+
return condition ? { [key]: value } : {};
|
|
211
|
+
}
|
|
212
|
+
function parse(body) {
|
|
213
|
+
const parseWithSource = JSON.parse;
|
|
214
|
+
return object(parseWithSource(Buffer.from(body).toString("utf8"), (_key, value, context) => typeof value === "number" ? context.source ?? String(value) : value));
|
|
215
|
+
}
|
|
216
|
+
function entity(body, name) {
|
|
217
|
+
const response = parse(body);
|
|
218
|
+
if (!(name in response)) throw new TypeError(`response has no ${name}`);
|
|
219
|
+
return object(response[name]);
|
|
220
|
+
}
|
|
221
|
+
function entities(body, name) {
|
|
222
|
+
const response = parse(body);
|
|
223
|
+
const query = object(response.QueryResponse);
|
|
224
|
+
if (!(name in query)) return [];
|
|
225
|
+
return array(query[name]).map(object);
|
|
226
|
+
}
|
|
227
|
+
function validID(name, value) {
|
|
228
|
+
if (!entityID.test(value)) throw new TypeError(`${name} must be a QuickBooks Id, a decimal string such as 145`);
|
|
229
|
+
}
|
|
230
|
+
function validText(name, value, maximum, multiline = false) {
|
|
231
|
+
if ([...value].length > maximum) throw new TypeError(`${name} can be at most ${maximum} characters`);
|
|
232
|
+
if ([...value].some((char) => {
|
|
233
|
+
const code = char.codePointAt(0);
|
|
234
|
+
return (code < 32 || code === 127) && !(multiline && "\n\r ".includes(char));
|
|
235
|
+
})) throw new TypeError(`${name} must not contain control characters`);
|
|
236
|
+
}
|
|
237
|
+
function validQuery(name, value, maximum) {
|
|
238
|
+
validText(name, value, maximum);
|
|
239
|
+
if (value.includes("\\")) throw new TypeError(`${name} cannot contain a backslash`);
|
|
240
|
+
}
|
|
241
|
+
function quote(value) {
|
|
242
|
+
return `'${value.replaceAll("'", "\\'")}'`;
|
|
243
|
+
}
|
|
244
|
+
function validDate(name, value) {
|
|
245
|
+
const parts = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
|
246
|
+
const year = Number(parts?.[1]), month = Number(parts?.[2]), day = Number(parts?.[3]);
|
|
247
|
+
const boundary = /* @__PURE__ */ new Date(0);
|
|
248
|
+
boundary.setUTCFullYear(year, month, 0);
|
|
249
|
+
const lastDay = boundary.getUTCDate();
|
|
250
|
+
if (!parts || month < 1 || month > 12 || day < 1 || day > lastDay) throw new TypeError(`${name} must be a calendar date written YYYY-MM-DD, such as 2026-10-01`);
|
|
251
|
+
}
|
|
252
|
+
function validCurrency(name, value) {
|
|
253
|
+
if (value && !currencyCode.test(value)) throw new TypeError(`${name} must be a three-letter ISO 4217 code such as USD`);
|
|
254
|
+
}
|
|
255
|
+
function validEmail(name, value) {
|
|
256
|
+
const invalid = () => {
|
|
257
|
+
throw new TypeError(`${name} must be one bare email address such as jane@example.com`);
|
|
258
|
+
};
|
|
259
|
+
if (!value || Buffer.byteLength(value, "utf8") > 254 || /[ "\\'()<>,;]/.test(value)) invalid();
|
|
260
|
+
const at = value.lastIndexOf("@");
|
|
261
|
+
if (at < 1 || at === value.length - 1 || value.indexOf("@") !== at) invalid();
|
|
262
|
+
const local = value.slice(0, at), domain = value.slice(at + 1);
|
|
263
|
+
const localAtom = /^[\p{L}\p{N}\p{M}!#$%&*+\-/=?^_`{|}~]+$/u;
|
|
264
|
+
if (local.split(".").some((part) => !localAtom.test(part))) invalid();
|
|
265
|
+
if (domain.startsWith("[") && domain.endsWith("]")) {
|
|
266
|
+
const contents = domain.slice(1, -1);
|
|
267
|
+
if (!isIP(contents)) invalid();
|
|
268
|
+
} else {
|
|
269
|
+
const domainAtom = /^[\p{L}\p{N}\p{M}_-]+$/u;
|
|
270
|
+
if (domain.split(".").some((part) => !domainAtom.test(part))) invalid();
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
function metadata(wire) {
|
|
274
|
+
const raw = wire.MetaData;
|
|
275
|
+
if (raw == null) return {};
|
|
276
|
+
const meta = object(raw);
|
|
277
|
+
const result = {};
|
|
278
|
+
for (const [wireName, outputName] of [["CreateTime", "createdAt"], ["LastUpdatedTime", "updatedAt"]]) {
|
|
279
|
+
const value = string(meta[wireName]);
|
|
280
|
+
if (!value) continue;
|
|
281
|
+
try {
|
|
282
|
+
result[outputName] = parseRFC3339(value);
|
|
283
|
+
} catch {
|
|
284
|
+
throw new TypeError(`invalid MetaData.${wireName}`);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
return result;
|
|
288
|
+
}
|
|
289
|
+
function decimal(value, required = false) {
|
|
290
|
+
if (value === void 0 || value === null) {
|
|
291
|
+
if (required) throw new TypeError("missing decimal");
|
|
292
|
+
return "";
|
|
293
|
+
}
|
|
294
|
+
if (typeof value !== "number" && typeof value !== "string") throw new TypeError("invalid decimal");
|
|
295
|
+
const text = String(value).trim();
|
|
296
|
+
if (!/^-?(?:0|[1-9][0-9]{0,17})(?:\.[0-9]{1,18})?(?:[eE][+-]?[0-9]{1,2})?$/.test(text)) throw new TypeError("invalid decimal");
|
|
297
|
+
const match = /^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(text);
|
|
298
|
+
let digits = match[2] + (match[3] ?? "");
|
|
299
|
+
let point = match[2].length + Number(match[4] ?? 0);
|
|
300
|
+
if (point <= 0) {
|
|
301
|
+
digits = "0".repeat(1 - point) + digits;
|
|
302
|
+
point = 1;
|
|
303
|
+
} else if (point > digits.length) digits += "0".repeat(point - digits.length);
|
|
304
|
+
const whole = digits.slice(0, point).replace(/^0+/, "") || "0";
|
|
305
|
+
const fraction = digits.slice(point);
|
|
306
|
+
const result = `${match[1]}${whole}${fraction ? `.${fraction}` : ""}`;
|
|
307
|
+
const canonical = /[1-9]/.test(result) ? result : result.replace(/^-/, "");
|
|
308
|
+
if (!/^-?(?:0|[1-9][0-9]{0,17})(?:\.[0-9]{1,10})?$/.test(canonical)) throw new TypeError("invalid decimal");
|
|
309
|
+
return canonical;
|
|
310
|
+
}
|
|
311
|
+
function parseRFC3339(value, includeFraction = true) {
|
|
312
|
+
const parts = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:[.,](\d+))?(Z|[+-]\d{2}:\d{2})$/.exec(value);
|
|
313
|
+
if (!parts) throw new TypeError("invalid RFC 3339 timestamp");
|
|
314
|
+
const [year, month, day, hour, minute, second2] = parts.slice(1, 7).map(Number);
|
|
315
|
+
validDate("timestamp", `${parts[1]}-${parts[2]}-${parts[3]}`);
|
|
316
|
+
if (hour > 23 || minute > 59 || second2 > 59) throw new TypeError("invalid RFC 3339 timestamp");
|
|
317
|
+
const zone = parts[8];
|
|
318
|
+
const offsetHours = zone === "Z" ? 0 : Number(zone.slice(1, 3));
|
|
319
|
+
const offsetMinutes = zone === "Z" ? 0 : Number(zone.slice(4, 6));
|
|
320
|
+
if (offsetHours > 24 || offsetMinutes > 59) throw new TypeError("invalid RFC 3339 timestamp");
|
|
321
|
+
const date = /* @__PURE__ */ new Date(0);
|
|
322
|
+
date.setUTCFullYear(year, month - 1, day);
|
|
323
|
+
date.setUTCHours(hour, minute, second2, 0);
|
|
324
|
+
const sign = zone.startsWith("-") ? -1 : 1;
|
|
325
|
+
const utc = new Date(date.getTime() - sign * (offsetHours * 60 + offsetMinutes) * 6e4);
|
|
326
|
+
const seconds = utc.toISOString().slice(0, 19);
|
|
327
|
+
const fraction = includeFraction ? (parts[7] ?? "").slice(0, 9).replace(/0+$/, "") : "";
|
|
328
|
+
return `${seconds}${fraction ? `.${fraction}` : ""}Z`;
|
|
329
|
+
}
|
|
330
|
+
function omitEmptyOptionalFields(value) {
|
|
331
|
+
return Object.fromEntries(Object.entries(value).filter(([name, item]) => item !== "" && (!Array.isArray(item) || item.length > 0 || name === "lines")));
|
|
332
|
+
}
|
|
333
|
+
function decodeCustomer(wire) {
|
|
334
|
+
const id = string(wire.Id), displayName = string(wire.DisplayName);
|
|
335
|
+
validID("customer Id", id);
|
|
336
|
+
if (!displayName.trim()) throw new TypeError("customer has no DisplayName");
|
|
337
|
+
const email = wire.PrimaryEmailAddr == null ? "" : string(object(wire.PrimaryEmailAddr).Address).trim();
|
|
338
|
+
const phone = wire.PrimaryPhone == null ? "" : string(object(wire.PrimaryPhone).FreeFormNumber);
|
|
339
|
+
if (wire.Active != null && typeof wire.Active !== "boolean") throw new TypeError("invalid Active");
|
|
340
|
+
return omitEmptyOptionalFields({
|
|
341
|
+
customerId: id,
|
|
342
|
+
displayName,
|
|
343
|
+
isActive: wire.Active == null || wire.Active === true,
|
|
344
|
+
...optional(!!wire.SyncToken, "syncToken", string(wire.SyncToken)),
|
|
345
|
+
...optional(!!wire.GivenName, "givenName", string(wire.GivenName)),
|
|
346
|
+
...optional(!!wire.FamilyName, "familyName", string(wire.FamilyName)),
|
|
347
|
+
...optional(!!wire.CompanyName, "companyName", string(wire.CompanyName)),
|
|
348
|
+
...optional(!!email, "emailAddress", email),
|
|
349
|
+
...optional(!!phone, "phone", phone),
|
|
350
|
+
...optional(wire.Balance != null, "balance", decimal(wire.Balance)),
|
|
351
|
+
...optional(wire.CurrencyRef != null, "currencyCode", reference(wire.CurrencyRef)),
|
|
352
|
+
...metadata(wire)
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
function decodeInvoiceLine(wire) {
|
|
356
|
+
const detailType = string(wire.DetailType);
|
|
357
|
+
if (!detailType) throw new TypeError("line has no DetailType");
|
|
358
|
+
const detail = wire.SalesItemLineDetail == null ? null : object(wire.SalesItemLineDetail);
|
|
359
|
+
return omitEmptyOptionalFields({
|
|
360
|
+
detailType,
|
|
361
|
+
...optional(!!wire.Id, "lineId", string(wire.Id)),
|
|
362
|
+
...optional(!!wire.Description, "description", string(wire.Description)),
|
|
363
|
+
...optional(wire.Amount != null, "amount", decimal(wire.Amount)),
|
|
364
|
+
...detail ? { ...optional(detail.ItemRef != null, "itemId", reference(detail.ItemRef)), ...optional(detail.ItemRef != null && !!object(detail.ItemRef).name, "itemName", string(detail.ItemRef == null ? "" : object(detail.ItemRef).name)), ...optional(detail.Qty != null, "quantity", decimal(detail.Qty)), ...optional(detail.UnitPrice != null, "unitPrice", decimal(detail.UnitPrice)), ...optional(detail.TaxCodeRef != null, "taxCodeId", reference(detail.TaxCodeRef)), ...optional(!!detail.ServiceDate, "serviceDate", string(detail.ServiceDate)) } : {}
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
function decodeInvoiceQueryPage(body) {
|
|
368
|
+
return entities(body, "Invoice").map(decodeInvoice);
|
|
369
|
+
}
|
|
370
|
+
function decodeInvoice(wire) {
|
|
371
|
+
const id = string(wire.Id), customer = reference(wire.CustomerRef);
|
|
372
|
+
validID("invoice Id", id);
|
|
373
|
+
validID("CustomerRef", customer);
|
|
374
|
+
const total = decimal(wire.TotalAmt, true), balance = decimal(wire.Balance, true);
|
|
375
|
+
const lines = array(wire.Line).map(object).map(decodeInvoiceLine);
|
|
376
|
+
const linked = array(wire.LinkedTxn).map(object).filter((item) => item.TxnType === "Payment" && entityID.test(string(item.TxnId))).map((item) => string(item.TxnId));
|
|
377
|
+
const delivered = wire.DeliveryInfo == null ? "" : string(object(wire.DeliveryInfo).DeliveryTime);
|
|
378
|
+
if (delivered) try {
|
|
379
|
+
parseRFC3339(delivered);
|
|
380
|
+
} catch {
|
|
381
|
+
throw new TypeError("invoice has an invalid DeliveryInfo.DeliveryTime");
|
|
382
|
+
}
|
|
383
|
+
for (const key of ["TxnDate", "DueDate"]) if (wire[key]) validDate(key, string(wire[key]));
|
|
384
|
+
return omitEmptyOptionalFields({
|
|
385
|
+
invoiceId: id,
|
|
386
|
+
customerId: customer,
|
|
387
|
+
lines,
|
|
388
|
+
totalAmount: total,
|
|
389
|
+
balance,
|
|
390
|
+
...optional(!!wire.SyncToken, "syncToken", string(wire.SyncToken)),
|
|
391
|
+
...optional(!!wire.DocNumber, "docNumber", string(wire.DocNumber)),
|
|
392
|
+
...optional(wire.CustomerRef != null && !!object(wire.CustomerRef).name, "customerName", wire.CustomerRef == null ? "" : string(object(wire.CustomerRef).name)),
|
|
393
|
+
...optional(!!wire.TxnDate, "txnDate", string(wire.TxnDate)),
|
|
394
|
+
...optional(!!wire.DueDate, "dueDate", string(wire.DueDate)),
|
|
395
|
+
...optional(wire.CurrencyRef != null, "currencyCode", reference(wire.CurrencyRef)),
|
|
396
|
+
...optional(wire.ExchangeRate != null, "exchangeRate", decimal(wire.ExchangeRate)),
|
|
397
|
+
...optional(wire.TxnTaxDetail != null, "totalTax", decimal(wire.TxnTaxDetail == null ? void 0 : object(wire.TxnTaxDetail).TotalTax)),
|
|
398
|
+
...optional(!!wire.EmailStatus, "emailStatus", string(wire.EmailStatus)),
|
|
399
|
+
...optional(wire.BillEmail != null, "billEmail", wire.BillEmail == null ? "" : string(object(wire.BillEmail).Address).trim()),
|
|
400
|
+
...optional(!!delivered, "deliveredAt", delivered ? parseRFC3339(delivered) : ""),
|
|
401
|
+
...optional(wire.CustomerMemo != null, "customerMemo", wire.CustomerMemo == null ? "" : string(object(wire.CustomerMemo).value)),
|
|
402
|
+
...optional(!!wire.PrivateNote, "privateNote", string(wire.PrivateNote)),
|
|
403
|
+
...optional(linked.length > 0, "linkedPaymentIds", linked),
|
|
404
|
+
...metadata(wire)
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
function decodePayment(wire) {
|
|
408
|
+
const id = string(wire.Id), customer = reference(wire.CustomerRef);
|
|
409
|
+
validID("payment Id", id);
|
|
410
|
+
validID("CustomerRef", customer);
|
|
411
|
+
const applications = [];
|
|
412
|
+
if (wire.TxnDate) validDate("TxnDate", string(wire.TxnDate));
|
|
413
|
+
for (const line of array(wire.Line).map(object)) for (const linked of array(line.LinkedTxn).map(object)) if (linked.TxnType === "Invoice") {
|
|
414
|
+
const invoiceID = string(linked.TxnId);
|
|
415
|
+
validID("payment TxnId", invoiceID);
|
|
416
|
+
applications.push({ invoiceId: invoiceID, amount: decimal(line.Amount, true) });
|
|
417
|
+
}
|
|
418
|
+
return omitEmptyOptionalFields({ paymentId: id, customerId: customer, totalAmount: decimal(wire.TotalAmt, true), ...optional(!!wire.SyncToken, "syncToken", string(wire.SyncToken)), ...optional(!!wire.TxnDate, "txnDate", string(wire.TxnDate)), ...optional(wire.UnappliedAmt != null, "unappliedAmount", decimal(wire.UnappliedAmt)), ...optional(wire.CurrencyRef != null, "currencyCode", reference(wire.CurrencyRef)), ...optional(!!wire.PaymentRefNum, "paymentReferenceNumber", string(wire.PaymentRefNum)), ...optional(wire.DepositToAccountRef != null, "depositAccountId", reference(wire.DepositToAccountRef)), ...optional(applications.length > 0, "appliedInvoices", applications), ...optional(!!wire.PrivateNote, "privateNote", string(wire.PrivateNote)), ...metadata(wire) });
|
|
419
|
+
}
|
|
420
|
+
function queryOutcome(result, output, notFound = false) {
|
|
421
|
+
if (result.disposition === "succeeded") return void 0;
|
|
422
|
+
if (result.disposition === "retry" || result.disposition === "interrupted") return newQueryRetry(result.failure, result.retryAfterMs);
|
|
423
|
+
const branch = result.disposition === "defect" ? "defect" : result.disposition === "invalid" ? "invalidResponse" : result.disposition === "notFound" && notFound ? "notFound" : "providerRejected";
|
|
424
|
+
return newQueryBranch(branch, output, result.receipt, result.failure);
|
|
425
|
+
}
|
|
426
|
+
function mutationOutcome(result, output, nameConflict = false) {
|
|
427
|
+
if (result.disposition === "succeeded" || result.disposition === "invalid" || result.disposition === "interrupted") return void 0;
|
|
428
|
+
if (result.disposition === "retry") return newMutationRetry(result.failure, result.retryAfterMs);
|
|
429
|
+
return newMutationBranch(result.disposition === "defect" ? "defect" : result.disposition === "nameConflict" && nameConflict ? "nameConflict" : "providerRejected", output, result.receipt, result.failure);
|
|
430
|
+
}
|
|
431
|
+
function defect(client, operation, error) {
|
|
432
|
+
return client.failure("VALIDATION", operation, error instanceof Error ? error.message : "invalid input");
|
|
433
|
+
}
|
|
434
|
+
var FindCustomerOperation = class {
|
|
435
|
+
/** Bind one client. */
|
|
436
|
+
constructor(client) {
|
|
437
|
+
this.client = client;
|
|
438
|
+
}
|
|
439
|
+
client;
|
|
440
|
+
/** Return the manifest definition. */
|
|
441
|
+
definition() {
|
|
442
|
+
return FindCustomerDefinition;
|
|
443
|
+
}
|
|
444
|
+
/** Execute one bounded QuickBooks customer query. */
|
|
445
|
+
async invoke(call, input) {
|
|
446
|
+
const requested = { ...optional(!!input.emailAddress?.trim(), "emailAddress", input.emailAddress?.trim() ?? ""), ...optional(!!input.displayName?.trim(), "displayName", input.displayName?.trim() ?? "") };
|
|
447
|
+
let statement;
|
|
448
|
+
try {
|
|
449
|
+
const email = input.emailAddress?.trim() ?? "", displayName = input.displayName?.trim() ?? "";
|
|
450
|
+
if (email && displayName) throw new TypeError("give either emailAddress or displayName, not both");
|
|
451
|
+
if (email) {
|
|
452
|
+
validEmail("emailAddress", email);
|
|
453
|
+
statement = `PrimaryEmailAddr = ${quote(email)}`;
|
|
454
|
+
} else if (displayName) {
|
|
455
|
+
validQuery("displayName", displayName, 500);
|
|
456
|
+
statement = `DisplayName = ${quote(displayName)}`;
|
|
457
|
+
} else throw new TypeError("emailAddress or displayName is required");
|
|
458
|
+
if (input.includesInactive) statement += " AND Active IN (true, false)";
|
|
459
|
+
statement = `select * from Customer where ${statement} MAXRESULTS 10`;
|
|
460
|
+
} catch (error) {
|
|
461
|
+
return newQueryBranch("defect", requested, {}, defect(this.client, "findCustomer", error));
|
|
462
|
+
}
|
|
463
|
+
const result = await this.client.exchange(call, "findCustomer", { method: "GET", path: "/query", query: { query: statement } });
|
|
464
|
+
const outcome = queryOutcome(result, requested);
|
|
465
|
+
if (outcome) return outcome;
|
|
466
|
+
try {
|
|
467
|
+
const matches = entities(result.body, "Customer").map(decodeCustomer).filter((customer) => (requested.emailAddress ? customer.emailAddress?.toLowerCase() === requested.emailAddress.toLowerCase() : customer.displayName.toLowerCase() === requested.displayName?.toLowerCase()) && (input.includesInactive || customer.isActive));
|
|
468
|
+
if (matches.length > 10) throw new TypeError("response has more customers than requested");
|
|
469
|
+
if (!matches.length) return newQueryBranch("notFound", requested, result.receipt, this.client.failure("NOT_FOUND", "findCustomer", "no QuickBooks customer matches"));
|
|
470
|
+
if (matches.length > 1) return newQueryBranch("ambiguous", { ...requested, matches }, result.receipt, this.client.failure("CONFLICT", "findCustomer", "several QuickBooks customers match"));
|
|
471
|
+
result.receipt.providerObjectId = matches[0].customerId;
|
|
472
|
+
return newQueryBranch("found", { ...requested, customer: matches[0] }, result.receipt);
|
|
473
|
+
} catch (error) {
|
|
474
|
+
return newQueryBranch("invalidResponse", requested, result.receipt, this.client.failure("PROTOCOL", "findCustomer", `QuickBooks returned an invalid customer list: ${error instanceof Error ? error.message : "invalid response"}`));
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
var GetInvoiceOperation = class {
|
|
479
|
+
/** Bind one client. */
|
|
480
|
+
constructor(client) {
|
|
481
|
+
this.client = client;
|
|
482
|
+
}
|
|
483
|
+
client;
|
|
484
|
+
/** Return the manifest definition. */
|
|
485
|
+
definition() {
|
|
486
|
+
return GetInvoiceDefinition;
|
|
487
|
+
}
|
|
488
|
+
/** Validate and read one invoice. */
|
|
489
|
+
async invoke(call, input) {
|
|
490
|
+
const invoiceID = input.invoiceId.trim(), requested = { ...zeroInvoice, invoiceId: invoiceID };
|
|
491
|
+
try {
|
|
492
|
+
validID("invoiceId", invoiceID);
|
|
493
|
+
} catch (error) {
|
|
494
|
+
return newQueryBranch("defect", requested, {}, defect(this.client, "getInvoice", error));
|
|
495
|
+
}
|
|
496
|
+
const result = await this.client.exchange(call, "getInvoice", { method: "GET", path: `/invoice/${invoiceID}` }, invoiceID);
|
|
497
|
+
const outcome = queryOutcome(result, requested, true);
|
|
498
|
+
if (outcome) return outcome;
|
|
499
|
+
try {
|
|
500
|
+
const invoice = decodeInvoice(entity(result.body, "Invoice"));
|
|
501
|
+
if (invoice.invoiceId !== invoiceID) throw new TypeError("QuickBooks returned another invoice");
|
|
502
|
+
return newQueryBranch("found", invoice, result.receipt);
|
|
503
|
+
} catch (error) {
|
|
504
|
+
return newQueryBranch("invalidResponse", requested, result.receipt, this.client.failure("PROTOCOL", "getInvoice", `QuickBooks returned an invalid invoice: ${error instanceof Error ? error.message : "invalid response"}`));
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
};
|
|
508
|
+
var ListInvoicesOperation = class {
|
|
509
|
+
/** Bind one client. */
|
|
510
|
+
constructor(client) {
|
|
511
|
+
this.client = client;
|
|
512
|
+
}
|
|
513
|
+
client;
|
|
514
|
+
/** Return the manifest definition. */
|
|
515
|
+
definition() {
|
|
516
|
+
return ListInvoicesDefinition;
|
|
517
|
+
}
|
|
518
|
+
/** Build and execute the invoice page query. */
|
|
519
|
+
async invoke(call, input) {
|
|
520
|
+
const empty = { invoices: [], startPosition: 0, maxResults: 0, hasMorePages: false };
|
|
521
|
+
let statement, startPosition, maxResults;
|
|
522
|
+
try {
|
|
523
|
+
startPosition = input.startPosition || 1;
|
|
524
|
+
maxResults = input.maxResults || 25;
|
|
525
|
+
if (startPosition < 1) throw new TypeError("startPosition must be 1 or greater");
|
|
526
|
+
if (maxResults < 1 || maxResults > 100) throw new TypeError("maxResults must be between 1 and 100");
|
|
527
|
+
const conditions = [];
|
|
528
|
+
if (input.customerId?.trim()) {
|
|
529
|
+
validID("customerId", input.customerId.trim());
|
|
530
|
+
conditions.push(`CustomerRef = ${quote(input.customerId.trim())}`);
|
|
531
|
+
}
|
|
532
|
+
if (input.docNumber?.trim()) {
|
|
533
|
+
validQuery("docNumber", input.docNumber.trim(), 21);
|
|
534
|
+
conditions.push(`DocNumber = ${quote(input.docNumber.trim())}`);
|
|
535
|
+
}
|
|
536
|
+
if (input.isOpenOnly) conditions.push("Balance > '0'");
|
|
537
|
+
for (const [name, operator] of [["txnDateFrom", ">="], ["txnDateTo", "<="]]) {
|
|
538
|
+
const value = (input[name] ?? "").trim();
|
|
539
|
+
if (value) {
|
|
540
|
+
validDate(name, value);
|
|
541
|
+
conditions.push(`TxnDate ${operator} ${quote(value)}`);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
if (input.updatedSince) conditions.push(`MetaData.LastUpdatedTime >= ${quote(parseRFC3339(input.updatedSince, false))}`);
|
|
545
|
+
statement = `select * from Invoice${conditions.length ? ` where ${conditions.join(" AND ")}` : ""} ORDERBY MetaData.CreateTime STARTPOSITION ${startPosition} MAXRESULTS ${maxResults}`;
|
|
546
|
+
} catch (error) {
|
|
547
|
+
return newQueryBranch("defect", empty, {}, defect(this.client, "listInvoices", error));
|
|
548
|
+
}
|
|
549
|
+
const result = await this.client.exchange(call, "listInvoices", { method: "GET", path: "/query", query: { query: statement } });
|
|
550
|
+
const outcome = queryOutcome(result, empty);
|
|
551
|
+
if (outcome) return outcome;
|
|
552
|
+
try {
|
|
553
|
+
const invoices = entities(result.body, "Invoice").map(decodeInvoice);
|
|
554
|
+
if (invoices.length > maxResults) throw new TypeError("response has more invoices than requested");
|
|
555
|
+
const page = { invoices, startPosition, maxResults, hasMorePages: invoices.length === maxResults, ...invoices.length === maxResults ? { nextStartPosition: startPosition + maxResults } : {} };
|
|
556
|
+
return newQueryBranch("listed", page, result.receipt);
|
|
557
|
+
} catch (error) {
|
|
558
|
+
return newQueryBranch("invalidResponse", empty, result.receipt, this.client.failure("PROTOCOL", "listInvoices", `QuickBooks returned an invalid invoice page: ${error instanceof Error ? error.message : "invalid response"}`));
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
};
|
|
562
|
+
function encoded(value) {
|
|
563
|
+
const serialize = (part) => {
|
|
564
|
+
if (part && typeof part === "object" && "__quickbooksRawNumber" in part) return String(part.__quickbooksRawNumber);
|
|
565
|
+
if (Array.isArray(part)) return `[${part.map(serialize).join(",")}]`;
|
|
566
|
+
if (part && typeof part === "object") return `{${Object.entries(part).filter(([, item]) => item !== void 0).map(([key, item]) => `${JSON.stringify(key)}:${serialize(item)}`).join(",")}}`;
|
|
567
|
+
return JSON.stringify(part);
|
|
568
|
+
};
|
|
569
|
+
return Buffer.from(serialize(value), "utf8");
|
|
570
|
+
}
|
|
571
|
+
function validDecimal(name, value, fraction, integer, negative, zero) {
|
|
572
|
+
if (!/^-?(?:0|[1-9][0-9]{0,17})(?:\.[0-9]{1,10})?$/.test(value)) throw new TypeError(`${name} must be an exact decimal number such as 1800.00, without an exponent or leading zeros`);
|
|
573
|
+
const unsigned = value.replace(/^-/, ""), [whole, fractional = ""] = unsigned.split(".");
|
|
574
|
+
if (fractional.length > fraction) throw new TypeError(`${name} can have at most ${fraction} decimal places`);
|
|
575
|
+
if (whole.length > integer) throw new TypeError(`${name} can have at most ${integer} digits before the decimal point`);
|
|
576
|
+
if (!negative && value.startsWith("-") && /[1-9]/.test(value)) throw new TypeError(`${name} cannot be negative`);
|
|
577
|
+
if (!zero && !/[1-9]/.test(value)) throw new TypeError(`${name} must be greater than zero`);
|
|
578
|
+
}
|
|
579
|
+
function rawNumber(value) {
|
|
580
|
+
return { __quickbooksRawNumber: value };
|
|
581
|
+
}
|
|
582
|
+
function acceptedID(body, name) {
|
|
583
|
+
if (!body) return "";
|
|
584
|
+
try {
|
|
585
|
+
const found = parse(body)[name];
|
|
586
|
+
const id = string(object(found).Id);
|
|
587
|
+
return entityID.test(id) ? id : "";
|
|
588
|
+
} catch {
|
|
589
|
+
return "";
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
async function readAccepted(client, call, operation, name, id) {
|
|
593
|
+
if (!id) return void 0;
|
|
594
|
+
const result = await client.exchange(call, operation, { method: "GET", path: `/${name.toLowerCase()}/${id}` });
|
|
595
|
+
if (result.disposition !== "succeeded") return void 0;
|
|
596
|
+
try {
|
|
597
|
+
return entity(result.body, name);
|
|
598
|
+
} catch {
|
|
599
|
+
return void 0;
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
var CreateCustomerOperation = class {
|
|
603
|
+
/** Bind one client. */
|
|
604
|
+
constructor(client) {
|
|
605
|
+
this.client = client;
|
|
606
|
+
}
|
|
607
|
+
client;
|
|
608
|
+
/** Return the manifest definition. */
|
|
609
|
+
definition() {
|
|
610
|
+
return CreateCustomerDefinition;
|
|
611
|
+
}
|
|
612
|
+
/** Use Dex Call ID as QuickBooks requestid. */
|
|
613
|
+
idempotencyKey(callID) {
|
|
614
|
+
return callID;
|
|
615
|
+
}
|
|
616
|
+
/** Validate, create, and confirm an accepted write if necessary. */
|
|
617
|
+
async invoke(call, input) {
|
|
618
|
+
const requested = { customer: zeroCustomer, displayName: input.displayName.trim() };
|
|
619
|
+
let payload;
|
|
620
|
+
try {
|
|
621
|
+
const displayName = input.displayName.trim(), givenName = input.givenName?.trim() ?? "", familyName = input.familyName?.trim() ?? "", companyName = input.companyName?.trim() ?? "", email = input.emailAddress?.trim() ?? "", phone = input.phone?.trim() ?? "", currency = input.currencyCode?.trim() ?? "";
|
|
622
|
+
if (!displayName) throw new TypeError("displayName is required");
|
|
623
|
+
for (const [name, value, max] of [["displayName", displayName, 500], ["givenName", givenName, 100], ["familyName", familyName, 100], ["companyName", companyName, 100]]) validText(name, value, max);
|
|
624
|
+
if (displayName.includes(":")) throw new TypeError("displayName cannot contain a colon, which QuickBooks reserves for sub-customers");
|
|
625
|
+
if (email) {
|
|
626
|
+
validEmail("emailAddress", email);
|
|
627
|
+
validText("emailAddress", email, 100);
|
|
628
|
+
}
|
|
629
|
+
if (phone) validText("phone", phone, 30);
|
|
630
|
+
validCurrency("currencyCode", currency);
|
|
631
|
+
payload = { DisplayName: displayName, ...optional(!!email, "PrimaryEmailAddr", { Address: email }), ...optional(!!givenName, "GivenName", givenName), ...optional(!!familyName, "FamilyName", familyName), ...optional(!!companyName, "CompanyName", companyName), ...optional(!!phone, "PrimaryPhone", { FreeFormNumber: phone }), ...optional(!!currency, "CurrencyRef", { value: currency }) };
|
|
632
|
+
} catch (error) {
|
|
633
|
+
return newMutationBranch("defect", requested, {}, defect(this.client, "createCustomer", error));
|
|
634
|
+
}
|
|
635
|
+
const result = await this.client.exchange(call, "createCustomer", { method: "POST", path: "/customer", body: encoded(payload), mutation: true });
|
|
636
|
+
const outcome = mutationOutcome(result, requested, true);
|
|
637
|
+
if (outcome) return outcome;
|
|
638
|
+
let cause = "invalid customer";
|
|
639
|
+
try {
|
|
640
|
+
const customer = decodeCustomer(entity(result.body, "Customer"));
|
|
641
|
+
if (!customerMatches(customer, payload)) throw new TypeError("QuickBooks returned another customer");
|
|
642
|
+
result.receipt.providerObjectId = customer.customerId;
|
|
643
|
+
return newMutationBranch("created", { customer, displayName: requested.displayName }, result.receipt);
|
|
644
|
+
} catch (error) {
|
|
645
|
+
cause = error instanceof Error ? error.message : cause;
|
|
646
|
+
}
|
|
647
|
+
const id = acceptedID(result.body, "Customer");
|
|
648
|
+
const read = await readAccepted(this.client, call, "createCustomer", "Customer", id);
|
|
649
|
+
if (read) try {
|
|
650
|
+
const customer = decodeCustomer(read);
|
|
651
|
+
if (customer.customerId === id && customerMatches(customer, payload)) {
|
|
652
|
+
result.receipt.providerObjectId = id;
|
|
653
|
+
return newMutationBranch("created", { customer, displayName: requested.displayName }, result.receipt);
|
|
654
|
+
}
|
|
655
|
+
} catch {
|
|
656
|
+
}
|
|
657
|
+
return newMutationUncertain(requested, this.client.failure("PROTOCOL", "createCustomer", `QuickBooks accepted the customer but returned an unusable customer: ${cause}`), result.receipt);
|
|
658
|
+
}
|
|
659
|
+
};
|
|
660
|
+
function customerMatches(customer, payload) {
|
|
661
|
+
if (customer.displayName !== payload.DisplayName) return false;
|
|
662
|
+
for (const [requested, actual] of [["GivenName", customer.givenName], ["FamilyName", customer.familyName], ["CompanyName", customer.companyName]]) if (payload[requested] && actual !== payload[requested]) return false;
|
|
663
|
+
return !payload.PrimaryEmailAddr || (customer.emailAddress ?? "").toLowerCase() === string(object(payload.PrimaryEmailAddr).Address).toLowerCase();
|
|
664
|
+
}
|
|
665
|
+
var CreateInvoiceOperation = class {
|
|
666
|
+
/** Bind one client. */
|
|
667
|
+
constructor(client) {
|
|
668
|
+
this.client = client;
|
|
669
|
+
}
|
|
670
|
+
client;
|
|
671
|
+
/** Return the manifest definition. */
|
|
672
|
+
definition() {
|
|
673
|
+
return CreateInvoiceDefinition;
|
|
674
|
+
}
|
|
675
|
+
/** Use Dex Call ID as QuickBooks requestid. */
|
|
676
|
+
idempotencyKey(callID) {
|
|
677
|
+
return callID;
|
|
678
|
+
}
|
|
679
|
+
/** Validate, create, and read back an accepted invoice if necessary. */
|
|
680
|
+
async invoke(call, input) {
|
|
681
|
+
const requested = { invoice: zeroInvoice, ...optional(!!input.docNumber?.trim(), "docNumber", input.docNumber?.trim() ?? "") };
|
|
682
|
+
let payload;
|
|
683
|
+
try {
|
|
684
|
+
payload = buildInvoicePayload(input);
|
|
685
|
+
} catch (error) {
|
|
686
|
+
return newMutationBranch("defect", requested, {}, defect(this.client, "createInvoice", error));
|
|
687
|
+
}
|
|
688
|
+
const result = await this.client.exchange(call, "createInvoice", { method: "POST", path: "/invoice", body: encoded(payload), mutation: true });
|
|
689
|
+
const outcome = mutationOutcome(result, requested);
|
|
690
|
+
if (outcome) return outcome;
|
|
691
|
+
let cause = "invalid invoice";
|
|
692
|
+
try {
|
|
693
|
+
const invoice = decodeInvoice(entity(result.body, "Invoice"));
|
|
694
|
+
if (invoice.customerId !== input.customerId.trim()) throw new TypeError("invoice belongs to another customer");
|
|
695
|
+
result.receipt.providerObjectId = invoice.invoiceId;
|
|
696
|
+
return newMutationBranch("created", { invoice, ...optional(!!requested.docNumber, "docNumber", requested.docNumber ?? "") }, result.receipt);
|
|
697
|
+
} catch (error) {
|
|
698
|
+
cause = error instanceof Error ? error.message : cause;
|
|
699
|
+
}
|
|
700
|
+
const id = acceptedID(result.body, "Invoice"), read = await readAccepted(this.client, call, "createInvoice", "Invoice", id);
|
|
701
|
+
if (read) try {
|
|
702
|
+
const invoice = decodeInvoice(read);
|
|
703
|
+
if (invoice.invoiceId === id && invoice.customerId === input.customerId.trim() && (!requested.docNumber || invoice.docNumber === requested.docNumber)) {
|
|
704
|
+
result.receipt.providerObjectId = id;
|
|
705
|
+
return newMutationBranch("created", { invoice, ...optional(!!requested.docNumber, "docNumber", requested.docNumber ?? "") }, result.receipt);
|
|
706
|
+
}
|
|
707
|
+
} catch {
|
|
708
|
+
}
|
|
709
|
+
return newMutationUncertain(requested, this.client.failure("PROTOCOL", "createInvoice", `QuickBooks accepted the invoice but returned an unusable invoice: ${cause}`), result.receipt);
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
function buildInvoicePayload(input) {
|
|
713
|
+
const customer = input.customerId.trim(), txnDate = input.txnDate?.trim() ?? "", dueDate = input.dueDate?.trim() ?? "", docNumber = input.docNumber?.trim() ?? "", billEmail = input.billEmail?.trim() ?? "", currency = input.currencyCode?.trim() ?? "";
|
|
714
|
+
validID("customerId", customer);
|
|
715
|
+
if (txnDate) validDate("txnDate", txnDate);
|
|
716
|
+
if (dueDate) validDate("dueDate", dueDate);
|
|
717
|
+
if (txnDate && dueDate && dueDate < txnDate) throw new TypeError("dueDate cannot be before txnDate");
|
|
718
|
+
validQuery("docNumber", docNumber, 21);
|
|
719
|
+
if (billEmail) validEmail("billEmail", billEmail);
|
|
720
|
+
validCurrency("currencyCode", currency);
|
|
721
|
+
validText("customerMemo", input.customerMemo ?? "", 1e3, true);
|
|
722
|
+
validText("privateNote", input.privateNote ?? "", 4e3, true);
|
|
723
|
+
if (!input.lines || input.lines.length < 1 || input.lines.length > 100) throw new TypeError("lines must hold 1 to 100 lines");
|
|
724
|
+
return { CustomerRef: { value: customer }, Line: input.lines.map((line, index) => buildInvoiceLine(line, index)), ...optional(!!txnDate, "TxnDate", txnDate), ...optional(!!dueDate, "DueDate", dueDate), ...optional(!!docNumber, "DocNumber", docNumber), ...optional(!!billEmail, "BillEmail", { Address: billEmail }), ...optional(!!currency, "CurrencyRef", { value: currency }), ...optional(!!input.customerMemo, "CustomerMemo", { value: input.customerMemo ?? "" }), ...optional(!!input.privateNote, "PrivateNote", input.privateNote ?? "") };
|
|
725
|
+
}
|
|
726
|
+
function buildInvoiceLine(line, index) {
|
|
727
|
+
const prefix = `lines[${index}]`, itemID = line.itemId.trim(), serviceDate = line.serviceDate?.trim() ?? "", taxCode = line.taxCodeId?.trim() ?? "";
|
|
728
|
+
validID(`${prefix}.itemId`, itemID);
|
|
729
|
+
validText(`${prefix}.description`, line.description ?? "", 4e3, true);
|
|
730
|
+
if (serviceDate) validDate(`${prefix}.serviceDate`, serviceDate);
|
|
731
|
+
if (taxCode && !/^[A-Za-z0-9]{1,20}$/.test(taxCode)) throw new TypeError(`${prefix}.taxCodeId must be a QuickBooks tax code such as TAX, NON, or 3`);
|
|
732
|
+
if (line.quantity) validDecimal(`${prefix}.quantity`, line.quantity, 5, 12, false, true);
|
|
733
|
+
if (line.unitPrice) validDecimal(`${prefix}.unitPrice`, line.unitPrice, 5, 12, true, true);
|
|
734
|
+
let amount = line.amount ?? "";
|
|
735
|
+
if (amount) validDecimal(`${prefix}.amount`, amount, 2, 10, true, true);
|
|
736
|
+
else {
|
|
737
|
+
if (!line.quantity || !line.unitPrice) throw new TypeError(`${prefix} needs an amount, or both quantity and unitPrice`);
|
|
738
|
+
amount = multiplyRoundedToCents(line.quantity, line.unitPrice);
|
|
739
|
+
validDecimal(`${prefix}.amount`, amount, 2, 10, true, true);
|
|
740
|
+
}
|
|
741
|
+
return { DetailType: "SalesItemLineDetail", Amount: rawNumber(amount), ...optional(!!line.description, "Description", line.description ?? ""), SalesItemLineDetail: { ItemRef: { value: itemID }, ...optional(!!line.quantity, "Qty", rawNumber(line.quantity ?? "")), ...optional(!!line.unitPrice, "UnitPrice", rawNumber(line.unitPrice ?? "")), ...optional(!!taxCode, "TaxCodeRef", { value: taxCode }), ...optional(!!serviceDate, "ServiceDate", serviceDate) } };
|
|
742
|
+
}
|
|
743
|
+
function multiplyRoundedToCents(quantity, unitPrice) {
|
|
744
|
+
const scaled = (value) => {
|
|
745
|
+
const sign = value.startsWith("-") ? -1n : 1n;
|
|
746
|
+
const unsigned = value.replace(/^-/, "");
|
|
747
|
+
const [whole, fraction = ""] = unsigned.split(".");
|
|
748
|
+
return { digits: sign * BigInt(whole + fraction), scale: fraction.length };
|
|
749
|
+
};
|
|
750
|
+
const left = scaled(quantity), right = scaled(unitPrice);
|
|
751
|
+
const product = left.digits * right.digits;
|
|
752
|
+
const scale = left.scale + right.scale;
|
|
753
|
+
const divisor = 10n ** BigInt(Math.max(scale - 2, 0));
|
|
754
|
+
const magnitude = product < 0n ? -product : product;
|
|
755
|
+
const cents = scale > 2 ? (magnitude + divisor / 2n) / divisor : magnitude * 10n ** BigInt(2 - scale);
|
|
756
|
+
return `${product < 0n && cents !== 0n ? "-" : ""}${cents / 100n}.${String(cents % 100n).padStart(2, "0")}`;
|
|
757
|
+
}
|
|
758
|
+
var SendInvoiceOperation = class {
|
|
759
|
+
/** Bind one client. */
|
|
760
|
+
constructor(client) {
|
|
761
|
+
this.client = client;
|
|
762
|
+
}
|
|
763
|
+
client;
|
|
764
|
+
/** Return the manifest definition. */
|
|
765
|
+
definition() {
|
|
766
|
+
return SendInvoiceDefinition;
|
|
767
|
+
}
|
|
768
|
+
/** Use Dex Call ID as QuickBooks requestid. */
|
|
769
|
+
idempotencyKey(callID) {
|
|
770
|
+
return callID;
|
|
771
|
+
}
|
|
772
|
+
/** Send and confirm one invoice delivery. */
|
|
773
|
+
async invoke(call, input) {
|
|
774
|
+
const invoiceID = input.invoiceId.trim(), sendTo = input.sendTo?.trim() ?? "", requested = { ...zeroInvoice, invoiceId: invoiceID };
|
|
775
|
+
try {
|
|
776
|
+
validID("invoiceId", invoiceID);
|
|
777
|
+
if (sendTo) validEmail("sendTo", sendTo);
|
|
778
|
+
} catch (error) {
|
|
779
|
+
return newMutationBranch("defect", requested, {}, defect(this.client, "sendInvoice", error));
|
|
780
|
+
}
|
|
781
|
+
const result = await this.client.exchange(call, "sendInvoice", { method: "POST", path: `/invoice/${invoiceID}/send`, query: sendTo ? { sendTo } : {}, mutation: true }, invoiceID);
|
|
782
|
+
const outcome = mutationOutcome(result, requested);
|
|
783
|
+
if (outcome) return outcome;
|
|
784
|
+
let cause = "invalid invoice";
|
|
785
|
+
try {
|
|
786
|
+
const invoice = decodeInvoice(entity(result.body, "Invoice"));
|
|
787
|
+
verifySent(invoice, invoiceID, sendTo);
|
|
788
|
+
return newMutationBranch("sent", invoice, result.receipt);
|
|
789
|
+
} catch (error) {
|
|
790
|
+
cause = error instanceof Error ? error.message : cause;
|
|
791
|
+
}
|
|
792
|
+
const read = await readAccepted(this.client, call, "sendInvoice", "Invoice", invoiceID);
|
|
793
|
+
if (read) try {
|
|
794
|
+
const invoice = decodeInvoice(read);
|
|
795
|
+
verifySent(invoice, invoiceID, sendTo);
|
|
796
|
+
return newMutationBranch("sent", invoice, result.receipt);
|
|
797
|
+
} catch {
|
|
798
|
+
}
|
|
799
|
+
return newMutationUncertain(requested, this.client.failure("PROTOCOL", "sendInvoice", `QuickBooks accepted the delivery but returned an unusable invoice: ${cause}`), result.receipt);
|
|
800
|
+
}
|
|
801
|
+
};
|
|
802
|
+
function verifySent(invoice, invoiceID, sendTo) {
|
|
803
|
+
if (invoice.invoiceId !== invoiceID) throw new TypeError("QuickBooks returned another invoice");
|
|
804
|
+
if (invoice.emailStatus !== "EmailSent") throw new TypeError("the returned invoice is not marked EmailSent");
|
|
805
|
+
if (sendTo && invoice.billEmail?.toLowerCase() !== sendTo.toLowerCase()) throw new TypeError("the returned invoice has another billing address");
|
|
806
|
+
}
|
|
807
|
+
var RecordPaymentOperation = class {
|
|
808
|
+
/** Bind one client. */
|
|
809
|
+
constructor(client) {
|
|
810
|
+
this.client = client;
|
|
811
|
+
}
|
|
812
|
+
client;
|
|
813
|
+
/** Return the manifest definition. */
|
|
814
|
+
definition() {
|
|
815
|
+
return RecordPaymentDefinition;
|
|
816
|
+
}
|
|
817
|
+
/** Use Dex Call ID as QuickBooks requestid. */
|
|
818
|
+
idempotencyKey(callID) {
|
|
819
|
+
return callID;
|
|
820
|
+
}
|
|
821
|
+
/** Record and confirm one payment. */
|
|
822
|
+
async invoke(call, input) {
|
|
823
|
+
const requested = { ...zeroPayment, customerId: input.customerId.trim(), totalAmount: input.amount };
|
|
824
|
+
let payload;
|
|
825
|
+
try {
|
|
826
|
+
payload = buildPaymentPayload(input);
|
|
827
|
+
} catch (error) {
|
|
828
|
+
return newMutationBranch("defect", requested, {}, defect(this.client, "recordPayment", error));
|
|
829
|
+
}
|
|
830
|
+
const result = await this.client.exchange(call, "recordPayment", { method: "POST", path: "/payment", body: encoded(payload), mutation: true });
|
|
831
|
+
const outcome = mutationOutcome(result, requested);
|
|
832
|
+
if (outcome) return outcome;
|
|
833
|
+
let cause = "invalid payment";
|
|
834
|
+
try {
|
|
835
|
+
const payment = decodePayment(entity(result.body, "Payment"));
|
|
836
|
+
verifyPayment(payment, input);
|
|
837
|
+
result.receipt.providerObjectId = payment.paymentId;
|
|
838
|
+
return newMutationBranch("recorded", payment, result.receipt);
|
|
839
|
+
} catch (error) {
|
|
840
|
+
cause = error instanceof Error ? error.message : cause;
|
|
841
|
+
}
|
|
842
|
+
const id = acceptedID(result.body, "Payment"), read = await readAccepted(this.client, call, "recordPayment", "Payment", id);
|
|
843
|
+
if (read) try {
|
|
844
|
+
const payment = decodePayment(read);
|
|
845
|
+
verifyPayment(payment, input);
|
|
846
|
+
if (payment.paymentId !== id) throw new TypeError("another payment");
|
|
847
|
+
result.receipt.providerObjectId = id;
|
|
848
|
+
return newMutationBranch("recorded", payment, result.receipt);
|
|
849
|
+
} catch {
|
|
850
|
+
}
|
|
851
|
+
return newMutationUncertain(requested, this.client.failure("PROTOCOL", "recordPayment", `QuickBooks accepted the payment but returned an unusable payment: ${cause}`), result.receipt);
|
|
852
|
+
}
|
|
853
|
+
};
|
|
854
|
+
function buildPaymentPayload(input) {
|
|
855
|
+
const customer = input.customerId.trim(), invoice = input.invoiceId.trim(), txnDate = input.txnDate?.trim() ?? "", referenceNumber = input.paymentReferenceNumber?.trim() ?? "", deposit = input.depositAccountId?.trim() ?? "", method = input.paymentMethodId?.trim() ?? "", currency = input.currencyCode?.trim() ?? "";
|
|
856
|
+
validID("customerId", customer);
|
|
857
|
+
validID("invoiceId", invoice);
|
|
858
|
+
validDecimal("amount", input.amount, 2, 10, false, false);
|
|
859
|
+
if (txnDate) validDate("txnDate", txnDate);
|
|
860
|
+
validText("paymentReferenceNumber", referenceNumber, 21);
|
|
861
|
+
validText("privateNote", input.privateNote ?? "", 4e3, true);
|
|
862
|
+
if (deposit) validID("depositAccountId", deposit);
|
|
863
|
+
if (method) validID("paymentMethodId", method);
|
|
864
|
+
validCurrency("currencyCode", currency);
|
|
865
|
+
return { CustomerRef: { value: customer }, TotalAmt: rawNumber(input.amount), ...optional(!!txnDate, "TxnDate", txnDate), Line: [{ Amount: rawNumber(input.amount), LinkedTxn: [{ TxnId: invoice, TxnType: "Invoice" }] }], ...optional(!!referenceNumber, "PaymentRefNum", referenceNumber), ...optional(!!deposit, "DepositToAccountRef", { value: deposit }), ...optional(!!method, "PaymentMethodRef", { value: method }), ...optional(!!currency, "CurrencyRef", { value: currency }), ...optional(!!input.privateNote, "PrivateNote", input.privateNote ?? "") };
|
|
866
|
+
}
|
|
867
|
+
function verifyPayment(payment, input) {
|
|
868
|
+
if (payment.customerId !== input.customerId.trim() || !payment.appliedInvoices?.some((item) => item.invoiceId === input.invoiceId.trim())) throw new TypeError("the returned payment does not apply to the invoice");
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
// src/client.ts
|
|
872
|
+
var productionEndpoint = "https://quickbooks.api.intuit.com";
|
|
873
|
+
var sandboxEndpoint = "https://sandbox-quickbooks.api.intuit.com";
|
|
874
|
+
var realmPattern = /^[1-9][0-9]{0,24}$/;
|
|
875
|
+
var transactionPattern = /^[A-Za-z0-9-]{1,64}$/;
|
|
876
|
+
var minimumPollIntervalMs = 5e3;
|
|
877
|
+
var QuickBooksClient = class {
|
|
878
|
+
/** Validate immutable connection configuration without contacting Intuit. */
|
|
879
|
+
constructor(config, credentials, options = {}) {
|
|
880
|
+
this.credentials = credentials;
|
|
881
|
+
if (!credentials) throw new TypeError("QuickBooks credential provider is required");
|
|
882
|
+
this.environment = config.environment === "sandbox" ? "sandbox" : "production";
|
|
883
|
+
if (config.environment && config.environment !== "production" && config.environment !== "sandbox") throw new TypeError("QuickBooks environment is invalid");
|
|
884
|
+
this.configuredRealmID = (config.realmId ?? "").trim();
|
|
885
|
+
if (this.configuredRealmID && !realmPattern.test(this.configuredRealmID)) throw new TypeError("QuickBooks realmId must be a company ID");
|
|
886
|
+
this.maxResponseBytes = config.maxResponseBytes || 4194304;
|
|
887
|
+
if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes < 1) throw new TypeError("QuickBooks response limit must be positive");
|
|
888
|
+
this.pollIntervalMs = config.pollIntervalMs || 3e4;
|
|
889
|
+
if (!Number.isSafeInteger(this.pollIntervalMs) || this.pollIntervalMs < minimumPollIntervalMs) throw new TypeError("QuickBooks pollInterval must be at least 5s");
|
|
890
|
+
this.triggerLogger = options.logger ?? defaultTriggerLogger;
|
|
891
|
+
this.endpoint = options.localProviderURL ?? (this.environment === "sandbox" ? sandboxEndpoint : productionEndpoint);
|
|
892
|
+
if (options.localProviderURL) {
|
|
893
|
+
const target = new URL(options.localProviderURL);
|
|
894
|
+
const hostname = target.hostname.replace(/^\[|\]$/g, "").toLowerCase();
|
|
895
|
+
const isLoopback = hostname === "localhost" || isIP2(hostname) === 4 && hostname.startsWith("127.") || hostname === "::1" || isIP2(hostname) === 6 && /^::ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(hostname);
|
|
896
|
+
if (!isLoopback || target.pathname !== "/" || target.search || target.hash || target.username || target.password) throw new TypeError("QuickBooks local provider URL must be a loopback origin");
|
|
897
|
+
}
|
|
898
|
+
this.send = options.send ?? sendProviderRequest;
|
|
899
|
+
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
900
|
+
}
|
|
901
|
+
credentials;
|
|
902
|
+
endpoint;
|
|
903
|
+
/** The connection's QuickBooks environment, which selects the API host. */
|
|
904
|
+
environment;
|
|
905
|
+
/** Delay between invoiceChanged polls in milliseconds, at least 5 seconds; 30 seconds by default. */
|
|
906
|
+
pollIntervalMs;
|
|
907
|
+
/** Receives the invoiceChanged runner's and durable inboxes' records. */
|
|
908
|
+
triggerLogger;
|
|
909
|
+
configuredRealmID;
|
|
910
|
+
maxResponseBytes;
|
|
911
|
+
send;
|
|
912
|
+
now;
|
|
913
|
+
refreshDriver = new ManifestCredentialRefreshDriver({ providerName: "Intuit", auth: Authorization, credentialFields: CredentialFields });
|
|
914
|
+
/** Bind the customer lookup. */
|
|
915
|
+
findCustomer() {
|
|
916
|
+
return new FindCustomerOperation(this);
|
|
917
|
+
}
|
|
918
|
+
/** Bind customer creation. */
|
|
919
|
+
createCustomer() {
|
|
920
|
+
return new CreateCustomerOperation(this);
|
|
921
|
+
}
|
|
922
|
+
/** Bind invoice creation. */
|
|
923
|
+
createInvoice() {
|
|
924
|
+
return new CreateInvoiceOperation(this);
|
|
925
|
+
}
|
|
926
|
+
/** Bind invoice lookup. */
|
|
927
|
+
getInvoice() {
|
|
928
|
+
return new GetInvoiceOperation(this);
|
|
929
|
+
}
|
|
930
|
+
/** Bind invoice paging. */
|
|
931
|
+
listInvoices() {
|
|
932
|
+
return new ListInvoicesOperation(this);
|
|
933
|
+
}
|
|
934
|
+
/** Bind invoice delivery. */
|
|
935
|
+
sendInvoice() {
|
|
936
|
+
return new SendInvoiceOperation(this);
|
|
937
|
+
}
|
|
938
|
+
/** Bind payment recording. */
|
|
939
|
+
recordPayment() {
|
|
940
|
+
return new RecordPaymentOperation(this);
|
|
941
|
+
}
|
|
942
|
+
/** Return a secret-safe failure. */
|
|
943
|
+
failure(kind, operation, message) {
|
|
944
|
+
return { kind, provider: "quickbooks", operation, message };
|
|
945
|
+
}
|
|
946
|
+
/** Send and classify one request, preserving the original requestid after a credential refresh. */
|
|
947
|
+
async exchange(call, operation, request, objectID = "") {
|
|
948
|
+
let credentials;
|
|
949
|
+
try {
|
|
950
|
+
credentials = await resolveCredential(this.credentials, call, this.refreshDriver, call.context.cancellationSignal);
|
|
951
|
+
} catch (error) {
|
|
952
|
+
const isReauthorization = error instanceof ReauthorizationRequiredError;
|
|
953
|
+
const isMalformed = error instanceof TypeError;
|
|
954
|
+
return this.localFailure(
|
|
955
|
+
call,
|
|
956
|
+
isReauthorization ? "rejected" : isMalformed ? "defect" : "retry",
|
|
957
|
+
isReauthorization || isMalformed ? "AUTHENTICATION" : "AVAILABILITY",
|
|
958
|
+
operation,
|
|
959
|
+
isReauthorization ? "QuickBooks authorization must be renewed: connect the company again" : isMalformed ? "QuickBooks connection credentials are unavailable" : "Intuit access token refresh is temporarily unavailable",
|
|
960
|
+
objectID
|
|
961
|
+
);
|
|
962
|
+
}
|
|
963
|
+
const token = credentials.accessToken.reveal();
|
|
964
|
+
if (!isHeaderSafeCredential(token)) return this.localFailure(call, "defect", "AUTHENTICATION", operation, "QuickBooks connection credentials are unavailable", objectID);
|
|
965
|
+
let realmID;
|
|
966
|
+
try {
|
|
967
|
+
realmID = resolveRealmID(credentials, this.configuredRealmID);
|
|
968
|
+
} catch (error) {
|
|
969
|
+
return this.localFailure(call, "defect", "AUTHENTICATION", operation, error instanceof Error ? error.message : "QuickBooks company ID is invalid", objectID);
|
|
970
|
+
}
|
|
971
|
+
if (request.mutation && (!call.idempotencyKey || Buffer.byteLength(call.idempotencyKey, "utf8") > 50)) return this.localFailure(call, "defect", "LOCAL_DEFECT", operation, "QuickBooks mutation has no usable requestid", objectID);
|
|
972
|
+
const startedAt = this.now().getTime();
|
|
973
|
+
const available = Math.max(0, Math.min(3e4, (call.context.deadline?.getTime() ?? startedAt + 3e4) - startedAt));
|
|
974
|
+
const budget = { deadline: startedAt + available, minimumWriteTime: available / 10 };
|
|
975
|
+
let result = await this.sendRequest(call, operation, request, objectID, realmID, token, budget);
|
|
976
|
+
if (result.status === 401 && "resolveAfterRejection" in this.credentials) {
|
|
977
|
+
try {
|
|
978
|
+
const replacement = await resolveCredentialAfterRejection(this.credentials, call, this.refreshDriver, call.context.cancellationSignal);
|
|
979
|
+
if (isHeaderSafeCredential(replacement.accessToken.reveal()) && resolveRealmID(replacement, this.configuredRealmID) === realmID) result = await this.sendRequest(call, operation, request, objectID, realmID, replacement.accessToken.reveal(), budget);
|
|
980
|
+
} catch {
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
result.receipt.metadata = { ...result.receipt.metadata ?? {}, realmId: realmID, environment: this.environment };
|
|
984
|
+
return result;
|
|
985
|
+
}
|
|
986
|
+
localFailure(call, disposition, kind, operation, message, objectID = "") {
|
|
987
|
+
return { disposition, failure: this.failure(kind, operation, message), retryAfterMs: 0, status: 0, receipt: this.receipt(call, objectID) };
|
|
988
|
+
}
|
|
989
|
+
/** Create a receipt after a provider attempt. */
|
|
990
|
+
receipt(call, objectID) {
|
|
991
|
+
return { callId: call.id, provider: "quickbooks", observedAt: this.now().toISOString(), ...call.idempotencyKey ? { idempotencyKey: call.idempotencyKey } : {}, ...objectID ? { providerObjectId: objectID } : {} };
|
|
992
|
+
}
|
|
993
|
+
async sendRequest(call, operation, request, objectID, realmID, token, budget) {
|
|
994
|
+
const receipt = this.receipt(call, objectID);
|
|
995
|
+
const now = this.now().getTime();
|
|
996
|
+
if (request.mutation && (budget.minimumWriteTime <= 0 || budget.deadline - now < budget.minimumWriteTime)) return this.localFailure(call, "retry", "TRANSPORT", operation, "QuickBooks write was not sent because too little attempt time remains", objectID);
|
|
997
|
+
if (call.context.cancellationSignal.aborted) return this.localFailure(call, "retry", "TRANSPORT", operation, "QuickBooks attempt has no time left for a request; no request was sent", objectID);
|
|
998
|
+
const deadline = Math.min(call.context.deadline?.getTime() ?? Infinity, request.mutation ? budget.deadline : Infinity);
|
|
999
|
+
if (deadline !== Infinity && deadline - now <= 500) return this.localFailure(call, "retry", "TRANSPORT", operation, "QuickBooks attempt has no time left for a request; no request was sent", objectID);
|
|
1000
|
+
const timeoutMs = Math.min(2e4, deadline === Infinity ? 2e4 : deadline - now - 500);
|
|
1001
|
+
const query = goQueryEncode({ ...request.query ?? {}, minorversion: "75", ...request.mutation ? { requestid: call.idempotencyKey } : {} });
|
|
1002
|
+
const url = `${this.endpoint}/v3/company/${realmID}${request.path}?${query}`;
|
|
1003
|
+
const headers = { Authorization: `Bearer ${token}`, Accept: "application/json", ...request.body ? { "Content-Type": "application/json" } : request.method === "POST" ? { "Content-Type": "application/octet-stream" } : {} };
|
|
1004
|
+
let response;
|
|
1005
|
+
let observedStatus = 0;
|
|
1006
|
+
let observedHeaders = {};
|
|
1007
|
+
try {
|
|
1008
|
+
response = await this.send({ url, method: request.method, headers, ...request.body ? { body: request.body } : {}, maxResponseBytes: this.maxResponseBytes, maxErrorResponseBytes: 65536, ignoreErrorBodyReadFailure: true, addressPolicy: this.endpoint.startsWith("https://") ? "publicHTTPS" : "privateNetworkHTTP", timeoutMs, signal: call.context.cancellationSignal, onResponseChunk: (_chunk, status, responseHeaders) => {
|
|
1009
|
+
observedStatus = status;
|
|
1010
|
+
observedHeaders = responseHeaders;
|
|
1011
|
+
} });
|
|
1012
|
+
} catch (error) {
|
|
1013
|
+
if (error instanceof BodyTooLargeError) {
|
|
1014
|
+
const transaction2 = error.headers?.intuit_tid;
|
|
1015
|
+
const transactionID3 = Array.isArray(transaction2) ? transaction2[0] : transaction2;
|
|
1016
|
+
if (transactionID3 && transactionPattern.test(transactionID3)) receipt.providerRequestId = transactionID3;
|
|
1017
|
+
return { disposition: "invalid", status: error.status ?? 0, failure: this.failure("RESPONSE_TOO_LARGE", operation, "QuickBooks response exceeds the configured maxResponseBytes limit"), receipt, retryAfterMs: 0 };
|
|
1018
|
+
}
|
|
1019
|
+
const transaction = observedHeaders.intuit_tid;
|
|
1020
|
+
const transactionID2 = Array.isArray(transaction) ? transaction[0] : transaction;
|
|
1021
|
+
if (transactionID2 && transactionPattern.test(transactionID2)) receipt.providerRequestId = transactionID2;
|
|
1022
|
+
if (observedStatus >= 200 && observedStatus < 300) return { disposition: "interrupted", status: observedStatus, failure: this.failure("TRANSPORT", operation, "QuickBooks response was interrupted"), receipt, retryAfterMs: 0 };
|
|
1023
|
+
return { disposition: "retry", status: observedStatus, failure: this.failure("TRANSPORT", operation, "QuickBooks request failed before a response arrived"), receipt, retryAfterMs: 0 };
|
|
1024
|
+
}
|
|
1025
|
+
const transactionID = response.headers.intuit_tid;
|
|
1026
|
+
const reportedID = Array.isArray(transactionID) ? transactionID[0] : transactionID;
|
|
1027
|
+
if (reportedID && transactionPattern.test(reportedID)) receipt.providerRequestId = reportedID;
|
|
1028
|
+
if (response.status >= 200 && response.status < 300) {
|
|
1029
|
+
if (Buffer.from(response.body).includes(token)) return { disposition: "invalid", status: response.status, failure: this.failure("PROTOCOL", operation, "QuickBooks response reflected the connection credential"), receipt, retryAfterMs: 0 };
|
|
1030
|
+
const fault = summarizeFault(response.body);
|
|
1031
|
+
if (fault.type || fault.count) return this.classifyStatus(operation, response, receipt, fault);
|
|
1032
|
+
return { disposition: "succeeded", status: response.status, body: response.body, receipt, retryAfterMs: 0 };
|
|
1033
|
+
}
|
|
1034
|
+
return this.classifyStatus(operation, response, receipt, summarizeFault(response.body));
|
|
1035
|
+
}
|
|
1036
|
+
classifyStatus(operation, response, receipt, fault) {
|
|
1037
|
+
const status = response.status;
|
|
1038
|
+
if (fault.codes.length) receipt.metadata = { faultCode: fault.codes[0] };
|
|
1039
|
+
const suffix = `${fault.type ? fault.type : ""}${fault.codes.length ? `${fault.type ? "; " : ""}code ${fault.codes.join(", ")}` : ""}${fault.count > 1 ? `${fault.type || fault.codes.length ? "; " : ""}${fault.count} errors` : ""}`;
|
|
1040
|
+
const classified = (disposition, kind, message, retryAfterMs = 0) => ({ disposition, status, failure: this.failure(kind, operation, `${message} (HTTP ${status})${suffix ? ` [${suffix}]` : ""}`), receipt, retryAfterMs });
|
|
1041
|
+
if (status === 429) return classified("retry", "RATE_LIMIT", "QuickBooks throttled the request", parseRetryAfter(String(response.headers["retry-after"] ?? ""), this.now()) || 6e4);
|
|
1042
|
+
if (status === 501) return classified("rejected", "PROVIDER_REJECTION", "QuickBooks does not implement the request");
|
|
1043
|
+
if (status === 408 || status >= 500) return classified("retry", "AVAILABILITY", "QuickBooks is temporarily unavailable");
|
|
1044
|
+
if (status === 401) return classified("rejected", "AUTHENTICATION", "QuickBooks rejected the access token");
|
|
1045
|
+
if (status === 403) return fault.codes.includes("3100") ? classified("rejected", "AUTHORIZATION", "QuickBooks token lacks the com.intuit.quickbooks.accounting scope") : classified("rejected", "AUTHORIZATION", "QuickBooks denied access to the company or the request");
|
|
1046
|
+
if (status === 404) return classified("notFound", "NOT_FOUND", "QuickBooks found no such resource");
|
|
1047
|
+
if (status === 409) return classified("retry", "CONFLICT", "QuickBooks returned a conflict; retrying the same requestid");
|
|
1048
|
+
if (fault.codes.includes("600")) return classified("retry", "CONFLICT", "QuickBooks is still answering an earlier attempt with this requestid");
|
|
1049
|
+
if (fault.codes.includes("610")) return classified("notFound", "NOT_FOUND", "QuickBooks found no such object");
|
|
1050
|
+
if (fault.codes.includes("6240")) return classified("nameConflict", "CONFLICT", "QuickBooks already has a name list entry with that display name");
|
|
1051
|
+
if (fault.codes.includes("6140")) return classified("rejected", "CONFLICT", "QuickBooks already has a transaction with that document number");
|
|
1052
|
+
if (fault.type.toLowerCase() === "authenticationfault") return classified("rejected", "AUTHENTICATION", "QuickBooks rejected the authentication");
|
|
1053
|
+
if (fault.type.toLowerCase() === "authorizationfault") return classified("rejected", "AUTHORIZATION", "QuickBooks denied the request");
|
|
1054
|
+
if (fault.type.toLowerCase() === "systemfault") return classified("retry", "AVAILABILITY", "QuickBooks failed internally");
|
|
1055
|
+
if (status === 400) return classified("rejected", "VALIDATION", "QuickBooks rejected the request");
|
|
1056
|
+
if (status >= 200 && status < 300) return classified("rejected", "VALIDATION", "QuickBooks rejected the request");
|
|
1057
|
+
if (status >= 300 && status < 400) return classified("rejected", "PROTOCOL", "QuickBooks redirected the request");
|
|
1058
|
+
return classified("rejected", "PROVIDER_REJECTION", "QuickBooks rejected the request");
|
|
1059
|
+
}
|
|
1060
|
+
};
|
|
1061
|
+
function summarizeFault(body) {
|
|
1062
|
+
try {
|
|
1063
|
+
const parseWithSource = JSON.parse;
|
|
1064
|
+
const parsed = parseWithSource(Buffer.from(body).toString("utf8"), (_key, value, context) => typeof value === "number" ? context.source ?? String(value) : value);
|
|
1065
|
+
if (!parsed || typeof parsed !== "object" || !("Fault" in parsed) || !parsed.Fault || typeof parsed.Fault !== "object") return { type: "", codes: [], count: 0 };
|
|
1066
|
+
const fault = parsed.Fault;
|
|
1067
|
+
if (fault.type != null && typeof fault.type !== "string") return { type: "", codes: [], count: 0 };
|
|
1068
|
+
if (fault.Error != null && (!Array.isArray(fault.Error) || fault.Error.some((item) => !item || typeof item !== "object" || Array.isArray(item)))) return { type: "", codes: [], count: 0 };
|
|
1069
|
+
const errors = Array.isArray(fault.Error) ? fault.Error.slice(0, 1e3) : [];
|
|
1070
|
+
const codes = errors.flatMap((error) => {
|
|
1071
|
+
const code = error && typeof error === "object" ? error.code : void 0;
|
|
1072
|
+
const text = typeof code === "number" || typeof code === "string" ? String(code) : "";
|
|
1073
|
+
return /^[0-9]{1,10}$/.test(text) ? [text] : [];
|
|
1074
|
+
}).slice(0, 5);
|
|
1075
|
+
return { type: typeof fault.type === "string" && /^[A-Za-z]{1,64}$/.test(fault.type) ? fault.type : "", codes, count: errors.length };
|
|
1076
|
+
} catch {
|
|
1077
|
+
return { type: "", codes: [], count: 0 };
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
function resolveRealmID(credentials, configured) {
|
|
1081
|
+
const token = credentials.idToken?.reveal() ?? "";
|
|
1082
|
+
if (!token) {
|
|
1083
|
+
if (configured) return configured;
|
|
1084
|
+
throw new TypeError("QuickBooks company ID is unknown: authorize again while signed in to the company, or enter its company ID in realmId");
|
|
1085
|
+
}
|
|
1086
|
+
if (Buffer.byteLength(token, "utf8") > 16384) throw new TypeError("QuickBooks ID token is too large");
|
|
1087
|
+
const parts = token.split(".");
|
|
1088
|
+
if (parts.length !== 3) throw new TypeError("QuickBooks ID token is not a JWT");
|
|
1089
|
+
const payloadSegment = parts[1].replace(/=+$/, "");
|
|
1090
|
+
if (!/^[A-Za-z0-9_-]+$/.test(payloadSegment) || payloadSegment.length % 4 === 1) throw new TypeError("QuickBooks ID token payload is not base64url");
|
|
1091
|
+
let claims;
|
|
1092
|
+
try {
|
|
1093
|
+
const decoded = JSON.parse(Buffer.from(payloadSegment, "base64url").toString("utf8"));
|
|
1094
|
+
if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) throw new TypeError("invalid object");
|
|
1095
|
+
claims = decoded;
|
|
1096
|
+
} catch {
|
|
1097
|
+
throw new TypeError("QuickBooks ID token payload is not a JSON object");
|
|
1098
|
+
}
|
|
1099
|
+
if (claims.iss !== "https://oauth.platform.intuit.com/op/v1") throw new TypeError("QuickBooks ID token was not issued by Intuit");
|
|
1100
|
+
const audience = claims.aud;
|
|
1101
|
+
if (!credentials.clientId || !(audience === credentials.clientId || Array.isArray(audience) && audience.every((value) => typeof value === "string") && audience.includes(credentials.clientId))) throw new TypeError("QuickBooks ID token was issued to another app");
|
|
1102
|
+
const realm = claims.realmid;
|
|
1103
|
+
if (!realm) {
|
|
1104
|
+
if (configured) return configured;
|
|
1105
|
+
throw new TypeError("QuickBooks company ID is unknown: authorize again while signed in to the company, or enter its company ID in realmId");
|
|
1106
|
+
}
|
|
1107
|
+
if (typeof realm !== "string" || !realmPattern.test(realm)) throw new TypeError("QuickBooks ID token realmid is not a company ID");
|
|
1108
|
+
if (configured && configured !== realm) throw new TypeError("the realmId setting names another company than the one Intuit authorized: clear it or authorize that company");
|
|
1109
|
+
return realm;
|
|
1110
|
+
}
|
|
1111
|
+
function goQueryEncode(values) {
|
|
1112
|
+
return Object.keys(values).sort((left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right))).flatMap((key) => {
|
|
1113
|
+
const entry = values[key];
|
|
1114
|
+
return (typeof entry === "string" ? [entry] : entry).map((value) => `${goQueryEscape(key)}=${goQueryEscape(value)}`);
|
|
1115
|
+
}).join("&");
|
|
1116
|
+
}
|
|
1117
|
+
function goQueryEscape(value) {
|
|
1118
|
+
return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g, "+");
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
// src/generated/steps.ts
|
|
1122
|
+
import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
|
|
1123
|
+
function newFindCustomerStep(configuration) {
|
|
1124
|
+
const { connection, connectionName, found, notFound, ambiguous, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
|
|
1125
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
1126
|
+
return newQueryStep({ ...stepConfiguration, operation: connection.operations.findCustomer(), connection: connection.reference, branches: [
|
|
1127
|
+
goToBranch("found", found),
|
|
1128
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
1129
|
+
...ambiguous ? [goToBranch("ambiguous", ambiguous)] : [],
|
|
1130
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
1131
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
1132
|
+
...defect2 ? [goToBranch("defect", defect2)] : []
|
|
1133
|
+
] });
|
|
1134
|
+
}
|
|
1135
|
+
function newCreateCustomerStep(configuration) {
|
|
1136
|
+
const { connection, connectionName, created, nameConflict, providerRejected, uncertain, defect: defect2, ...stepConfiguration } = configuration;
|
|
1137
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
1138
|
+
return newMutationStep({ ...stepConfiguration, operation: connection.operations.createCustomer(), connection: connection.reference, branches: [
|
|
1139
|
+
goToBranch("created", created),
|
|
1140
|
+
...nameConflict ? [goToBranch("nameConflict", nameConflict)] : [],
|
|
1141
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
1142
|
+
...uncertain ? [goToBranch("uncertain", uncertain)] : [],
|
|
1143
|
+
...defect2 ? [goToBranch("defect", defect2)] : []
|
|
1144
|
+
] });
|
|
1145
|
+
}
|
|
1146
|
+
function newCreateInvoiceStep(configuration) {
|
|
1147
|
+
const { connection, connectionName, created, providerRejected, uncertain, defect: defect2, ...stepConfiguration } = configuration;
|
|
1148
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
1149
|
+
return newMutationStep({ ...stepConfiguration, operation: connection.operations.createInvoice(), connection: connection.reference, branches: [
|
|
1150
|
+
goToBranch("created", created),
|
|
1151
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
1152
|
+
...uncertain ? [goToBranch("uncertain", uncertain)] : [],
|
|
1153
|
+
...defect2 ? [goToBranch("defect", defect2)] : []
|
|
1154
|
+
] });
|
|
1155
|
+
}
|
|
1156
|
+
function newGetInvoiceStep(configuration) {
|
|
1157
|
+
const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
|
|
1158
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
1159
|
+
return newQueryStep({ ...stepConfiguration, operation: connection.operations.getInvoice(), connection: connection.reference, branches: [
|
|
1160
|
+
goToBranch("found", found),
|
|
1161
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
1162
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
1163
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
1164
|
+
...defect2 ? [goToBranch("defect", defect2)] : []
|
|
1165
|
+
] });
|
|
1166
|
+
}
|
|
1167
|
+
function newListInvoicesStep(configuration) {
|
|
1168
|
+
const { connection, connectionName, listed, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
|
|
1169
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
1170
|
+
return newQueryStep({ ...stepConfiguration, operation: connection.operations.listInvoices(), connection: connection.reference, branches: [
|
|
1171
|
+
goToBranch("listed", listed),
|
|
1172
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
1173
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
1174
|
+
...defect2 ? [goToBranch("defect", defect2)] : []
|
|
1175
|
+
] });
|
|
1176
|
+
}
|
|
1177
|
+
function newSendInvoiceStep(configuration) {
|
|
1178
|
+
const { connection, connectionName, sent, providerRejected, uncertain, defect: defect2, ...stepConfiguration } = configuration;
|
|
1179
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
1180
|
+
return newMutationStep({ ...stepConfiguration, operation: connection.operations.sendInvoice(), connection: connection.reference, branches: [
|
|
1181
|
+
goToBranch("sent", sent),
|
|
1182
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
1183
|
+
...uncertain ? [goToBranch("uncertain", uncertain)] : [],
|
|
1184
|
+
...defect2 ? [goToBranch("defect", defect2)] : []
|
|
1185
|
+
] });
|
|
1186
|
+
}
|
|
1187
|
+
function newRecordPaymentStep(configuration) {
|
|
1188
|
+
const { connection, connectionName, recorded, providerRejected, uncertain, defect: defect2, ...stepConfiguration } = configuration;
|
|
1189
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
1190
|
+
return newMutationStep({ ...stepConfiguration, operation: connection.operations.recordPayment(), connection: connection.reference, branches: [
|
|
1191
|
+
goToBranch("recorded", recorded),
|
|
1192
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
1193
|
+
...uncertain ? [goToBranch("uncertain", uncertain)] : [],
|
|
1194
|
+
...defect2 ? [goToBranch("defect", defect2)] : []
|
|
1195
|
+
] });
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
// src/project.ts
|
|
1199
|
+
function encodeCredentials(credentials) {
|
|
1200
|
+
return { client_id: credentials.clientId, client_secret: credentials.clientSecret.reveal(), access_token: credentials.accessToken.reveal(), refresh_token: credentials.refreshToken.reveal(), id_token: credentials.idToken?.reveal() ?? "" };
|
|
1201
|
+
}
|
|
1202
|
+
function newProjectConnection2(project, connectionName, options = {}) {
|
|
1203
|
+
return newProjectConnection(project, connectionName, (loadedProject, name) => {
|
|
1204
|
+
const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "quickbooks" && entry.connectionName === name);
|
|
1205
|
+
if (!selected) throw new TypeError("QuickBooks project connection is not configured");
|
|
1206
|
+
const { pollInterval, ...rest } = selected.configuration;
|
|
1207
|
+
const settings = ConfigSchema.parse({ ...rest, pollIntervalMs: pollIntervalMilliseconds(pollInterval) });
|
|
1208
|
+
const config = {
|
|
1209
|
+
...settings.environment !== void 0 ? { environment: settings.environment } : {},
|
|
1210
|
+
...settings.realmId !== void 0 ? { realmId: settings.realmId } : {},
|
|
1211
|
+
...settings.maxResponseBytes !== void 0 ? { maxResponseBytes: settings.maxResponseBytes } : {},
|
|
1212
|
+
...settings.pollIntervalMs !== void 0 ? { pollIntervalMs: settings.pollIntervalMs } : {}
|
|
1213
|
+
};
|
|
1214
|
+
return new QuickBooksClient(config, newProjectCredentialProvider(loadedProject, name, decodeCredentials, encodeCredentials, decodeSharedCredentials), options);
|
|
1215
|
+
});
|
|
1216
|
+
}
|
|
1217
|
+
function pollIntervalMilliseconds(value) {
|
|
1218
|
+
if (value === void 0 || value === null || value === "" || value === 0) return void 0;
|
|
1219
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new TypeError("QuickBooks pollInterval must be a duration in integer nanoseconds");
|
|
1220
|
+
if (value < 0) throw new TypeError("QuickBooks pollInterval cannot be negative");
|
|
1221
|
+
return Math.ceil(value / 1e6);
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
// src/trigger_definition.ts
|
|
1225
|
+
import { mustTriggerBindingDefinition } from "@superdurable/connectors-sdk";
|
|
1226
|
+
import { z } from "zod";
|
|
1227
|
+
var InvoiceChangeCreated = "created";
|
|
1228
|
+
var InvoiceChangeUpdated = "updated";
|
|
1229
|
+
var InvoiceChangedTriggerConfigurationSchema = z.strictObject({});
|
|
1230
|
+
var InvoiceChangedEventSchema = z.object({
|
|
1231
|
+
/** The QuickBooks company the invoice belongs to. */
|
|
1232
|
+
realmId: z.string(),
|
|
1233
|
+
/** The connection's QuickBooks environment, production or sandbox. */
|
|
1234
|
+
environment: z.string(),
|
|
1235
|
+
/** created or updated; see InvoiceChangeKind. */
|
|
1236
|
+
changeKind: z.enum([InvoiceChangeCreated, InvoiceChangeUpdated]),
|
|
1237
|
+
/** The invoice as QuickBooks returned it in the poll, with its syncToken and updatedAt. */
|
|
1238
|
+
invoice: InvoiceSchema
|
|
1239
|
+
});
|
|
1240
|
+
var InvoiceChangedTriggerDefinition = {
|
|
1241
|
+
trigger: { connectorId: ConnectorID, triggerName: "invoiceChanged" },
|
|
1242
|
+
description: "Receive each invoice created or changed in the connected QuickBooks company, including payments, emails, and voids that update it, read by polling invoices by MetaData.LastUpdatedTime; the first run records a baseline and delivers no existing invoices, and deleted invoices are not reported."
|
|
1243
|
+
};
|
|
1244
|
+
function defineInvoiceChangedTriggerBinding(config) {
|
|
1245
|
+
return mustTriggerBindingDefinition({ definition: InvoiceChangedTriggerDefinition, ...config });
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
// src/invoice_change_cursor.ts
|
|
1249
|
+
var second = 1000000000n;
|
|
1250
|
+
var InvoiceChangeLookbackMs = 3e4;
|
|
1251
|
+
var lookback = BigInt(InvoiceChangeLookbackMs) * 1000000n;
|
|
1252
|
+
var MaximumSeenInvoiceVersions = 1e3;
|
|
1253
|
+
var invoiceTiePageOverlap = 20;
|
|
1254
|
+
var zeroTime = -62135596800n * second;
|
|
1255
|
+
var realmIDPattern = /^[1-9][0-9]{0,24}$/;
|
|
1256
|
+
var goIntegerPattern = /^[+-]?[0-9]+$/;
|
|
1257
|
+
var rfc3339Pattern = /^(\d{4})-(\d{2})-(\d{2})T(\d{1,2}):(\d{2}):(\d{2})(?:[.,](\d+))?(Z|[+-]\d{2}:\d{2})$/;
|
|
1258
|
+
var int64Minimum = -(1n << 63n);
|
|
1259
|
+
var int64Maximum = (1n << 63n) - 1n;
|
|
1260
|
+
var InvoiceChangeCursorInvalidError = class extends Error {
|
|
1261
|
+
/** Describe the rejected token without echoing it. */
|
|
1262
|
+
constructor(message = "QuickBooks invoice cursor is not decodable") {
|
|
1263
|
+
super(message);
|
|
1264
|
+
this.name = "InvoiceChangeCursorInvalidError";
|
|
1265
|
+
}
|
|
1266
|
+
};
|
|
1267
|
+
var InvoiceWindow = class _InvoiceWindow {
|
|
1268
|
+
/** Create a window; the defaults are the "no watermark" position. */
|
|
1269
|
+
constructor(since = zeroTime, from = zeroTime, seen = /* @__PURE__ */ new Map(), offset = 0) {
|
|
1270
|
+
this.since = since;
|
|
1271
|
+
this.from = from;
|
|
1272
|
+
this.seen = seen;
|
|
1273
|
+
this.offset = offset;
|
|
1274
|
+
}
|
|
1275
|
+
since;
|
|
1276
|
+
from;
|
|
1277
|
+
seen;
|
|
1278
|
+
offset;
|
|
1279
|
+
/**
|
|
1280
|
+
* Record a page of [version key, second] and return the next window. The lower bound never moves back; the page
|
|
1281
|
+
* offset continues only while the lower bound stays put.
|
|
1282
|
+
*/
|
|
1283
|
+
advance(invoices, isFullPage) {
|
|
1284
|
+
const following = new _InvoiceWindow(this.since, this.from, new Map(this.seen));
|
|
1285
|
+
for (const [key, updatedAt] of invoices) {
|
|
1286
|
+
following.seen.set(key, updatedAt);
|
|
1287
|
+
if (updatedAt > following.since) following.since = updatedAt;
|
|
1288
|
+
}
|
|
1289
|
+
if (following.since === zeroTime) return following;
|
|
1290
|
+
const floor = following.since - lookback;
|
|
1291
|
+
if (floor > following.from) following.from = floor;
|
|
1292
|
+
following.pruneToBound();
|
|
1293
|
+
if (isFullPage && following.from === this.from) following.offset = Math.max(0, this.offset + invoices.length - invoiceTiePageOverlap);
|
|
1294
|
+
return following;
|
|
1295
|
+
}
|
|
1296
|
+
/**
|
|
1297
|
+
* Drop versions below the lower bound, then whole oldest seconds while too many remain. A single second with more
|
|
1298
|
+
* versions than the bound moves the window past it.
|
|
1299
|
+
*/
|
|
1300
|
+
pruneToBound() {
|
|
1301
|
+
const seconds = /* @__PURE__ */ new Map();
|
|
1302
|
+
for (const [key, updatedAt] of this.seen) {
|
|
1303
|
+
if (updatedAt < this.from) {
|
|
1304
|
+
this.seen.delete(key);
|
|
1305
|
+
continue;
|
|
1306
|
+
}
|
|
1307
|
+
seconds.set(updatedAt, (seconds.get(updatedAt) ?? 0) + 1);
|
|
1308
|
+
}
|
|
1309
|
+
let ordered = [...seconds.keys()].sort((left, right) => left < right ? -1 : left > right ? 1 : 0);
|
|
1310
|
+
let remaining = this.seen.size;
|
|
1311
|
+
while (remaining > MaximumSeenInvoiceVersions) {
|
|
1312
|
+
remaining -= seconds.get(ordered[0]);
|
|
1313
|
+
if (ordered.length === 1) {
|
|
1314
|
+
this.since = ordered[0] + second;
|
|
1315
|
+
this.from = this.since;
|
|
1316
|
+
this.seen = /* @__PURE__ */ new Map();
|
|
1317
|
+
return;
|
|
1318
|
+
}
|
|
1319
|
+
this.from = ordered[1];
|
|
1320
|
+
for (const [key, updatedAt] of this.seen) if (updatedAt < this.from) this.seen.delete(key);
|
|
1321
|
+
ordered = ordered.slice(1);
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
};
|
|
1325
|
+
var floorDivide = (value, divisor) => value >= 0n || value % divisor === 0n ? value / divisor : value / divisor - 1n;
|
|
1326
|
+
function formatRFC3339Seconds(nanoseconds) {
|
|
1327
|
+
return `${new Date(Number(floorDivide(nanoseconds, second)) * 1e3).toISOString().slice(0, 19)}Z`;
|
|
1328
|
+
}
|
|
1329
|
+
function parseRFC3339Nanoseconds(text) {
|
|
1330
|
+
const parts = rfc3339Pattern.exec(text);
|
|
1331
|
+
if (!parts) throw new TypeError("not an RFC 3339 time");
|
|
1332
|
+
const [year, month, day, hour, minute, secondOfMinute] = parts.slice(1, 7).map(Number);
|
|
1333
|
+
const zone = parts[8];
|
|
1334
|
+
const offsetHours = zone === "Z" ? 0 : Number(zone.slice(1, 3));
|
|
1335
|
+
const offsetMinutes = zone === "Z" ? 0 : Number(zone.slice(4, 6));
|
|
1336
|
+
if (month < 1 || month > 12 || day < 1 || hour > 23 || minute > 59 || secondOfMinute > 59 || offsetHours > 24 || offsetMinutes > 60) throw new TypeError("not an RFC 3339 time");
|
|
1337
|
+
const date = /* @__PURE__ */ new Date(0);
|
|
1338
|
+
date.setUTCFullYear(year, month - 1, day);
|
|
1339
|
+
if (date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) throw new TypeError("not an RFC 3339 time");
|
|
1340
|
+
date.setUTCHours(hour, minute, secondOfMinute, 0);
|
|
1341
|
+
const sign = zone.startsWith("-") ? -1 : 1;
|
|
1342
|
+
const utcSeconds = BigInt(date.getTime() / 1e3 - sign * (offsetHours * 3600 + offsetMinutes * 60));
|
|
1343
|
+
return utcSeconds * second + BigInt((parts[7] ?? "").slice(0, 9).padEnd(9, "0"));
|
|
1344
|
+
}
|
|
1345
|
+
var wellFormed = (text) => text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "\uFFFD");
|
|
1346
|
+
function encodeGoJSONString(text) {
|
|
1347
|
+
return JSON.stringify(wellFormed(text)).replace(/[<>&\u2028\u2029]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
1348
|
+
}
|
|
1349
|
+
var compareUTF8 = (left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right));
|
|
1350
|
+
function encodeInvoiceChangeCursor(realmId, environment, window) {
|
|
1351
|
+
const members = [`"realmId":${encodeGoJSONString(realmId)}`, `"environment":${encodeGoJSONString(environment)}`];
|
|
1352
|
+
if (window.since !== zeroTime) {
|
|
1353
|
+
members.push(`"since":${encodeGoJSONString(formatRFC3339Seconds(window.since))}`, `"from":${encodeGoJSONString(formatRFC3339Seconds(window.from))}`);
|
|
1354
|
+
}
|
|
1355
|
+
const seen = [...window.seen].map(([key, updatedAt]) => `${floorDivide(updatedAt, second)}/${key}`).sort(compareUTF8);
|
|
1356
|
+
if (seen.length) members.push(`"seen":[${seen.map(encodeGoJSONString).join(",")}]`);
|
|
1357
|
+
if (window.offset) members.push(`"offset":${window.offset}`);
|
|
1358
|
+
return { token: `{${members.join(",")}}` };
|
|
1359
|
+
}
|
|
1360
|
+
var stringFields = { realmid: "realmId", environment: "environment", since: "since", from: "from" };
|
|
1361
|
+
var goFieldKey = (name) => name.toLowerCase().replaceAll("\u017F", "s");
|
|
1362
|
+
function skipJSONValue(text, index) {
|
|
1363
|
+
let depth = 0;
|
|
1364
|
+
do {
|
|
1365
|
+
const character = text[index];
|
|
1366
|
+
if (character === '"') {
|
|
1367
|
+
for (index++; text[index] !== '"'; index++) if (text[index] === "\\") index++;
|
|
1368
|
+
index++;
|
|
1369
|
+
} else if (character === "{" || character === "[") {
|
|
1370
|
+
depth++;
|
|
1371
|
+
index++;
|
|
1372
|
+
} else if (character === "}" || character === "]") {
|
|
1373
|
+
depth--;
|
|
1374
|
+
index++;
|
|
1375
|
+
} else if (depth > 0) index++;
|
|
1376
|
+
else {
|
|
1377
|
+
while (index < text.length && !/[\s,}\]]/.test(text[index])) index++;
|
|
1378
|
+
}
|
|
1379
|
+
} while (depth > 0);
|
|
1380
|
+
return index;
|
|
1381
|
+
}
|
|
1382
|
+
function objectMembers(text) {
|
|
1383
|
+
const members = [];
|
|
1384
|
+
const skipSpace = (index2) => {
|
|
1385
|
+
while (/[ \t\n\r]/.test(text[index2] ?? "")) index2++;
|
|
1386
|
+
return index2;
|
|
1387
|
+
};
|
|
1388
|
+
let index = skipSpace(skipSpace(0) + 1);
|
|
1389
|
+
while (text[index] === '"') {
|
|
1390
|
+
const keyEnd = skipJSONValue(text, index);
|
|
1391
|
+
const valueStart = skipSpace(skipSpace(keyEnd) + 1);
|
|
1392
|
+
const valueEnd = skipJSONValue(text, valueStart);
|
|
1393
|
+
members.push([JSON.parse(text.slice(index, keyEnd)), text.slice(valueStart, valueEnd)]);
|
|
1394
|
+
index = skipSpace(valueEnd);
|
|
1395
|
+
if (text[index] === ",") index = skipSpace(index + 1);
|
|
1396
|
+
}
|
|
1397
|
+
return members;
|
|
1398
|
+
}
|
|
1399
|
+
function decodeCursorPosition(token) {
|
|
1400
|
+
let document;
|
|
1401
|
+
try {
|
|
1402
|
+
document = JSON.parse(token);
|
|
1403
|
+
} catch {
|
|
1404
|
+
throw new InvoiceChangeCursorInvalidError();
|
|
1405
|
+
}
|
|
1406
|
+
const position = { realmId: "", environment: "", since: "", from: "", seen: [], offset: 0 };
|
|
1407
|
+
if (document === null) return position;
|
|
1408
|
+
if (typeof document !== "object" || Array.isArray(document)) throw new InvoiceChangeCursorInvalidError();
|
|
1409
|
+
for (const [name, source] of objectMembers(token)) {
|
|
1410
|
+
const value = JSON.parse(source);
|
|
1411
|
+
if (value === null) continue;
|
|
1412
|
+
const folded = goFieldKey(name);
|
|
1413
|
+
const field = stringFields[folded];
|
|
1414
|
+
if (field) {
|
|
1415
|
+
if (typeof value !== "string") throw new InvoiceChangeCursorInvalidError();
|
|
1416
|
+
position[field] = wellFormed(value);
|
|
1417
|
+
} else if (folded === "seen") {
|
|
1418
|
+
if (!Array.isArray(value) || value.some((item) => item !== null && typeof item !== "string")) throw new InvoiceChangeCursorInvalidError();
|
|
1419
|
+
position.seen = value.map((item) => typeof item === "string" ? wellFormed(item) : "");
|
|
1420
|
+
} else if (folded === "offset") {
|
|
1421
|
+
if (!/^-?(0|[1-9][0-9]*)$/.test(source) || !Number.isSafeInteger(Number(source))) throw new InvoiceChangeCursorInvalidError();
|
|
1422
|
+
position.offset = Number(source);
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
return position;
|
|
1426
|
+
}
|
|
1427
|
+
function decodeInvoiceChangeCursor(token) {
|
|
1428
|
+
const position = decodeCursorPosition(token);
|
|
1429
|
+
if (!realmIDPattern.test(position.realmId)) throw new InvoiceChangeCursorInvalidError();
|
|
1430
|
+
if (position.offset < 0 || position.seen.length > MaximumSeenInvoiceVersions) throw new InvoiceChangeCursorInvalidError("QuickBooks invoice cursor is out of bounds");
|
|
1431
|
+
const window = new InvoiceWindow(zeroTime, zeroTime, /* @__PURE__ */ new Map(), position.offset);
|
|
1432
|
+
if (position.since === "" && position.from === "" && position.seen.length === 0) return { position, window };
|
|
1433
|
+
try {
|
|
1434
|
+
window.since = parseRFC3339Nanoseconds(position.since);
|
|
1435
|
+
window.from = parseRFC3339Nanoseconds(position.from);
|
|
1436
|
+
} catch {
|
|
1437
|
+
throw new InvoiceChangeCursorInvalidError("QuickBooks invoice cursor has an invalid watermark");
|
|
1438
|
+
}
|
|
1439
|
+
if (window.from > window.since) throw new InvoiceChangeCursorInvalidError("QuickBooks invoice cursor has an invalid watermark");
|
|
1440
|
+
for (const entry of position.seen) {
|
|
1441
|
+
const separator = entry.indexOf("/");
|
|
1442
|
+
const unix = separator < 0 ? "" : entry.slice(0, separator);
|
|
1443
|
+
const key = separator < 0 ? "" : entry.slice(separator + 1);
|
|
1444
|
+
const seconds = goIntegerPattern.test(unix) ? BigInt(unix) : void 0;
|
|
1445
|
+
const updatedAt = seconds !== void 0 && seconds >= int64Minimum && seconds <= int64Maximum ? seconds * second : void 0;
|
|
1446
|
+
if (updatedAt === void 0 || !key.includes(":") || updatedAt < window.from || updatedAt > window.since) throw new InvoiceChangeCursorInvalidError("QuickBooks invoice cursor has an invalid delivered version");
|
|
1447
|
+
window.seen.set(key, updatedAt);
|
|
1448
|
+
}
|
|
1449
|
+
return { position, window };
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
// src/invoice_change_fetcher.ts
|
|
1453
|
+
import { createHash } from "crypto";
|
|
1454
|
+
import { markCursorInvalid, markRateLimited, newTriggerCredentialCall, waitForPollRequest } from "@superdurable/connectors-sdk/pollingtrigger";
|
|
1455
|
+
var InvoiceChangePageSize = 100;
|
|
1456
|
+
var lookback2 = BigInt(InvoiceChangeLookbackMs) * 1000000n;
|
|
1457
|
+
var maximumSeedPages = MaximumSeenInvoiceVersions / InvoiceChangePageSize;
|
|
1458
|
+
var operationName = "invoiceChanged";
|
|
1459
|
+
var newInvoiceSyncToken = "0";
|
|
1460
|
+
function invoiceVersionKey(invoice) {
|
|
1461
|
+
return `${invoice.invoiceId}:${invoice.syncToken ?? ""}`;
|
|
1462
|
+
}
|
|
1463
|
+
function invoiceChangeEventId(realmId, environment, invoice) {
|
|
1464
|
+
const updated = invoice.updatedAt ? formatRFC3339Seconds(parseRFC3339Nanoseconds(invoice.updatedAt)) : "";
|
|
1465
|
+
const digest = createHash("sha256").update([environment, realmId, invoice.invoiceId, invoice.syncToken ?? "", updated].join("\0")).digest("hex");
|
|
1466
|
+
return `qbo-invoice-${digest.slice(0, 32)}`;
|
|
1467
|
+
}
|
|
1468
|
+
function newInvoiceChangedTriggerEvent(realmId, environment, invoice) {
|
|
1469
|
+
const changeKind = invoice.syncToken === newInvoiceSyncToken ? InvoiceChangeCreated : InvoiceChangeUpdated;
|
|
1470
|
+
return { id: invoiceChangeEventId(realmId, environment, invoice), occurredAt: new Date(invoice.updatedAt), payload: { realmId, environment, changeKind, invoice } };
|
|
1471
|
+
}
|
|
1472
|
+
var quoteQueryLiteral = (value) => `'${value.replaceAll("'", "\\'")}'`;
|
|
1473
|
+
var InvoiceChangeFetcher = class {
|
|
1474
|
+
/** Bind the fetcher to one connection's client. */
|
|
1475
|
+
constructor(client, connection) {
|
|
1476
|
+
this.client = client;
|
|
1477
|
+
this.connection = connection;
|
|
1478
|
+
if (!client || !connection) throw new TypeError("QuickBooks invoiceChanged client and connection are required");
|
|
1479
|
+
}
|
|
1480
|
+
client;
|
|
1481
|
+
connection;
|
|
1482
|
+
/**
|
|
1483
|
+
* Record every version in the 30 seconds before the newest LastUpdatedTime as the baseline, so existing invoices
|
|
1484
|
+
* are never delivered; an empty company delivers its first invoice.
|
|
1485
|
+
*/
|
|
1486
|
+
async seedCursor(context) {
|
|
1487
|
+
let realmId = "";
|
|
1488
|
+
const baseline = [];
|
|
1489
|
+
let newest;
|
|
1490
|
+
let isWindowComplete = false;
|
|
1491
|
+
for (let page = 0; page < maximumSeedPages && !isWindowComplete; page++) {
|
|
1492
|
+
const statement = `select * from Invoice ORDERBY MetaData.LastUpdatedTime DESC STARTPOSITION ${1 + page * InvoiceChangePageSize} MAXRESULTS ${InvoiceChangePageSize}`;
|
|
1493
|
+
const queried = await this.queryInvoices(context, statement, false);
|
|
1494
|
+
realmId = queried.realmId;
|
|
1495
|
+
isWindowComplete = queried.invoices.length < InvoiceChangePageSize;
|
|
1496
|
+
for (const polled of queried.invoices) {
|
|
1497
|
+
newest ??= polled.updatedAt;
|
|
1498
|
+
if (polled.updatedAt < newest - lookback2) {
|
|
1499
|
+
isWindowComplete = true;
|
|
1500
|
+
break;
|
|
1501
|
+
}
|
|
1502
|
+
baseline.push(polled);
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
const window = new InvoiceWindow();
|
|
1506
|
+
if (baseline.length && newest !== void 0) {
|
|
1507
|
+
window.since = newest;
|
|
1508
|
+
window.from = newest - lookback2;
|
|
1509
|
+
if (!isWindowComplete) window.from = baseline[baseline.length - 1].updatedAt + second;
|
|
1510
|
+
for (const polled of baseline) if (polled.updatedAt >= window.from) window.seen.set(invoiceVersionKey(polled.invoice), polled.updatedAt);
|
|
1511
|
+
if (window.from > window.since) {
|
|
1512
|
+
window.from = window.since + second;
|
|
1513
|
+
window.since = window.from;
|
|
1514
|
+
}
|
|
1515
|
+
window.pruneToBound();
|
|
1516
|
+
}
|
|
1517
|
+
return encodeInvoiceChangeCursor(realmId, this.client.environment, window);
|
|
1518
|
+
}
|
|
1519
|
+
/**
|
|
1520
|
+
* Read one page of invoices changed at or after the window's lower bound, oldest first, skipping versions already
|
|
1521
|
+
* delivered or baselined. An undecodable cursor, one for another company or environment, or a QuickBooks
|
|
1522
|
+
* validation Fault for the watermark query rejects with markCursorInvalid, so the kit records a new baseline; a
|
|
1523
|
+
* 429 rejects with markRateLimited.
|
|
1524
|
+
*/
|
|
1525
|
+
async fetchChanges(context, cursor) {
|
|
1526
|
+
let decoded;
|
|
1527
|
+
try {
|
|
1528
|
+
decoded = decodeInvoiceChangeCursor(cursor.token);
|
|
1529
|
+
} catch (error) {
|
|
1530
|
+
throw markCursorInvalid(error instanceof InvoiceChangeCursorInvalidError ? error : new InvoiceChangeCursorInvalidError());
|
|
1531
|
+
}
|
|
1532
|
+
const { position, window } = decoded;
|
|
1533
|
+
const environment = this.client.environment;
|
|
1534
|
+
if (position.environment !== environment) throw markCursorInvalid(new Error("QuickBooks invoice cursor belongs to another environment"));
|
|
1535
|
+
let statement = "select * from Invoice";
|
|
1536
|
+
if (position.from) statement += ` where MetaData.LastUpdatedTime >= ${quoteQueryLiteral(position.from)}`;
|
|
1537
|
+
statement += ` ORDERBY MetaData.LastUpdatedTime STARTPOSITION ${1 + window.offset} MAXRESULTS ${InvoiceChangePageSize}`;
|
|
1538
|
+
const { realmId, invoices } = await this.queryInvoices(context, statement, position.from !== "");
|
|
1539
|
+
if (realmId !== position.realmId) throw markCursorInvalid(new Error("QuickBooks invoice cursor belongs to another company"));
|
|
1540
|
+
const changes = [];
|
|
1541
|
+
let previous = window.from;
|
|
1542
|
+
for (const polled of invoices) {
|
|
1543
|
+
if (polled.updatedAt < previous) throw new Error("QuickBooks invoice page is not in LastUpdatedTime order");
|
|
1544
|
+
previous = polled.updatedAt;
|
|
1545
|
+
if (window.seen.has(invoiceVersionKey(polled.invoice))) continue;
|
|
1546
|
+
changes.push(newInvoiceChangedTriggerEvent(realmId, environment, polled.invoice));
|
|
1547
|
+
}
|
|
1548
|
+
const isFullPage = invoices.length === InvoiceChangePageSize;
|
|
1549
|
+
const following = window.advance(invoices.map((polled) => [invoiceVersionKey(polled.invoice), polled.updatedAt]), isFullPage);
|
|
1550
|
+
return { changes, next: encodeInvoiceChangeCursor(position.realmId, position.environment, following), hasMorePages: isFullPage };
|
|
1551
|
+
}
|
|
1552
|
+
async queryInvoices(context, statement, hasWatermark) {
|
|
1553
|
+
await waitForPollRequest(context);
|
|
1554
|
+
const call = newTriggerCredentialCall(this.connection, InvoiceChangedTriggerDefinition.trigger, context.signal);
|
|
1555
|
+
const result = await this.client.exchange(call, operationName, { method: "GET", path: "/query", query: { query: statement } });
|
|
1556
|
+
if (result.disposition !== "succeeded") {
|
|
1557
|
+
const failure = new Error(`QuickBooks invoice poll: ${result.failure?.message ?? "QuickBooks returned no response"}`);
|
|
1558
|
+
if (result.failure?.kind === "RATE_LIMIT") throw markRateLimited(failure, result.retryAfterMs);
|
|
1559
|
+
if (hasWatermark && result.status === 400 && result.failure?.kind === "VALIDATION") throw markCursorInvalid(failure);
|
|
1560
|
+
throw failure;
|
|
1561
|
+
}
|
|
1562
|
+
const realmId = String(result.receipt.metadata?.realmId ?? "");
|
|
1563
|
+
let decoded;
|
|
1564
|
+
try {
|
|
1565
|
+
decoded = decodeInvoiceQueryPage(result.body ?? new Uint8Array());
|
|
1566
|
+
} catch (error) {
|
|
1567
|
+
throw new Error(`QuickBooks invoice poll returned an invalid page: ${error instanceof Error ? error.message : "invalid invoice"}`);
|
|
1568
|
+
}
|
|
1569
|
+
if (decoded.length > InvoiceChangePageSize) throw new Error("QuickBooks invoice poll returned more invoices than requested");
|
|
1570
|
+
const invoices = decoded.map((invoice) => {
|
|
1571
|
+
if (!invoice.updatedAt) throw new Error("QuickBooks invoice poll returned an invoice without MetaData.LastUpdatedTime");
|
|
1572
|
+
const updatedAt = parseRFC3339Nanoseconds(invoice.updatedAt);
|
|
1573
|
+
const remainder = (updatedAt % second + second) % second;
|
|
1574
|
+
return { invoice, updatedAt: updatedAt - remainder };
|
|
1575
|
+
});
|
|
1576
|
+
return { realmId, invoices };
|
|
1577
|
+
}
|
|
1578
|
+
};
|
|
1579
|
+
|
|
1580
|
+
// src/trigger.ts
|
|
1581
|
+
import { newTrigger } from "@superdurable/connectors-sdk";
|
|
1582
|
+
import { newBindingPoller, newBindingTriggerSource, newMemoryCursorStore, newRunner } from "@superdurable/connectors-sdk/pollingtrigger";
|
|
1583
|
+
import { ObjectNotFoundError, decodeTriggerConfiguration, newDurableTriggerTarget } from "@superdurable/connectors-sdk/projectconfig";
|
|
1584
|
+
var triggerName = InvoiceChangedTriggerDefinition.trigger.triggerName;
|
|
1585
|
+
function quickBooksClientOf(connection) {
|
|
1586
|
+
if (!connection) throw new TypeError("QuickBooks invoiceChanged connection is required");
|
|
1587
|
+
if (!(connection.operations instanceof QuickBooksClient)) throw new TypeError("QuickBooks invoiceChanged Triggers require a QuickBooksClient connection, not a mock");
|
|
1588
|
+
return connection.operations;
|
|
1589
|
+
}
|
|
1590
|
+
var pollSchedule = (client) => ({ intervalMs: client.pollIntervalMs });
|
|
1591
|
+
function newInvoiceTriggerRunner(config) {
|
|
1592
|
+
const client = quickBooksClientOf(config.connection);
|
|
1593
|
+
if (!config.invoiceChangedRoutes?.length) throw new TypeError("QuickBooks invoiceChanged routes are required");
|
|
1594
|
+
const reference2 = config.connection.reference;
|
|
1595
|
+
const pollers = config.invoiceChangedRoutes.map((route) => {
|
|
1596
|
+
if (!route?.bindingName?.trim() || !route.target) throw new TypeError("QuickBooks invoiceChanged binding name and target are required");
|
|
1597
|
+
parseInvoiceChangedTriggerConfiguration(route.configuration ?? {});
|
|
1598
|
+
return newBindingPoller({
|
|
1599
|
+
definition: InvoiceChangedTriggerDefinition,
|
|
1600
|
+
binding: { connection: reference2, trigger: InvoiceChangedTriggerDefinition.trigger, name: route.bindingName },
|
|
1601
|
+
cursor: route.cursor ?? newMemoryCursorStore(),
|
|
1602
|
+
fetcher: new InvoiceChangeFetcher(client, reference2),
|
|
1603
|
+
target: route.target
|
|
1604
|
+
});
|
|
1605
|
+
});
|
|
1606
|
+
return newRunner({ connection: reference2, schedule: pollSchedule(client), pollers, logger: client.triggerLogger });
|
|
1607
|
+
}
|
|
1608
|
+
function parseInvoiceChangedTriggerConfiguration(configuration) {
|
|
1609
|
+
const parsed = InvoiceChangedTriggerConfigurationSchema.safeParse(configuration);
|
|
1610
|
+
if (!parsed.success) throw new TypeError(`quickbooks invoiceChanged configuration: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`);
|
|
1611
|
+
return parsed.data;
|
|
1612
|
+
}
|
|
1613
|
+
function decodeInvoiceChangedEventPayload(payloadJSON) {
|
|
1614
|
+
return InvoiceChangedEventSchema.parse(JSON.parse(payloadJSON));
|
|
1615
|
+
}
|
|
1616
|
+
function newProjectInvoiceTriggerRunner(project, connection, config) {
|
|
1617
|
+
if (!project) throw new TypeError("QuickBooks invoiceChanged Triggers require a loaded project");
|
|
1618
|
+
const client = quickBooksClientOf(connection);
|
|
1619
|
+
const invoiceChangedRoutes = (config.invoiceChangedRoutes ?? []).map((route) => {
|
|
1620
|
+
if (!route?.target) throw new TypeError("QuickBooks invoiceChanged binding target is required");
|
|
1621
|
+
const key = { connectorId: ConnectorID, connectionName: connection.reference.name, triggerName, bindingName: route.bindingName };
|
|
1622
|
+
let configuration;
|
|
1623
|
+
try {
|
|
1624
|
+
configuration = decodeTriggerConfiguration(project.configuration, key, InvoiceChangedTriggerConfigurationSchema);
|
|
1625
|
+
} catch (error) {
|
|
1626
|
+
if (!(error instanceof ObjectNotFoundError)) throw new TypeError(`quickbooks invoiceChanged binding ${JSON.stringify(route.bindingName)} configuration is invalid`, { cause: error });
|
|
1627
|
+
configuration = {};
|
|
1628
|
+
}
|
|
1629
|
+
const target = newDurableTriggerTarget(project.triggerInbox(key), key, route.target, { logger: client.triggerLogger, decodePayload: decodeInvoiceChangedEventPayload });
|
|
1630
|
+
return { bindingName: route.bindingName, configuration, target, cursor: project.pollCursorStore(key) };
|
|
1631
|
+
});
|
|
1632
|
+
return newInvoiceTriggerRunner({ connection, invoiceChangedRoutes });
|
|
1633
|
+
}
|
|
1634
|
+
function newInvoiceChangedTrigger(config) {
|
|
1635
|
+
const client = quickBooksClientOf(config.connection);
|
|
1636
|
+
const reference2 = config.connection.reference;
|
|
1637
|
+
if (config.connectionName !== reference2.name) throw new TypeError(`quickbooks connector trigger connectionName ${JSON.stringify(config.connectionName)} must equal its connection's name ${JSON.stringify(reference2.name)}`);
|
|
1638
|
+
parseInvoiceChangedTriggerConfiguration(config.configuration ?? {});
|
|
1639
|
+
const binding = { connection: reference2, trigger: InvoiceChangedTriggerDefinition.trigger, name: config.bindingName };
|
|
1640
|
+
const source = newBindingTriggerSource({
|
|
1641
|
+
definition: InvoiceChangedTriggerDefinition,
|
|
1642
|
+
binding,
|
|
1643
|
+
cursor: newMemoryCursorStore(),
|
|
1644
|
+
fetcher: new InvoiceChangeFetcher(client, reference2)
|
|
1645
|
+
}, pollSchedule(client), client.triggerLogger);
|
|
1646
|
+
return newTrigger({ definition: InvoiceChangedTriggerDefinition, binding, source, target: config.target, logger: client.triggerLogger });
|
|
1647
|
+
}
|
|
1648
|
+
export {
|
|
1649
|
+
ConfigSchema,
|
|
1650
|
+
Connection,
|
|
1651
|
+
ConnectorID,
|
|
1652
|
+
CreateCustomerBranch,
|
|
1653
|
+
CreateCustomerBranchCreated,
|
|
1654
|
+
CreateCustomerBranchDefect,
|
|
1655
|
+
CreateCustomerBranchNameConflict,
|
|
1656
|
+
CreateCustomerBranchProviderRejected,
|
|
1657
|
+
CreateCustomerBranchUncertain,
|
|
1658
|
+
CreateCustomerDefinition,
|
|
1659
|
+
CreateCustomerInputSchema,
|
|
1660
|
+
CreateCustomerMetadata,
|
|
1661
|
+
CreateCustomerOutputSchema,
|
|
1662
|
+
CreateInvoiceBranch,
|
|
1663
|
+
CreateInvoiceBranchCreated,
|
|
1664
|
+
CreateInvoiceBranchDefect,
|
|
1665
|
+
CreateInvoiceBranchProviderRejected,
|
|
1666
|
+
CreateInvoiceBranchUncertain,
|
|
1667
|
+
CreateInvoiceDefinition,
|
|
1668
|
+
CreateInvoiceInputSchema,
|
|
1669
|
+
CreateInvoiceMetadata,
|
|
1670
|
+
CreateInvoiceOutputSchema,
|
|
1671
|
+
CustomerSchema,
|
|
1672
|
+
FindCustomerBranch,
|
|
1673
|
+
FindCustomerBranchAmbiguous,
|
|
1674
|
+
FindCustomerBranchDefect,
|
|
1675
|
+
FindCustomerBranchFound,
|
|
1676
|
+
FindCustomerBranchInvalidResponse,
|
|
1677
|
+
FindCustomerBranchNotFound,
|
|
1678
|
+
FindCustomerBranchProviderRejected,
|
|
1679
|
+
FindCustomerDefinition,
|
|
1680
|
+
FindCustomerInputSchema,
|
|
1681
|
+
FindCustomerMetadata,
|
|
1682
|
+
FindCustomerOutputSchema,
|
|
1683
|
+
GetInvoiceBranch,
|
|
1684
|
+
GetInvoiceBranchDefect,
|
|
1685
|
+
GetInvoiceBranchFound,
|
|
1686
|
+
GetInvoiceBranchInvalidResponse,
|
|
1687
|
+
GetInvoiceBranchNotFound,
|
|
1688
|
+
GetInvoiceBranchProviderRejected,
|
|
1689
|
+
GetInvoiceDefinition,
|
|
1690
|
+
GetInvoiceInputSchema,
|
|
1691
|
+
GetInvoiceMetadata,
|
|
1692
|
+
InvoiceChangeCreated,
|
|
1693
|
+
InvoiceChangeCursorInvalidError,
|
|
1694
|
+
InvoiceChangeFetcher,
|
|
1695
|
+
InvoiceChangeLookbackMs,
|
|
1696
|
+
InvoiceChangePageSize,
|
|
1697
|
+
InvoiceChangeUpdated,
|
|
1698
|
+
InvoiceChangedEventSchema,
|
|
1699
|
+
InvoiceChangedTriggerConfigurationSchema,
|
|
1700
|
+
InvoiceChangedTriggerDefinition,
|
|
1701
|
+
InvoiceLineInputSchema,
|
|
1702
|
+
InvoiceLineSchema,
|
|
1703
|
+
InvoicePageSchema,
|
|
1704
|
+
InvoiceSchema,
|
|
1705
|
+
ListInvoicesBranch,
|
|
1706
|
+
ListInvoicesBranchDefect,
|
|
1707
|
+
ListInvoicesBranchInvalidResponse,
|
|
1708
|
+
ListInvoicesBranchListed,
|
|
1709
|
+
ListInvoicesBranchProviderRejected,
|
|
1710
|
+
ListInvoicesDefinition,
|
|
1711
|
+
ListInvoicesInputSchema,
|
|
1712
|
+
ListInvoicesMetadata,
|
|
1713
|
+
MaximumSeenInvoiceVersions,
|
|
1714
|
+
PaymentApplicationSchema,
|
|
1715
|
+
PaymentSchema,
|
|
1716
|
+
ProviderID,
|
|
1717
|
+
QuickBooksClient,
|
|
1718
|
+
RecordPaymentBranch,
|
|
1719
|
+
RecordPaymentBranchDefect,
|
|
1720
|
+
RecordPaymentBranchProviderRejected,
|
|
1721
|
+
RecordPaymentBranchRecorded,
|
|
1722
|
+
RecordPaymentBranchUncertain,
|
|
1723
|
+
RecordPaymentDefinition,
|
|
1724
|
+
RecordPaymentInputSchema,
|
|
1725
|
+
RecordPaymentMetadata,
|
|
1726
|
+
SendInvoiceBranch,
|
|
1727
|
+
SendInvoiceBranchDefect,
|
|
1728
|
+
SendInvoiceBranchProviderRejected,
|
|
1729
|
+
SendInvoiceBranchSent,
|
|
1730
|
+
SendInvoiceBranchUncertain,
|
|
1731
|
+
SendInvoiceDefinition,
|
|
1732
|
+
SendInvoiceInputSchema,
|
|
1733
|
+
SendInvoiceMetadata,
|
|
1734
|
+
decodeCredentials,
|
|
1735
|
+
decodeInvoiceChangedEventPayload,
|
|
1736
|
+
decodeSharedCredentials,
|
|
1737
|
+
defineInvoiceChangedTriggerBinding,
|
|
1738
|
+
invoiceChangeEventId,
|
|
1739
|
+
invoiceVersionKey,
|
|
1740
|
+
newConnection,
|
|
1741
|
+
newConnectionWithOperations,
|
|
1742
|
+
newCreateCustomerStep,
|
|
1743
|
+
newCreateInvoiceStep,
|
|
1744
|
+
newFindCustomerStep,
|
|
1745
|
+
newGetInvoiceStep,
|
|
1746
|
+
newInvoiceChangedTrigger,
|
|
1747
|
+
newInvoiceTriggerRunner,
|
|
1748
|
+
newListInvoicesStep,
|
|
1749
|
+
newProjectConnection2 as newProjectConnection,
|
|
1750
|
+
newProjectCredentialProvider,
|
|
1751
|
+
newProjectInvoiceTriggerRunner,
|
|
1752
|
+
newRecordPaymentStep,
|
|
1753
|
+
newSendInvoiceStep,
|
|
1754
|
+
parseInvoiceChangedTriggerConfiguration
|
|
1755
|
+
};
|