@superdurable/connector-intuit-quickbooks 0.1.0 → 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/dist/index.js CHANGED
@@ -79,13 +79,13 @@ import {
79
79
  newConnectionWithOperations,
80
80
  newProjectConnection,
81
81
  newProjectCredentialProvider
82
- } from "./chunk-4GHHKYDN.js";
82
+ } from "./chunk-MBZ23PGI.js";
83
83
 
84
84
  // src/client.ts
85
85
  import { BodyTooLargeError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest } from "@superdurable/connectors-sdk/providerhttp";
86
86
  import { isIP as isIP2 } from "net";
87
87
  import { ManifestCredentialRefreshDriver } from "@superdurable/connectors-sdk/oauthtoken";
88
- import { ReauthorizationRequiredError, resolveCredential, resolveCredentialAfterRejection } from "@superdurable/connectors-sdk";
88
+ import { ReauthorizationRequiredError, defaultTriggerLogger, resolveCredential, resolveCredentialAfterRejection } from "@superdurable/connectors-sdk";
89
89
 
90
90
  // src/generated/refresh.ts
91
91
  var Authorization = {
@@ -160,7 +160,8 @@ var Authorization = {
160
160
  "invalid_client",
161
161
  "unauthorized_client",
162
162
  "unsupported_grant_type"
163
- ]
163
+ ],
164
+ "tokenExchangeTimeout": "8s"
164
165
  },
165
166
  "scopes": [
166
167
  "com.intuit.quickbooks.accounting",
@@ -310,16 +311,16 @@ function decimal(value, required = false) {
310
311
  function parseRFC3339(value, includeFraction = true) {
311
312
  const parts = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:[.,](\d+))?(Z|[+-]\d{2}:\d{2})$/.exec(value);
312
313
  if (!parts) throw new TypeError("invalid RFC 3339 timestamp");
313
- const [year, month, day, hour, minute, second] = parts.slice(1, 7).map(Number);
314
+ const [year, month, day, hour, minute, second2] = parts.slice(1, 7).map(Number);
314
315
  validDate("timestamp", `${parts[1]}-${parts[2]}-${parts[3]}`);
315
- if (hour > 23 || minute > 59 || second > 59) throw new TypeError("invalid RFC 3339 timestamp");
316
+ if (hour > 23 || minute > 59 || second2 > 59) throw new TypeError("invalid RFC 3339 timestamp");
316
317
  const zone = parts[8];
317
318
  const offsetHours = zone === "Z" ? 0 : Number(zone.slice(1, 3));
318
319
  const offsetMinutes = zone === "Z" ? 0 : Number(zone.slice(4, 6));
319
320
  if (offsetHours > 24 || offsetMinutes > 59) throw new TypeError("invalid RFC 3339 timestamp");
320
321
  const date = /* @__PURE__ */ new Date(0);
321
322
  date.setUTCFullYear(year, month - 1, day);
322
- date.setUTCHours(hour, minute, second, 0);
323
+ date.setUTCHours(hour, minute, second2, 0);
323
324
  const sign = zone.startsWith("-") ? -1 : 1;
324
325
  const utc = new Date(date.getTime() - sign * (offsetHours * 60 + offsetMinutes) * 6e4);
325
326
  const seconds = utc.toISOString().slice(0, 19);
@@ -363,6 +364,9 @@ function decodeInvoiceLine(wire) {
363
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)) } : {}
364
365
  });
365
366
  }
