@superdurable/connector-airtable 0.1.2 → 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
@@ -46,10 +46,11 @@ import {
46
46
  UpsertRecordsInputSchema,
47
47
  UpsertRecordsMetadata,
48
48
  UpsertedRecordsSchema,
49
+ decodeCredentials,
49
50
  newConnection,
50
51
  newConnectionWithOperations,
51
52
  newProjectConnection
52
- } from "./chunk-T4RPDDJS.js";
53
+ } from "./chunk-RBINH2QY.js";
53
54
 
54
55
  // src/generated/steps.ts
55
56
  import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
@@ -415,7 +416,15 @@ var defaultEndpoint = "https://api.airtable.com";
415
416
  var defaultMaxResponseBytes = 4194304;
416
417
  var requestTimeoutMs = 25e3;
417
418
  var rateLimitCooldownMs = 3e4;
419
+ var defaultPollIntervalMs = 3e4;
420
+ var defaultPollPageSize = 100;
418
421
  var AirtableClient = class {
422
+ /** Delay between recordChanged polls of one binding, in milliseconds; at least 1000, 30000 by default. */
423
+ pollIntervalMs;
424
+ /** Records one recordChanged poll request reads, 1 to 100, 100 by default. */
425
+ pollPageSize;
426
+ /** The recordChanged Trigger logger from AirtableClientOptions, or undefined for the SDK default. */
427
+ triggerLogger;
419
428
  endpoint;
420
429
  maxResponseBytes;
421
430
  credentials;
@@ -428,6 +437,11 @@ var AirtableClient = class {
428
437
  this.endpoint = validateBaseURL(config.endpoint || defaultEndpoint);
429
438
  this.maxResponseBytes = config.maxResponseBytes || defaultMaxResponseBytes;
430
439
  if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0) throw new TypeError("Airtable maxResponseBytes must be positive");
440
+ this.pollIntervalMs = config.pollIntervalMs || defaultPollIntervalMs;
441
+ if (!Number.isFinite(this.pollIntervalMs) || this.pollIntervalMs < 1e3) throw new TypeError("Airtable pollInterval must be at least one second");
442
+ this.pollPageSize = config.pollPageSize || defaultPollPageSize;
443
+ if (!Number.isSafeInteger(this.pollPageSize) || this.pollPageSize < 1 || this.pollPageSize > 100) throw new TypeError("Airtable pollPageSize must be from 1 to 100");
444
+ this.triggerLogger = options.logger;
431
445
  this.credentials = credentials;
432
446
  this.send = options.send ?? sendProviderRequest;
433
447
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
@@ -560,11 +574,22 @@ function waitForSlot(delayMs, signal) {
560
574
  }
561
575
 
562
576
  // src/project.ts
563
- function newProjectConnection2(project, connectionName) {
577
+ function newProjectConnection2(project, connectionName, options = {}) {
564
578
  return newProjectConnection(project, connectionName, (loadedProject, name) => {
565
579
  const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "airtable" && entry.connectionName === name);
566
580
  if (!selected) throw new TypeError("Airtable project connection is not configured");
567
- const config = z.object({ endpoint: z.string().optional(), maxResponseBytes: z.number().int().optional() }).parse(selected.configuration);
581
+ const settings = z.object({
582
+ endpoint: z.string().optional(),
583
+ maxResponseBytes: z.number().int().optional(),
584
+ pollInterval: z.number().int().nonnegative().optional(),
585
+ pollPageSize: z.number().int().optional()
586
+ }).parse(selected.configuration);
587
+ const config = {
588
+ ...settings.endpoint !== void 0 ? { endpoint: settings.endpoint } : {},
589
+ ...settings.maxResponseBytes !== void 0 ? { maxResponseBytes: settings.maxResponseBytes } : {},
590
+ ...settings.pollInterval ? { pollIntervalMs: Math.ceil(settings.pollInterval / 1e6) } : {},
591
+ ...settings.pollPageSize !== void 0 ? { pollPageSize: settings.pollPageSize } : {}
592
+ };
568
593
  const credentials = {
569
594
  async resolve(call, signal) {
570
595
  void call;
@@ -573,9 +598,707 @@ function newProjectConnection2(project, connectionName) {
573
598
  return { personalAccessToken: new SecretString2(decoded.personal_access_token) };
574
599
  }
575
600
  };
576
- return new AirtableClient(config, credentials);
601
+ return new AirtableClient(config, credentials, options);
577
602
  });
578
603
  }
604
+
605
+ // src/trigger.ts
606
+ import {
607
+ mustTriggerBindingDefinition,
608
+ newTrigger
609
+ } from "@superdurable/connectors-sdk";
610
+ import { newBindingPoller, newBindingTriggerSource, newMemoryCursorStore, newRunner } from "@superdurable/connectors-sdk/pollingtrigger";
611
+ import {
612
+ ObjectNotFoundError,
613
+ decodeTriggerConfiguration,
614
+ newDurableTriggerTarget,
615
+ parseTriggerPayloadJSON
616
+ } from "@superdurable/connectors-sdk/projectconfig";
617
+
618
+ // src/record_changed_fetcher.ts
619
+ import { markCursorInvalid, markRateLimited, newTriggerCredentialCall, waitForPollRequest } from "@superdurable/connectors-sdk/pollingtrigger";
620
+
621
+ // src/record_changed_cursor.ts
622
+ import { encodeGoJSONValue } from "@superdurable/connectors-sdk/projectconfig";
623
+
624
+ // src/record_changed_time.ts
625
+ var NanosecondsPerMillisecond = 1000000n;
626
+ var NanosecondsPerSecond = 1000000000n;
627
+ var nanosecondsPerDay = 86400n * NanosecondsPerSecond;
628
+ var rfc3339Pattern = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:[.,]([0-9]+))?(Z|[+-][0-9]{2}:[0-9]{2})$/;
629
+ function parseRFC3339Nanoseconds(text) {
630
+ const match = rfc3339Pattern.exec(text);
631
+ if (!match) return void 0;
632
+ const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number);
633
+ if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) return void 0;
634
+ if (hour > 23 || minute > 59 || second > 59) return void 0;
635
+ const fraction = (match[7] ?? "").slice(0, 9).padEnd(9, "0");
636
+ const zone = match[8];
637
+ let offsetSeconds = 0;
638
+ if (zone !== "Z") {
639
+ const zoneHours = Number(zone.slice(1, 3)), zoneMinutes = Number(zone.slice(4, 6));
640
+ if (zoneHours > 23 || zoneMinutes > 59) return void 0;
641
+ offsetSeconds = (zoneHours * 3600 + zoneMinutes * 60) * (zone[0] === "-" ? -1 : 1);
642
+ }
643
+ const seconds = BigInt(daysFromCivil(year, month, day)) * 86400n + BigInt(hour * 3600 + minute * 60 + second - offsetSeconds);
644
+ return seconds * NanosecondsPerSecond + BigInt(fraction);
645
+ }
646
+ function formatRFC3339Nanoseconds(at) {
647
+ const { date, nanoseconds } = split(at);
648
+ const fraction = nanoseconds.toString().padStart(9, "0").replace(/0+$/, "");
649
+ return `${date}${fraction ? `.${fraction}` : ""}Z`;
650
+ }
651
+ function formatMilliseconds(at) {
652
+ const { date, nanoseconds } = split(at);
653
+ return `${date}.${(nanoseconds / NanosecondsPerMillisecond).toString().padStart(3, "0")}Z`;
654
+ }
655
+ function formatEventIDTime(at) {
656
+ const { date, nanoseconds } = split(at);
657
+ return `${date.replace(/[-:]/g, "")}${nanoseconds.toString().padStart(9, "0")}Z`;
658
+ }
659
+ function truncateToMillisecond(at) {
660
+ return at - floorModulo(at, NanosecondsPerMillisecond);
661
+ }
662
+ function nanosecondsToDate(at) {
663
+ return new Date(Number(floorDivide(at, NanosecondsPerMillisecond)));
664
+ }
665
+ function split(at) {
666
+ const days = floorDivide(at, nanosecondsPerDay);
667
+ const withinDay = at - days * nanosecondsPerDay;
668
+ const [year, month, day] = civilFromDays(Number(days));
669
+ const seconds = Number(withinDay / NanosecondsPerSecond);
670
+ const nanoseconds = withinDay % NanosecondsPerSecond;
671
+ const two = (value) => value.toString().padStart(2, "0");
672
+ const date = `${year.toString().padStart(4, "0")}-${two(month)}-${two(day)}T${two(Math.floor(seconds / 3600))}:${two(Math.floor(seconds / 60) % 60)}:${two(seconds % 60)}`;
673
+ return { date, nanoseconds };
674
+ }
675
+ function floorDivide(value, divisor) {
676
+ const quotient = value / divisor;
677
+ return value % divisor < 0n ? quotient - 1n : quotient;
678
+ }
679
+ function floorModulo(value, divisor) {
680
+ return value - floorDivide(value, divisor) * divisor;
681
+ }
682
+ function daysInMonth(year, month) {
683
+ if (month === 2) return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28;
684
+ return [4, 6, 9, 11].includes(month) ? 30 : 31;
685
+ }
686
+ function daysFromCivil(year, month, day) {
687
+ const shiftedYear = month <= 2 ? year - 1 : year;
688
+ const era = Math.floor(shiftedYear / 400);
689
+ const yearOfEra = shiftedYear - era * 400;
690
+ const dayOfYear = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1;
691
+ const dayOfEra = yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;
692
+ return era * 146097 + dayOfEra - 719468;
693
+ }
694
+ function civilFromDays(daysSinceEpoch) {
695
+ const days = daysSinceEpoch + 719468;
696
+ const era = Math.floor(days / 146097);
697
+ const dayOfEra = days - era * 146097;
698
+ const yearOfEra = Math.floor((dayOfEra - Math.floor(dayOfEra / 1460) + Math.floor(dayOfEra / 36524) - Math.floor(dayOfEra / 146096)) / 365);
699
+ const dayOfYear = dayOfEra - (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));
700
+ const monthIndex = Math.floor((5 * dayOfYear + 2) / 153);
701
+ const day = dayOfYear - Math.floor((153 * monthIndex + 2) / 5) + 1;
702
+ const month = monthIndex + (monthIndex < 10 ? 3 : -9);
703
+ return [yearOfEra + era * 400 + (month <= 2 ? 1 : 0), month, day];
704
+ }
705
+
706
+ // src/record_changed_cursor.ts
707
+ var recordChangedCursorVersion = 2;
708
+ var recordChangedOverlap = 5n * NanosecondsPerSecond;
709
+ var maximumRecordChangedSeen = 2e3;
710
+ var recordIdPattern2 = /^rec[0-9A-Za-z]{14}$/;
711
+ var int64DecimalPattern = /^[+-]?[0-9]+$/;
712
+ var maximumInt64 = (1n << 63n) - 1n;
713
+ var RecordChangedCursorError = class extends Error {
714
+ constructor(message) {
715
+ super(message);
716
+ this.name = "RecordChangedCursorError";
717
+ }
718
+ };
719
+ function later(left, right) {
720
+ return right !== void 0 && (left === void 0 || right > left) ? right : left;
721
+ }
722
+ var RecordChangedPosition = class {
723
+ constructor(fieldId) {
724
+ this.fieldId = fieldId;
725
+ }
726
+ fieldId;
727
+ after;
728
+ floor;
729
+ burst;
730
+ seen = [];
731
+ scan;
732
+ /** Return the earliest modification time a poll still delivers; undefined means every record. */
733
+ lowerBound() {
734
+ return this.after === void 0 ? void 0 : later(this.after - recordChangedOverlap, this.floor);
735
+ }
736
+ /** Report a record older than the lower bound or already delivered at this time. */
737
+ isDelivered(recordId, modifiedAt) {
738
+ const lowerBound = this.lowerBound();
739
+ if (lowerBound !== void 0 && modifiedAt < lowerBound) return true;
740
+ const at = truncateToMillisecond(modifiedAt);
741
+ return this.seen.some((seen) => seen.recordId === recordId && seen.at === at);
742
+ }
743
+ /** Remember one delivered record; records arrive oldest first within a scan. */
744
+ deliver(recordId, modifiedAt) {
745
+ if (this.burst !== void 0 && modifiedAt > this.burst) this.closeBurst();
746
+ this.after = later(this.after, modifiedAt);
747
+ this.seen.push({ recordId, at: truncateToMillisecond(modifiedAt) });
748
+ this.bound();
749
+ }
750
+ /** Move the floor past a burst time once every record at that time was listed. */
751
+ closeBurst() {
752
+ if (this.burst !== void 0) {
753
+ this.floor = later(this.floor, this.burst + NanosecondsPerMillisecond);
754
+ this.burst = void 0;
755
+ }
756
+ this.bound();
757
+ }
758
+ /** Return the listRecords filter bound: the lower bound minus one second of formula rounding. */
759
+ filterSince() {
760
+ const lowerBound = this.lowerBound();
761
+ return lowerBound === void 0 ? 0n : truncateToMillisecond(lowerBound - NanosecondsPerSecond);
762
+ }
763
+ bound() {
764
+ const lowerBound = this.lowerBound();
765
+ if (lowerBound !== void 0) this.seen = this.seen.filter((seen) => !(seen.at < lowerBound));
766
+ if (this.seen.length <= maximumRecordChangedSeen) return;
767
+ this.seen.sort((left, right) => left.at < right.at ? -1 : left.at > right.at ? 1 : 0);
768
+ const dropped = this.seen[this.seen.length - maximumRecordChangedSeen - 1].at;
769
+ this.seen = this.seen.filter((seen) => seen.at > dropped);
770
+ if (this.after !== void 0 && dropped < truncateToMillisecond(this.after)) {
771
+ this.floor = later(this.floor, dropped + NanosecondsPerMillisecond);
772
+ return;
773
+ }
774
+ this.burst = later(this.burst, dropped);
775
+ }
776
+ };
777
+ function encodeRecordChangedCursor(position) {
778
+ const parts = [`"v":${recordChangedCursorVersion}`, `"fieldId":${encodeGoJSONValue(position.fieldId)}`, `"after":${encodeGoJSONValue(formatCursorTime(position.after))}`];
779
+ if (position.floor !== void 0) parts.push(`"floor":${encodeGoJSONValue(formatCursorTime(position.floor))}`);
780
+ if (position.burst !== void 0) parts.push(`"burst":${encodeGoJSONValue(formatCursorTime(position.burst))}`);
781
+ if (position.seen.length > 0) {
782
+ const after = truncateToMillisecond(position.after ?? 0n);
783
+ parts.push(`"seen":[${position.seen.map((seen) => encodeGoJSONValue(`${seen.recordId}:${(after - seen.at) / NanosecondsPerMillisecond}`)).join(",")}]`);
784
+ }
785
+ if (position.scan) parts.push(`"scan":{"since":${encodeGoJSONValue(position.scan.since)},"offset":${encodeGoJSONValue(position.scan.offset)}}`);
786
+ return { token: `{${parts.join(",")}}` };
787
+ }
788
+ function decodeRecordChangedCursor(encoded) {
789
+ let token;
790
+ try {
791
+ token = decodeToken(encoded);
792
+ } catch {
793
+ throw new RecordChangedCursorError("Airtable recordChanged cursor is not a version 2 cursor");
794
+ }
795
+ if (token.version !== BigInt(recordChangedCursorVersion)) throw new RecordChangedCursorError("Airtable recordChanged cursor is not a version 2 cursor");
796
+ if (token.seen.length > maximumRecordChangedSeen) throw new RecordChangedCursorError("Airtable recordChanged cursor holds too many record IDs");
797
+ const position = new RecordChangedPosition(token.fieldId);
798
+ position.scan = token.scan;
799
+ position.after = parseCursorTime(token.after);
800
+ position.floor = parseCursorTime(token.floor);
801
+ position.burst = parseCursorTime(token.burst);
802
+ if (position.after === void 0 && (token.seen.length > 0 || position.floor !== void 0 || position.burst !== void 0)) {
803
+ throw new RecordChangedCursorError("Airtable recordChanged cursor remembers records without a time");
804
+ }
805
+ if (token.scan && (!token.scan.since || !token.scan.offset || parseRFC3339Nanoseconds(token.scan.since) === void 0)) {
806
+ throw new RecordChangedCursorError("Airtable recordChanged cursor scan is invalid");
807
+ }
808
+ const after = truncateToMillisecond(position.after ?? 0n);
809
+ for (const entry of token.seen) {
810
+ const separator = entry.indexOf(":");
811
+ const recordId = separator < 0 ? entry : entry.slice(0, separator), delta = separator < 0 ? "" : entry.slice(separator + 1);
812
+ const milliseconds = int64DecimalPattern.test(delta) ? BigInt(delta) : -1n;
813
+ if (separator < 0 || milliseconds < 0n || milliseconds > maximumInt64 || !recordIdPattern2.test(recordId)) {
814
+ throw new RecordChangedCursorError("Airtable recordChanged cursor holds an invalid record entry");
815
+ }
816
+ position.seen.push({ recordId, at: after - milliseconds * NanosecondsPerMillisecond });
817
+ }
818
+ return position;
819
+ }
820
+ function parseCursorTime(text) {
821
+ if (text === "") return void 0;
822
+ const at = parseRFC3339Nanoseconds(text);
823
+ if (at === void 0) throw new RecordChangedCursorError("Airtable recordChanged cursor time is invalid");
824
+ return at;
825
+ }
826
+ function formatCursorTime(at) {
827
+ return at === void 0 ? "" : formatRFC3339Nanoseconds(at);
828
+ }
829
+ var tokenFields = ["v", "fieldId", "after", "floor", "burst", "seen", "scan"];
830
+ function decodeToken(encoded) {
831
+ const document = new StrictJSONParser(encoded).parseDocument();
832
+ const token = { version: 0n, fieldId: "", after: "", floor: "", burst: "", seen: [], scan: void 0 };
833
+ if (document === null) return token;
834
+ for (const [name, value] of objectPairs(document, tokenFields)) {
835
+ if (name === "v") {
836
+ if (value === null) continue;
837
+ if (typeof value !== "object" || !("number" in value) || !/^-?(0|[1-9][0-9]*)$/.test(value.number)) throw new TypeError("v is not an int");
838
+ token.version = BigInt(value.number);
839
+ if (token.version > maximumInt64 || token.version < -maximumInt64 - 1n) throw new TypeError("v overflows int");
840
+ } else if (name === "seen") {
841
+ if (value === null) {
842
+ token.seen = [];
843
+ continue;
844
+ }
845
+ if (!Array.isArray(value)) throw new TypeError("seen is not an array");
846
+ token.seen = value.map((item) => goString(item, ""));
847
+ } else if (name === "scan") {
848
+ if (value === null) {
849
+ token.scan = void 0;
850
+ continue;
851
+ }
852
+ const scan = { since: "", offset: "" };
853
+ for (const [scanName, scanValue] of objectPairs(value, ["since", "offset"])) scan[scanName] = goString(scanValue, scan[scanName]);
854
+ token.scan = scan;
855
+ } else {
856
+ token[name] = goString(value, token[name]);
857
+ }
858
+ }
859
+ return token;
860
+ }
861
+ function objectPairs(value, names) {
862
+ if (value === null || typeof value !== "object" || !("pairs" in value)) throw new TypeError("JSON value is not an object");
863
+ const matched = [];
864
+ for (const [key, item] of value.pairs) {
865
+ const name = names.find((candidate) => candidate === key) ?? names.find((candidate) => candidate.toLowerCase() === key.toLowerCase());
866
+ if (name !== void 0) matched.push([name, item]);
867
+ }
868
+ return matched;
869
+ }
870
+ function goString(value, current) {
871
+ if (value === null) return current;
872
+ if (typeof value !== "string") throw new TypeError("JSON value is not a string");
873
+ return value;
874
+ }
875
+ var jsonNumberPattern = /-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/y;
876
+ var jsonStringPattern = /"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"/y;
877
+ var StrictJSONParser = class {
878
+ constructor(text) {
879
+ this.text = text;
880
+ }
881
+ text;
882
+ index = 0;
883
+ parseDocument() {
884
+ const value = this.parseValue(0);
885
+ this.skipWhitespace();
886
+ if (this.index !== this.text.length) throw new SyntaxError("trailing data after JSON value");
887
+ return value;
888
+ }
889
+ parseValue(depth) {
890
+ if (depth > 1e4) throw new SyntaxError("JSON nests too deeply");
891
+ this.skipWhitespace();
892
+ const character = this.text[this.index];
893
+ if (character === "{") return this.parseObject(depth);
894
+ if (character === "[") return this.parseArray(depth);
895
+ if (character === '"') return this.parseString();
896
+ for (const [literal, value] of [["true", true], ["false", false], ["null", null]]) {
897
+ if (this.text.startsWith(literal, this.index)) {
898
+ this.index += literal.length;
899
+ return value;
900
+ }
901
+ }
902
+ const number = this.matchAt(jsonNumberPattern);
903
+ if (!number) throw new SyntaxError("invalid JSON value");
904
+ this.index += number[0].length;
905
+ return { number: number[0] };
906
+ }
907
+ parseObject(depth) {
908
+ const pairs = [];
909
+ this.index++;
910
+ this.skipWhitespace();
911
+ if (this.text[this.index] === "}") {
912
+ this.index++;
913
+ return { pairs };
914
+ }
915
+ for (; ; ) {
916
+ this.skipWhitespace();
917
+ if (this.text[this.index] !== '"') throw new SyntaxError("object key must be a string");
918
+ const key = this.parseString();
919
+ this.skipWhitespace();
920
+ if (this.text[this.index++] !== ":") throw new SyntaxError("expected colon");
921
+ pairs.push([key, this.parseValue(depth + 1)]);
922
+ this.skipWhitespace();
923
+ const separator = this.text[this.index++];
924
+ if (separator === "}") return { pairs };
925
+ if (separator !== ",") throw new SyntaxError("expected comma or closing brace");
926
+ }
927
+ }
928
+ parseArray(depth) {
929
+ const items = [];
930
+ this.index++;
931
+ this.skipWhitespace();
932
+ if (this.text[this.index] === "]") {
933
+ this.index++;
934
+ return items;
935
+ }
936
+ for (; ; ) {
937
+ items.push(this.parseValue(depth + 1));
938
+ this.skipWhitespace();
939
+ const separator = this.text[this.index++];
940
+ if (separator === "]") return items;
941
+ if (separator !== ",") throw new SyntaxError("expected comma or closing bracket");
942
+ }
943
+ }
944
+ parseString() {
945
+ const match = this.matchAt(jsonStringPattern);
946
+ if (!match || [...match[0]].some((character) => character < " ")) throw new SyntaxError("invalid JSON string");
947
+ this.index += match[0].length;
948
+ return JSON.parse(match[0]);
949
+ }
950
+ matchAt(pattern) {
951
+ pattern.lastIndex = this.index;
952
+ return pattern.exec(this.text);
953
+ }
954
+ skipWhitespace() {
955
+ while (this.index < this.text.length && " \n\r".includes(this.text[this.index])) this.index++;
956
+ }
957
+ };
958
+
959
+ // src/record_changed_fetcher.ts
960
+ var maximumRecordChangedScanPages = 20;
961
+ var lastModifiedTimeFieldType = "lastModifiedTime";
962
+ var maximumOffsetBytes = 1024;
963
+ var RecordChangedPollError = class extends Error {
964
+ constructor(message) {
965
+ super(message);
966
+ this.name = "RecordChangedPollError";
967
+ }
968
+ };
969
+ var ListOffsetExpiredError = class extends RecordChangedPollError {
970
+ };
971
+ function recordChangedEventId(recordId, lastModifiedTime) {
972
+ return `${recordId}-${formatEventIDTime(lastModifiedTime)}`;
973
+ }
974
+ var RecordChangedFetcher = class {
975
+ /** Bind the client and the binding's table; it sends nothing. */
976
+ constructor(client, binding, configuration) {
977
+ this.client = client;
978
+ this.binding = binding;
979
+ this.configuration = configuration;
980
+ }
981
+ client;
982
+ binding;
983
+ configuration;
984
+ /** The watched field's current name, resolved from the base schema; blank until resolved. */
985
+ fieldName = "";
986
+ /** Position the cursor at the table's most recent change, so existing records are not delivered. */
987
+ async seedCursor(context) {
988
+ await this.resolveFieldName(context);
989
+ const { records, nextOffset } = await this.listRecords(context, void 0, "desc", "");
990
+ const position = new RecordChangedPosition(this.configuration.fieldId);
991
+ if (nextOffset && records.length > 0) {
992
+ const oldest = records.reduce((minimum, changed) => changed.modifiedAt < minimum ? changed.modifiedAt : minimum, records[0].modifiedAt);
993
+ position.floor = truncateToMillisecond(oldest) + NanosecondsPerMillisecond;
994
+ }
995
+ for (const changed of records) position.deliver(changed.record.id, changed.modifiedAt);
996
+ return encodeRecordChangedCursor(position);
997
+ }
998
+ /**
999
+ * List records modified since the cursor's lower bound, oldest first, and return those not yet delivered.
1000
+ * An open scan resumes from its stored Airtable offset.
1001
+ */
1002
+ async fetchChanges(context, cursor) {
1003
+ let position;
1004
+ try {
1005
+ position = decodeRecordChangedCursor(cursor.token);
1006
+ } catch (error) {
1007
+ if (error instanceof RecordChangedCursorError) throw markCursorInvalid(error);
1008
+ throw error;
1009
+ }
1010
+ if (position.fieldId !== this.configuration.fieldId) throw markCursorInvalid(new RecordChangedPollError("the binding now watches a different Last modified time field"));
1011
+ await this.resolveFieldName(context);
1012
+ let since = position.filterSince(), offset = "";
1013
+ if (position.scan) {
1014
+ since = parseRFC3339Nanoseconds(position.scan.since) ?? 0n;
1015
+ offset = position.scan.offset;
1016
+ }
1017
+ let hasRestartedScan = false;
1018
+ const changes = [];
1019
+ for (let scannedPages = 0; scannedPages < maximumRecordChangedScanPages; scannedPages++) {
1020
+ let page;
1021
+ try {
1022
+ page = await this.listRecords(context, since, "asc", offset);
1023
+ } catch (error) {
1024
+ if (!(error instanceof ListOffsetExpiredError) || !offset || hasRestartedScan) throw error;
1025
+ hasRestartedScan = true;
1026
+ position.scan = void 0;
1027
+ since = position.filterSince();
1028
+ offset = "";
1029
+ continue;
1030
+ }
1031
+ for (const changed of page.records) {
1032
+ if (position.isDelivered(changed.record.id, changed.modifiedAt)) continue;
1033
+ changes.push(this.newEvent(changed));
1034
+ position.deliver(changed.record.id, changed.modifiedAt);
1035
+ }
1036
+ position.scan = void 0;
1037
+ if (!page.nextOffset) position.closeBurst();
1038
+ else position.scan = { since: formatRFC3339Nanoseconds(since), offset: page.nextOffset };
1039
+ if (changes.length > 0 || !page.nextOffset) return { changes, next: encodeRecordChangedCursor(position), hasMorePages: page.nextOffset !== "" };
1040
+ offset = page.nextOffset;
1041
+ }
1042
+ return { changes, next: encodeRecordChangedCursor(position), hasMorePages: true };
1043
+ }
1044
+ newEvent(changed) {
1045
+ const createdAt = parseRFC3339Nanoseconds(changed.record.createdTime) ?? 0n;
1046
+ const distance = changed.modifiedAt - createdAt;
1047
+ return {
1048
+ id: recordChangedEventId(changed.record.id, changed.modifiedAt),
1049
+ occurredAt: nanosecondsToDate(changed.modifiedAt),
1050
+ payload: {
1051
+ baseId: this.configuration.baseId,
1052
+ tableId: this.configuration.tableId,
1053
+ lastModifiedTime: formatRFC3339Nanoseconds(changed.modifiedAt),
1054
+ isCreatedRecord: (distance < 0n ? -distance : distance) <= NanosecondsPerSecond,
1055
+ record: changed.record
1056
+ }
1057
+ };
1058
+ }
1059
+ /** Read one page sorted by the watched field, of records whose field value is after since. */
1060
+ async listRecords(context, since, direction, offset) {
1061
+ const fieldId = this.configuration.fieldId;
1062
+ const body = {
1063
+ pageSize: this.client.pollPageSize,
1064
+ ...offset ? { offset } : {},
1065
+ filterByFormula: `IS_AFTER({${fieldId}}, DATETIME_PARSE("${formatMilliseconds(since ?? 0n)}"))`,
1066
+ sort: [{ field: fieldId, direction }]
1067
+ };
1068
+ const path = `/v0/${encodeURIComponent(this.configuration.baseId)}/${encodeURIComponent(this.configuration.tableId)}/listRecords`;
1069
+ const response = await this.exchange(context, "POST", path, body);
1070
+ let records, nextOffset;
1071
+ try {
1072
+ const document = decodeJSONObject(response);
1073
+ if (document.records === void 0 || document.records === null) throw new RecordChangedPollError("Airtable returned a list response without records");
1074
+ if (!Array.isArray(document.records)) throw new RecordChangedPollError("Airtable returned a malformed response");
1075
+ if (document.records.length > this.client.pollPageSize) throw new RecordChangedPollError("Airtable returned more records than the requested page size");
1076
+ nextOffset = optionalMember(document, "offset", "string") ?? "";
1077
+ if (Buffer.byteLength(nextOffset, "utf8") > maximumOffsetBytes) throw new RecordChangedPollError("Airtable returned an oversized offset");
1078
+ records = document.records.map(decodeRecord);
1079
+ } catch (error) {
1080
+ if (error instanceof RecordChangedPollError) throw error;
1081
+ throw new RecordChangedPollError("Airtable returned a malformed response");
1082
+ }
1083
+ return { records: records.map((record) => ({ record, modifiedAt: this.readLastModifiedTime(record) })), nextOffset };
1084
+ }
1085
+ /** Parse the watched field of a record the filter matched, so the field has a value. */
1086
+ readLastModifiedTime(record) {
1087
+ const fields = record.fields ?? {};
1088
+ if (!Object.hasOwn(fields, this.fieldName)) {
1089
+ this.fieldName = "";
1090
+ throw new RecordChangedPollError("Airtable returned a changed record without the Last modified time field; the field name is read again");
1091
+ }
1092
+ const value = fields[this.fieldName];
1093
+ const modifiedAt = typeof value === "string" ? parseRFC3339Nanoseconds(value) : void 0;
1094
+ if (modifiedAt === void 0) throw new RecordChangedPollError("Airtable returned a Last modified time value without a time of day");
1095
+ return modifiedAt;
1096
+ }
1097
+ /** Read the base schema once, and again after a rename, to find the watched field's current name, since listed records key their fields by name. */
1098
+ async resolveFieldName(context) {
1099
+ if (this.fieldName) return;
1100
+ const response = await this.exchange(context, "GET", `/v0/meta/bases/${encodeURIComponent(this.configuration.baseId)}/tables`, void 0);
1101
+ let tables;
1102
+ try {
1103
+ tables = readSchemaTables(decodeJSONObject(response));
1104
+ } catch {
1105
+ throw new RecordChangedPollError("Airtable returned a malformed response");
1106
+ }
1107
+ const table = tables.find((candidate) => candidate.id === this.configuration.tableId);
1108
+ if (!table) throw new RecordChangedPollError("the Airtable base schema has no table with the recordChanged table ID");
1109
+ const field = table.fields.find((candidate) => candidate.id === this.configuration.fieldId);
1110
+ if (!field) throw new RecordChangedPollError("the Airtable table has no field with the recordChanged field ID");
1111
+ if (field.type !== lastModifiedTimeFieldType || field.name === "") throw new RecordChangedPollError("the Airtable recordChanged field is not a Last modified time field");
1112
+ if (field.resultType !== void 0 && field.resultType !== "dateTime") throw new RecordChangedPollError("the Airtable recordChanged Last modified time field must include a time of day");
1113
+ this.fieldName = field.name;
1114
+ }
1115
+ /** Wait on the runner's request limiter, then send one paced request through the client. */
1116
+ async exchange(context, method, path, body) {
1117
+ await waitForPollRequest(context);
1118
+ const call = newTriggerCredentialCall(this.binding.connection, this.binding.trigger, context.signal);
1119
+ const baseId = this.configuration.baseId;
1120
+ const result = await this.client.exchange(call, this.binding.trigger.triggerName, baseId, baseId, method, path, body);
1121
+ if ("response" in result) return result.response.body;
1122
+ const outcome = result.outcome;
1123
+ if (outcome.disposition === "offsetExpired") throw new ListOffsetExpiredError("Airtable no longer recognizes the list offset");
1124
+ const error = new RecordChangedPollError(outcome.failure.message);
1125
+ if (outcome.disposition === "retry" && outcome.failure.kind === "RATE_LIMIT") throw markRateLimited(error, outcome.retryAfterMs);
1126
+ throw error;
1127
+ }
1128
+ };
1129
+ function readSchemaTables(document) {
1130
+ return (optionalMember(document, "tables", "array") ?? []).map((table) => ({
1131
+ id: optionalMember(table, "id", "string") ?? "",
1132
+ fields: (optionalMember(table, "fields", "array") ?? []).map((field) => {
1133
+ const result = optionalMember(optionalMember(field, "options", "object"), "result", "object");
1134
+ return {
1135
+ id: optionalMember(field, "id", "string") ?? "",
1136
+ name: optionalMember(field, "name", "string") ?? "",
1137
+ type: optionalMember(field, "type", "string") ?? "",
1138
+ resultType: result === void 0 ? void 0 : optionalMember(result, "type", "string") ?? ""
1139
+ };
1140
+ })
1141
+ }));
1142
+ }
1143
+ function optionalMember(document, name, kind) {
1144
+ if (document === void 0 || document === null) return void 0;
1145
+ if (!isJSONObject(document)) throw new TypeError("Airtable returned a malformed response");
1146
+ const value = document[name];
1147
+ if (value === void 0 || value === null) return void 0;
1148
+ const matches = kind === "string" ? typeof value === "string" : kind === "array" ? Array.isArray(value) : isJSONObject(value);
1149
+ if (!matches) throw new TypeError("Airtable returned a malformed response");
1150
+ return value;
1151
+ }
1152
+ function isJSONObject(value) {
1153
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1154
+ }
1155
+ function decodeJSONObject(body) {
1156
+ const document = JSON.parse(Buffer.from(body).toString("utf8"));
1157
+ if (!isJSONObject(document)) throw new TypeError("Airtable returned a malformed response");
1158
+ return document;
1159
+ }
1160
+
1161
+ // src/record_changed_models.ts
1162
+ import { z as z2 } from "zod";
1163
+ var goString2 = z2.string().nullish().transform((value) => value ?? "");
1164
+ var optionalGoString = z2.string().nullish().transform((value) => value || void 0);
1165
+ var RecordChangedTriggerConfigurationSchema = z2.strictObject({
1166
+ baseId: goString2,
1167
+ baseName: optionalGoString,
1168
+ tableId: goString2,
1169
+ tableName: optionalGoString,
1170
+ fieldId: goString2,
1171
+ fieldName: optionalGoString
1172
+ }).transform((configuration) => ({
1173
+ baseId: configuration.baseId,
1174
+ ...configuration.baseName ? { baseName: configuration.baseName } : {},
1175
+ tableId: configuration.tableId,
1176
+ ...configuration.tableName ? { tableName: configuration.tableName } : {},
1177
+ fieldId: configuration.fieldId,
1178
+ ...configuration.fieldName ? { fieldName: configuration.fieldName } : {}
1179
+ }));
1180
+ var RecordChangedEventSchema = z2.object({
1181
+ baseId: goString2,
1182
+ tableId: goString2,
1183
+ lastModifiedTime: z2.string(),
1184
+ isCreatedRecord: z2.boolean().nullish().transform((value) => value ?? false),
1185
+ record: z2.object({
1186
+ id: goString2,
1187
+ createdTime: z2.string(),
1188
+ fields: z2.record(z2.string(), z2.unknown()).nullish().transform((value) => value ?? null)
1189
+ })
1190
+ }).transform((event) => ({
1191
+ baseId: event.baseId,
1192
+ tableId: event.tableId,
1193
+ lastModifiedTime: event.lastModifiedTime,
1194
+ isCreatedRecord: event.isCreatedRecord,
1195
+ record: { id: event.record.id, createdTime: event.record.createdTime, fields: event.record.fields }
1196
+ }));
1197
+
1198
+ // src/trigger.ts
1199
+ var UIUnitBasePicker = "basePicker";
1200
+ var UIBasePickerPortBaseID = "baseId";
1201
+ var UIBasePickerPortBaseName = "baseName";
1202
+ var UIUnitTablePicker = "tablePicker";
1203
+ var UITablePickerPortBaseID = "baseId";
1204
+ var UITablePickerPortTableID = "tableId";
1205
+ var UITablePickerPortTableName = "tableName";
1206
+ var UIUnitLastModifiedTimeFieldPicker = "lastModifiedTimeFieldPicker";
1207
+ var UILastModifiedTimeFieldPickerPortBaseID = "baseId";
1208
+ var UILastModifiedTimeFieldPickerPortTableID = "tableId";
1209
+ var UILastModifiedTimeFieldPickerPortFieldID = "fieldId";
1210
+ var UILastModifiedTimeFieldPickerPortFieldName = "fieldName";
1211
+ var recordChangedMaximumBackoffMs = 5 * 6e4;
1212
+ var baseIdPattern2 = /^app[0-9A-Za-z]{14}$/;
1213
+ var tableIdPattern = /^tbl[0-9A-Za-z]{14}$/;
1214
+ var fieldIdPattern = /^fld[0-9A-Za-z]{14}$/;
1215
+ var RecordChangedTriggerDefinition = {
1216
+ trigger: { connectorId: ConnectorID, triggerName: "recordChanged" },
1217
+ description: "Receive each record of one picked table that is created or changed after the last processed change, as reported by a picked Last modified time field."
1218
+ };
1219
+ function defineRecordChangedTriggerBinding(config) {
1220
+ return mustTriggerBindingDefinition({ definition: RecordChangedTriggerDefinition, ...config });
1221
+ }
1222
+ function validateRecordChangedTriggerConfiguration(configuration) {
1223
+ if (!baseIdPattern2.test(configuration?.baseId ?? "")) throw new TypeError("Airtable recordChanged baseId must be app followed by 14 letters and digits");
1224
+ if (!tableIdPattern.test(configuration.tableId ?? "")) throw new TypeError("Airtable recordChanged tableId must be tbl followed by 14 letters and digits");
1225
+ if (!fieldIdPattern.test(configuration.fieldId ?? "")) throw new TypeError("Airtable recordChanged fieldId must be fld followed by 14 letters and digits");
1226
+ }
1227
+ function decodeRecordChangedEventPayload(_payloadJSON, payloadBytes) {
1228
+ return RecordChangedEventSchema.parse(parseTriggerPayloadJSON(payloadBytes));
1229
+ }
1230
+ function newRecordChangedTriggerRunner(config) {
1231
+ const client = airtableClientOf(config.connection);
1232
+ if (!config.routes?.length) throw new TypeError("Airtable recordChanged Trigger routes are required");
1233
+ const pollers = config.routes.map((route) => {
1234
+ if (!route.bindingName?.trim() || !route.target || !route.cursor) throw new TypeError("Airtable recordChanged binding name, cursor, and target are required");
1235
+ validateRouteConfiguration(route.bindingName, route.configuration);
1236
+ const binding = bindingRef(config.connection, route.bindingName);
1237
+ return newBindingPoller({
1238
+ definition: RecordChangedTriggerDefinition,
1239
+ binding,
1240
+ cursor: route.cursor,
1241
+ fetcher: new RecordChangedFetcher(client, binding, route.configuration),
1242
+ target: route.target
1243
+ });
1244
+ });
1245
+ return newRunner({
1246
+ connection: config.connection.reference,
1247
+ schedule: pollSchedule(client),
1248
+ pollers,
1249
+ ...config.requestLimiter ? { requestLimiter: config.requestLimiter } : {},
1250
+ ...client.triggerLogger ? { logger: client.triggerLogger } : {}
1251
+ });
1252
+ }
1253
+ function newProjectRecordChangedTriggerRunner(project, connectionName, routes, options = {}) {
1254
+ const connection = newProjectConnection2(project, connectionName, options);
1255
+ const triggerName = RecordChangedTriggerDefinition.trigger.triggerName;
1256
+ const durableRoutes = routes.map((route) => {
1257
+ const name = JSON.stringify(route.bindingName);
1258
+ if (!route.target) throw new TypeError(`Airtable recordChanged binding ${name} target is required`);
1259
+ const key = { connectorId: ConnectorID, connectionName, triggerName, bindingName: route.bindingName };
1260
+ let configuration;
1261
+ try {
1262
+ configuration = decodeTriggerConfiguration(project.configuration, key, RecordChangedTriggerConfigurationSchema);
1263
+ } catch (error) {
1264
+ if (error instanceof ObjectNotFoundError) throw new TypeError(`Airtable recordChanged binding ${name} has no saved configuration; pick the base, table, and field in Dex Web and restart`, { cause: error });
1265
+ throw new TypeError(`Airtable recordChanged binding ${name} configuration: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
1266
+ }
1267
+ const target = newDurableTriggerTarget(project.triggerInbox(key), key, route.target, { ...options.logger ? { logger: options.logger } : {}, decodePayload: decodeRecordChangedEventPayload });
1268
+ return { bindingName: route.bindingName, configuration, cursor: project.pollCursorStore(key), target };
1269
+ });
1270
+ return newRecordChangedTriggerRunner({ connection, routes: durableRoutes });
1271
+ }
1272
+ function newRecordChangedTrigger(config) {
1273
+ const client = airtableClientOf(config.connection);
1274
+ if (!config.bindingName?.trim() || !config.target) throw new TypeError("Airtable recordChanged binding name, cursor, and target are required");
1275
+ validateRouteConfiguration(config.bindingName, config.configuration);
1276
+ const binding = bindingRef(config.connection, config.bindingName);
1277
+ const source = newBindingTriggerSource({
1278
+ definition: RecordChangedTriggerDefinition,
1279
+ binding,
1280
+ cursor: newMemoryCursorStore(),
1281
+ fetcher: new RecordChangedFetcher(client, binding, config.configuration)
1282
+ }, pollSchedule(client), client.triggerLogger);
1283
+ return newTrigger({ definition: RecordChangedTriggerDefinition, binding, source, target: config.target, ...client.triggerLogger ? { logger: client.triggerLogger } : {} });
1284
+ }
1285
+ function bindingRef(connection, bindingName) {
1286
+ return { connection: connection.reference, trigger: RecordChangedTriggerDefinition.trigger, name: bindingName };
1287
+ }
1288
+ function validateRouteConfiguration(bindingName, configuration) {
1289
+ try {
1290
+ validateRecordChangedTriggerConfiguration(configuration);
1291
+ } catch (error) {
1292
+ throw new TypeError(`Airtable recordChanged binding ${JSON.stringify(bindingName)}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
1293
+ }
1294
+ }
1295
+ function pollSchedule(client) {
1296
+ return { intervalMs: client.pollIntervalMs, maxBackoffMs: Math.max(recordChangedMaximumBackoffMs, client.pollIntervalMs) };
1297
+ }
1298
+ function airtableClientOf(connection) {
1299
+ if (!(connection?.operations instanceof AirtableClient)) throw new TypeError("Airtable recordChanged requires a connection from newProjectConnection or newConnection with an AirtableClient");
1300
+ return connection.operations;
1301
+ }
579
1302
  export {
580
1303
  AirtableClient,
581
1304
  ConfigSchema,
@@ -603,11 +1326,26 @@ export {
603
1326
  ListRecordsMetadata,
604
1327
  ListRecordsOperation,
605
1328
  ProviderID,
1329
+ RecordChangedEventSchema,
1330
+ RecordChangedTriggerConfigurationSchema,
1331
+ RecordChangedTriggerDefinition,
606
1332
  RecordPageSchema,
607
1333
  RecordSchema,
608
1334
  RecordSortSchema,
609
1335
  RecordUpdateSchema,
610
1336
  RecordUpsertSchema,
1337
+ UIBasePickerPortBaseID,
1338
+ UIBasePickerPortBaseName,
1339
+ UILastModifiedTimeFieldPickerPortBaseID,
1340
+ UILastModifiedTimeFieldPickerPortFieldID,
1341
+ UILastModifiedTimeFieldPickerPortFieldName,
1342
+ UILastModifiedTimeFieldPickerPortTableID,
1343
+ UITablePickerPortBaseID,
1344
+ UITablePickerPortTableID,
1345
+ UITablePickerPortTableName,
1346
+ UIUnitBasePicker,
1347
+ UIUnitLastModifiedTimeFieldPicker,
1348
+ UIUnitTablePicker,
611
1349
  UpdateRecordsBranch,
612
1350
  UpdateRecordsBranchDefect,
613
1351
  UpdateRecordsBranchInvalidResponse,
@@ -629,11 +1367,18 @@ export {
629
1367
  UpsertRecordsMetadata,
630
1368
  UpsertRecordsOperation,
631
1369
  UpsertedRecordsSchema,
1370
+ decodeCredentials,
1371
+ decodeRecordChangedEventPayload,
1372
+ defineRecordChangedTriggerBinding,
632
1373
  newConnection,
633
1374
  newConnectionWithOperations,
634
1375
  newGetRecordStep,
635
1376
  newListRecordsStep,
636
1377
  newProjectConnection2 as newProjectConnection,
1378
+ newProjectRecordChangedTriggerRunner,
1379
+ newRecordChangedTrigger,
1380
+ newRecordChangedTriggerRunner,
637
1381
  newUpdateRecordsStep,
638
- newUpsertRecordsStep
1382
+ newUpsertRecordsStep,
1383
+ validateRecordChangedTriggerConfiguration
639
1384
  };