367
+ function decodeInvoiceQueryPage(body) {
368
+ return entities(body, "Invoice").map(decodeInvoice);
369
+ }
366
370
  function decodeInvoice(wire) {
367
371
  const id = string(wire.Id), customer = reference(wire.CustomerRef);
368
372
  validID("invoice Id", id);
@@ -869,6 +873,7 @@ var productionEndpoint = "https://quickbooks.api.intuit.com";
869
873
  var sandboxEndpoint = "https://sandbox-quickbooks.api.intuit.com";
870
874
  var realmPattern = /^[1-9][0-9]{0,24}$/;
871
875
  var transactionPattern = /^[A-Za-z0-9-]{1,64}$/;
876
+ var minimumPollIntervalMs = 5e3;
872
877
  var QuickBooksClient = class {
873
878
  /** Validate immutable connection configuration without contacting Intuit. */
874
879
  constructor(config, credentials, options = {}) {
@@ -880,6 +885,9 @@ var QuickBooksClient = class {
880
885
  if (this.configuredRealmID && !realmPattern.test(this.configuredRealmID)) throw new TypeError("QuickBooks realmId must be a company ID");
881
886
  this.maxResponseBytes = config.maxResponseBytes || 4194304;
882
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;
883
891
  this.endpoint = options.localProviderURL ?? (this.environment === "sandbox" ? sandboxEndpoint : productionEndpoint);
884
892
  if (options.localProviderURL) {
885
893
  const target = new URL(options.localProviderURL);
@@ -892,7 +900,12 @@ var QuickBooksClient = class {
892
900
  }
893
901
  credentials;
894
902
  endpoint;
903
+ /** The connection's QuickBooks environment, which selects the API host. */
895
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;
896
909
  configuredRealmID;
897
910
  maxResponseBytes;
898
911
  send;
@@ -1190,15 +1203,448 @@ function newProjectConnection2(project, connectionName, options = {}) {
1190
1203
  return newProjectConnection(project, connectionName, (loadedProject, name) => {
1191
1204
  const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "quickbooks" && entry.connectionName === name);
1192
1205
  if (!selected) throw new TypeError("QuickBooks project connection is not configured");
1193
- const settings = ConfigSchema.parse(selected.configuration);
1206
+ const { pollInterval, ...rest } = selected.configuration;
1207
+ const settings = ConfigSchema.parse({ ...rest, pollIntervalMs: pollIntervalMilliseconds(pollInterval) });
1194
1208
  const config = {
1195
1209
  ...settings.environment !== void 0 ? { environment: settings.environment } : {},
1196
1210
  ...settings.realmId !== void 0 ? { realmId: settings.realmId } : {},
1197
- ...settings.maxResponseBytes !== void 0 ? { maxResponseBytes: settings.maxResponseBytes } : {}
1211
+ ...settings.maxResponseBytes !== void 0 ? { maxResponseBytes: settings.maxResponseBytes } : {},
1212
+ ...settings.pollIntervalMs !== void 0 ? { pollIntervalMs: settings.pollIntervalMs } : {}
1198
1213
  };
1199
1214
  return new QuickBooksClient(config, newProjectCredentialProvider(loadedProject, name, decodeCredentials, encodeCredentials, decodeSharedCredentials), options);
1200
1215
  });
1201
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
+ }
1202
1648
  export {
1203
1649
  ConfigSchema,
1204
1650
  Connection,
@@ -1243,6 +1689,15 @@ export {
1243
1689
  GetInvoiceDefinition,
1244
1690
  GetInvoiceInputSchema,
1245
1691
  GetInvoiceMetadata,
1692
+ InvoiceChangeCreated,
1693
+ InvoiceChangeCursorInvalidError,
1694
+ InvoiceChangeFetcher,
1695
+ InvoiceChangeLookbackMs,
1696
+ InvoiceChangePageSize,
1697
+ InvoiceChangeUpdated,
1698
+ InvoiceChangedEventSchema,
1699
+ InvoiceChangedTriggerConfigurationSchema,
1700
+ InvoiceChangedTriggerDefinition,
1246
1701
  InvoiceLineInputSchema,
1247
1702
  InvoiceLineSchema,
1248
1703
  InvoicePageSchema,
@@ -1255,6 +1710,7 @@ export {
1255
1710
  ListInvoicesDefinition,
1256
1711
  ListInvoicesInputSchema,
1257
1712
  ListInvoicesMetadata,
1713
+ MaximumSeenInvoiceVersions,
1258
1714
  PaymentApplicationSchema,
1259
1715
  PaymentSchema,
1260
1716
  ProviderID,
@@ -1276,16 +1732,24 @@ export {
1276
1732
  SendInvoiceInputSchema,
1277
1733
  SendInvoiceMetadata,
1278
1734
  decodeCredentials,
1735
+ decodeInvoiceChangedEventPayload,
1279
1736
  decodeSharedCredentials,
1737
+ defineInvoiceChangedTriggerBinding,
1738
+ invoiceChangeEventId,
1739
+ invoiceVersionKey,
1280
1740
  newConnection,
1281
1741
  newConnectionWithOperations,
1282
1742
  newCreateCustomerStep,
1283
1743
  newCreateInvoiceStep,
1284
1744
  newFindCustomerStep,
1285
1745
  newGetInvoiceStep,
1746
+ newInvoiceChangedTrigger,
1747
+ newInvoiceTriggerRunner,
1286
1748
  newListInvoicesStep,
1287
1749
  newProjectConnection2 as newProjectConnection,
1288
1750
  newProjectCredentialProvider,
1751
+ newProjectInvoiceTriggerRunner,
1289
1752
  newRecordPaymentStep,
1290
- newSendInvoiceStep
1753
+ newSendInvoiceStep,
1754
+ parseInvoiceChangedTriggerConfiguration
1291
1755
  };
package/dist/mock.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { MockQuery, MockMutation, Case } from '@superdurable/connectors-sdk/connectormock';
2
2
  import { Failure } from '@superdurable/connectors-sdk';
3
- import { O as Operations, h as Connection, F as FindCustomerInput, a as FindCustomerOutput, C as CreateCustomerInput, b as CreateCustomerOutput, c as CreateInvoiceInput, d as CreateInvoiceOutput, G as GetInvoiceInput, I as Invoice, L as ListInvoicesInput, e as InvoicePage, S as SendInvoiceInput, R as RecordPaymentInput, P as Payment, o as Customer, t as InvoiceLine, u as InvoiceLineInput, A as PaymentApplication } from './connection-DfEHGjAp.js';
3
+ import { O as Operations, h as Connection, F as FindCustomerInput, a as FindCustomerOutput, C as CreateCustomerInput, b as CreateCustomerOutput, c as CreateInvoiceInput, d as CreateInvoiceOutput, G as GetInvoiceInput, I as Invoice, L as ListInvoicesInput, e as InvoicePage, S as SendInvoiceInput, R as RecordPaymentInput, P as Payment, o as Customer, t as InvoiceLine, u as InvoiceLineInput, A as PaymentApplication } from './connection-yvzYeBut.js';
4
4
  import '@superdurable/connectors-sdk/projectconfig';
5
5
  import 'zod';
6
6
 
package/dist/mock.js CHANGED
@@ -26,7 +26,7 @@ import {
26
26
  SendInvoiceDefinition,
27
27
  SendInvoiceInputSchema,
28
28
  newConnectionWithOperations
29
- } from "./chunk-4GHHKYDN.js";
29
+ } from "./chunk-MBZ23PGI.js";
30
30
 
31
31
  // src/generated/mock.ts
32
32
  import { branchCase, retryCase, uncertainCase, newMutation, newQuery } from "@superdurable/connectors-sdk/connectormock";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@superdurable/connector-intuit-quickbooks",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "QuickBooks Online customer, invoice, and payment operations for Dex",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,7 +25,8 @@
25
25
  "./mock": {
26
26
  "types": "./dist/mock.d.ts",
27
27
  "import": "./dist/mock.js"
28
- }
28
+ },
29
+ "./dex-connector.json": "./dex-connector.json"
29
30
  },
30
31
  "files": [
31
32
  "dist",
@@ -41,11 +42,12 @@
41
42
  "test:integration": "npm run build && vitest run test/integration/*.integration.test.ts",
42
43
  "check": "npm test && npm run typecheck && npm run lint",
43
44
  "example:invoice": "npm run build && tsx examples/get-invoice/main.ts",
44
- "example:invoice:start": "npm run build && tsx examples/get-invoice/start.ts"
45
+ "example:invoice:start": "npm run build && tsx examples/get-invoice/start.ts",
46
+ "example:invoice-changed": "npm run build && tsx examples/invoice-changed/main.ts"
45
47
  },
46
48
  "dependencies": {
47
- "@superdurable/connectors-sdk": "0.7.0",
48
- "@superdurable/dex": ">=1.28.0",
49
+ "@superdurable/connectors-sdk": "0.12.0",
50
+ "@superdurable/dex": ">=1.45.4",
49
51
  "zod": "^4.1.0"
50
52
  },
51
53
  "devDependencies": {