@superdurable/connector-clickup 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
@@ -22,6 +22,7 @@ import {
22
22
  CreateTaskInputSchema,
23
23
  CreateTaskMetadata,
24
24
  CreateTaskOutputSchema,
25
+ CredentialMaterialError,
25
26
  CustomFieldInputSchema,
26
27
  CustomFieldValueSchema,
27
28
  FindMemberByEmailBranch,
@@ -78,10 +79,11 @@ import {
78
79
  UpdateTaskTagsOutputSchema,
79
80
  UserSchema,
80
81
  decodeCredentials,
82
+ isCredentialMaterialError,
81
83
  newConnection,
82
84
  newConnectionWithOperations,
83
85
  newProjectConnection
84
- } from "./chunk-PAUZSKGN.js";
86
+ } from "./chunk-PQCNNSDL.js";
85
87
 
86
88
  // src/generated/steps.ts
87
89
  import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
@@ -119,7 +121,7 @@ function newCreateTaskStep(configuration) {
119
121
  ] });
120
122
  }
121
123
  function newUpdateTaskStep(configuration) {
122
- const { connection, connectionName, updated, notFound, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
124
+ const { connection, connectionName, updated, notFound, providerRejected, invalidResponse, defect: defect2, maxSends, ...stepConfiguration } = configuration;
123
125
  if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
124
126
  return newMutationStep({ ...stepConfiguration, operation: connection.operations.updateTask(), connection: connection.reference, branches: [
125
127
  goToBranch("updated", updated),
@@ -130,7 +132,7 @@ function newUpdateTaskStep(configuration) {
130
132
  ] });
131
133
  }
132
134
  function newUpdateTaskTagsStep(configuration) {
133
- const { connection, connectionName, updated, notFound, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
135
+ const { connection, connectionName, updated, notFound, providerRejected, invalidResponse, defect: defect2, maxSends, ...stepConfiguration } = configuration;
134
136
  if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
135
137
  return newMutationStep({ ...stepConfiguration, operation: connection.operations.updateTaskTags(), connection: connection.reference, branches: [
136
138
  goToBranch("updated", updated),
@@ -168,11 +170,13 @@ import { SecretString as SecretString2 } from "@superdurable/connectors-sdk";
168
170
  import { z } from "zod";
169
171
 
170
172
  // src/client.ts
171
- import { BodyTooLargeError, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
172
- import { SecretString } from "@superdurable/connectors-sdk";
173
+ import { BodyTooLargeError, ProviderStalledError, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
174
+ import { defaultTriggerLogger, ReauthorizationRequiredError, SecretString } from "@superdurable/connectors-sdk";
175
+ import { ConnectionNotSelectedError, CredentialBrokerRejectedError, ObjectNotFoundError } from "@superdurable/connectors-sdk/projectconfig";
173
176
 
174
177
  // src/operations.ts
175
- import { newMutationBranch, newMutationRetry, newMutationUncertain, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
178
+ import { definitionMaxSends, newMutationBranch, newMutationRetry, newMutationUncertain, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
179
+ import { newFence } from "@superdurable/connectors-sdk/singledispatch";
176
180
  var taskIdPattern = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
177
181
  var numericIdPattern = /^[0-9]{1,20}$/;
178
182
  var zeroTask = { id: "", name: "", status: { name: "" }, assignees: [], tags: [] };
@@ -193,6 +197,26 @@ function mutationExchange(exchange, output, receipt2, hasInvalidResponse = true)
193
197
  const branch = exchange.kind === "notFound" ? "notFound" : exchange.kind === "invalid" && hasInvalidResponse ? "invalidResponse" : exchange.kind === "defect" ? "defect" : "providerRejected";
194
198
  return newMutationBranch(branch, output, receipt2, exchange.failure);
195
199
  }
200
+ var definiteWriteRefusalStatuses = /* @__PURE__ */ new Set([400, 401, 403, 404, 411, 413, 414, 415, 422]);
201
+ function classifyWrite(exchange) {
202
+ if (exchange.kind === "succeeded") return "accepted";
203
+ if (exchange.kind === "notSent" || exchange.kind === "rateLimited") return "notApplied";
204
+ if (exchange.kind === "defect") return "defect";
205
+ if (exchange.status >= 200 && exchange.status < 300) return "acceptedUnreadable";
206
+ if (exchange.kind === "invalid") return "unknown";
207
+ if (exchange.status === 503) return "notApplied";
208
+ if (exchange.isErrorBodyTooLarge) return "unknown";
209
+ if (exchange.kind === "notFound" && exchange.status !== 410) return "notFound";
210
+ if (exchange.kind === "rejected" && definiteWriteRefusalStatuses.has(exchange.status)) return "rejected";
211
+ return "unknown";
212
+ }
213
+ function repeatableWriteFailure(exchange, output, receipt2) {
214
+ const outcome = classifyWrite(exchange);
215
+ if (outcome === "notFound") return newMutationBranch("notFound", output, receipt2, exchange.failure);
216
+ if (outcome === "rejected") return newMutationBranch("providerRejected", output, receipt2, exchange.failure);
217
+ if (outcome === "defect") return newMutationBranch("defect", output, receipt2, exchange.failure);
218
+ return newMutationRetry(exchange.failure, exchange.retryAfterMs);
219
+ }
196
220
  function defect(operation, output, message) {
197
221
  const cause = failure("VALIDATION", operation, message);
198
222
  return newQueryBranch("defect", output, {}, cause);
@@ -509,11 +533,11 @@ var UpdateTaskOperation = class {
509
533
  if (input.addAssigneeIds?.length || input.removeAssigneeIds?.length) payload.assignees = { add: input.addAssigneeIds ?? [], rem: input.removeAssigneeIds ?? [] };
510
534
  const result = await this.client.exchange(call, "updateTask", "PUT", path(input.taskId), void 0, payload);
511
535
  const responseReceipt = receipt(this.client, call, input.taskId);
512
- if (result.kind !== "succeeded") return mutationExchange(result, output, responseReceipt);
536
+ if (result.kind !== "succeeded") return repeatableWriteFailure(result, output, responseReceipt);
513
537
  try {
514
538
  return newMutationBranch("updated", { task: taskBody(result.response.body, false) }, responseReceipt);
515
539
  } catch {
516
- return failedDecode("updateTask", output, responseReceipt);
540
+ return newMutationRetry(failure("PROTOCOL", "updateTask", "ClickUp accepted the update but returned an invalid task"));
517
541
  }
518
542
  }
519
543
  };
@@ -551,35 +575,152 @@ var UpdateTaskTagsOperation = class {
551
575
  output.appliedChanges++;
552
576
  continue;
553
577
  }
554
- return mutationExchange(result2, output, responseReceipt);
578
+ return repeatableWriteFailure(result2, output, responseReceipt);
555
579
  }
556
580
  const result = await this.client.exchange(call, "updateTaskTags", "GET", path(input.taskId), void 0, void 0, operationSignal);
581
+ if (result.kind === "invalid") return newMutationRetry(result.failure);
557
582
  if (result.kind !== "succeeded") return mutationExchange(result, output, responseReceipt);
558
583
  try {
559
584
  output.tags = taskBody(result.response.body, false).tags;
560
585
  return newMutationBranch("updated", output, responseReceipt);
561
586
  } catch {
562
- return failedDecode("updateTaskTags", output, responseReceipt);
587
+ return newMutationRetry(failure("PROTOCOL", "updateTaskTags", "ClickUp applied the tag changes but returned an invalid task"));
563
588
  }
564
589
  }
565
590
  };
566
- function previousDispatch(call) {
567
- if (!call.context.hasLastHeartbeatValue()) return void 0;
568
- const value = call.context.getLastHeartbeatValue();
569
- if (value === null) return void 0;
570
- if (!value || typeof value !== "object") return { clickupDispatchedCallId: call.id, clickupDispatchedAt: 0 };
571
- const marker = value;
572
- return { clickupDispatchedCallId: String(marker.clickupDispatchedCallId ?? ""), clickupDispatchedAt: Number(marker.clickupDispatchedAt ?? 0) };
573
- }
574
- async function clearDispatch(call) {
575
- try {
576
- await call.context.recordHeartbeat(void 0);
577
- } catch {
578
- }
579
- }
591
+ var writeReconciliationSkewMs = 3e5;
592
+ var unknownWriteSettleMs = 5e3;
580
593
  function matchText(value) {
581
594
  return value.trim().replace(/\s+/g, " ");
582
595
  }
596
+ function readBackCreatedSince(call) {
597
+ const context = call.context;
598
+ const firstAttemptAt = context.firstAttemptAt instanceof Date ? context.firstAttemptAt : context.flowStartedAt;
599
+ if (!(firstAttemptAt instanceof Date)) return 0;
600
+ const since = firstAttemptAt.getTime() - writeReconciliationSkewMs;
601
+ return since > 0 ? since : 0;
602
+ }
603
+ var FencedWrite = class _FencedWrite {
604
+ constructor(operation, fence, decision) {
605
+ this.operation = operation;
606
+ this.fence = fence;
607
+ this.decision = decision;
608
+ this.hasPossibleEarlierSend = (decision.priorSendUpperBound ?? 0) > 0;
609
+ this.providerId = decision.marker?.providerId ?? "";
610
+ }
611
+ operation;
612
+ fence;
613
+ decision;
614
+ /** Whether an earlier send of this call may have taken effect. */
615
+ hasPossibleEarlierSend;
616
+ /** The identity an earlier accepted send saved, or an empty string. */
617
+ providerId;
618
+ /** Decide whether this attempt may send, or return the attempt that forbids it. */
619
+ static start(call, definition, operation, output) {
620
+ let fence;
621
+ try {
622
+ fence = newFence(call, 3e4, { maxSends: definitionMaxSends(definition) });
623
+ } catch {
624
+ return newMutationBranch("defect", output, {}, failure("LOCAL_DEFECT", operation, "ClickUp dispatch fence could not be constructed"));
625
+ }
626
+ const decision = fence.decide();
627
+ if (decision.kind === "failClosed") return newMutationRetry(failure("AVAILABILITY", operation, "the ClickUp dispatch checkpoint is unreadable, so nothing was sent in this attempt"));
628
+ return new _FencedWrite(operation, fence, decision);
629
+ }
630
+ /** Whether an earlier send may have taken effect, so this attempt reads back first; sendAllowed after canResend can carry earlier sends. */
631
+ get needsReadBack() {
632
+ return this.decision.kind !== "sendAllowed" || this.hasPossibleEarlierSend || this.providerId !== "";
633
+ }
634
+ /** Send once behind the fence, or return the Retry when the fence refuses to send. */
635
+ async dispatch(send) {
636
+ try {
637
+ return { exchange: await this.fence.dispatch(send) };
638
+ } catch {
639
+ return { attempt: newMutationRetry(failure("AVAILABILITY", this.operation, "the ClickUp dispatch checkpoint or request budget is unavailable, so nothing was sent")) };
640
+ }
641
+ }
642
+ /** Map a sent write without a 2xx; an unknown outcome retries so the next attempt reads back. */
643
+ async unaccepted(exchange, output, responseReceipt) {
644
+ const outcome = classifyWrite(exchange);
645
+ if (outcome === "notApplied") {
646
+ try {
647
+ await this.fence.recordCanResend();
648
+ } catch {
649
+ return newMutationRetry(failure("AVAILABILITY", this.operation, "ClickUp retry checkpoint could not be recorded"), exchange.retryAfterMs);
650
+ }
651
+ return newMutationRetry(exchange.failure, exchange.retryAfterMs);
652
+ }
653
+ if (outcome === "defect") {
654
+ try {
655
+ await this.fence.recordCanResend();
656
+ } catch {
657
+ }
658
+ if (!this.hasPossibleEarlierSend) return newMutationBranch("defect", output, responseReceipt, exchange.failure);
659
+ if (exchange.failure.kind === "AUTHENTICATION") return this.terminalCredentialFailure(output, exchange.failure);
660
+ return newMutationUncertain(output, exchange.failure, responseReceipt);
661
+ }
662
+ if (outcome === "notFound" || outcome === "rejected") {
663
+ if (this.hasPossibleEarlierSend) return newMutationUncertain(output, exchange.failure, responseReceipt);
664
+ try {
665
+ await this.fence.recordCanResend();
666
+ } catch {
667
+ return newMutationRetry(failure("AVAILABILITY", this.operation, "ClickUp rejection checkpoint could not be recorded"));
668
+ }
669
+ return newMutationBranch(outcome === "notFound" ? "notFound" : "providerRejected", output, responseReceipt, exchange.failure);
670
+ }
671
+ if (outcome === "acceptedUnreadable") {
672
+ return newMutationUncertain(output, failure(exchange.failure.kind, this.operation, `ClickUp accepted the write but its response is unusable, so it is not sent again: ${exchange.failure.message}`), responseReceipt);
673
+ }
674
+ return newMutationRetry(exchange.failure, Math.max(exchange.retryAfterMs, unknownWriteSettleMs));
675
+ }
676
+ /** Save the accepted identity so a replayed attempt never resends it. */
677
+ async recordAccepted(providerId) {
678
+ try {
679
+ await this.fence.recordProviderId(providerId);
680
+ } catch {
681
+ }
682
+ }
683
+ /** Retry an unusable 2xx only when its ID is saved, so the next attempt reads it back; otherwise select uncertain. */
684
+ async retryAcceptedReadBackOrSelectUncertain(providerId, output, responseReceipt, message) {
685
+ if (providerId) {
686
+ try {
687
+ await this.fence.recordProviderId(providerId);
688
+ return newMutationRetry(failure("PROTOCOL", this.operation, `${message}, so the next attempt reads it back`), unknownWriteSettleMs);
689
+ } catch {
690
+ }
691
+ }
692
+ return newMutationUncertain(output, failure("PROTOCOL", this.operation, `${message}, so it is not sent again`), responseReceipt);
693
+ }
694
+ /**
695
+ * Select uncertain for a terminal credential failure after a possible earlier send, without recording notSent.
696
+ * A transient credential failure arrives as `notSent` and retries instead.
697
+ */
698
+ terminalCredentialFailure(output, cause) {
699
+ return newMutationUncertain(output, failure(cause.kind, this.operation, `an earlier attempt of this Step may have sent the write and the connection credentials cannot read it back: ${cause.message}`), {});
700
+ }
701
+ /** Permit one send when the fence allows it after a read-back that confirmed nothing, and otherwise select uncertain. */
702
+ missingReadBack(output, responseReceipt, subject, cause) {
703
+ if ((this.decision.kind === "readBackThenResendAllowed" || this.decision.kind === "sendAllowed") && !this.providerId) return void 0;
704
+ const confirmed = subject === "create" ? "task" : subject;
705
+ return newMutationUncertain(output, failure(cause.kind, this.operation, `earlier attempts of this Step sent the ${subject} up to the send cap or were accepted, and read-back cannot confirm the ${confirmed}, so it is not sent again: ${cause.message}`), responseReceipt);
706
+ }
707
+ };
708
+ function createTaskPayload(input) {
709
+ const payload = { name: input.name };
710
+ if (input.isCreatorNotified) payload.notify_all = true;
711
+ if (input.markdownDescription) payload.markdown_content = input.markdownDescription;
712
+ if (input.status) payload.status = input.status;
713
+ if (input.priority) payload.priority = input.priority;
714
+ if (input.dueAt) {
715
+ payload.due_date = dateMilliseconds(input.dueAt);
716
+ payload.due_date_time = true;
717
+ }
718
+ if (input.assigneeIds?.length) payload.assignees = input.assigneeIds;
719
+ if (input.tags?.length) payload.tags = input.tags;
720
+ if (input.parentTaskId) payload.parent = input.parentTaskId;
721
+ if (input.customFields?.length) payload.custom_fields = input.customFields.map((field) => ({ id: field.id, value: field.value }));
722
+ return payload;
723
+ }
583
724
  var CreateTaskOperation = class {
584
725
  /** Bind a client. */
585
726
  constructor(client) {
@@ -594,7 +735,7 @@ var CreateTaskOperation = class {
594
735
  idempotencyKey(callId) {
595
736
  return callId;
596
737
  }
597
- /** Create or reconcile one task. */
738
+ /** Create, read back, or resend one task. */
598
739
  async invoke(call, input) {
599
740
  const output = { listId: input.listId, name: input.name, task: zeroTask };
600
741
  try {
@@ -612,66 +753,79 @@ var CreateTaskOperation = class {
612
753
  } catch (error) {
613
754
  return defect("createTask", output, String(error));
614
755
  }
615
- const prior = previousDispatch(call);
616
- if (prior) return this.reconcile(call, input, output, prior);
617
- try {
618
- await call.context.recordHeartbeat({ clickupDispatchedCallId: call.id, clickupDispatchedAt: this.client.currentTime().getTime() });
619
- } catch {
620
- return newMutationRetry(failure("AVAILABILITY", "createTask", "Dex did not record the dispatch checkpoint; nothing was sent"));
756
+ const write = FencedWrite.start(call, CreateTaskDefinition, "createTask", output);
757
+ if (!(write instanceof FencedWrite)) return write;
758
+ if (write.needsReadBack) {
759
+ const reconciled = await this.reconcile(call, input, output, write);
760
+ if (reconciled) return reconciled;
621
761
  }
622
- const payload = { name: input.name };
623
- if (input.isCreatorNotified) payload.notify_all = true;
624
- if (input.markdownDescription) payload.markdown_content = input.markdownDescription;
625
- if (input.status) payload.status = input.status;
626
- if (input.priority) payload.priority = input.priority;
627
- if (input.dueAt) {
628
- payload.due_date = dateMilliseconds(input.dueAt);
629
- payload.due_date_time = true;
630
- }
631
- if (input.assigneeIds?.length) payload.assignees = input.assigneeIds;
632
- if (input.tags?.length) payload.tags = input.tags;
633
- if (input.parentTaskId) payload.parent = input.parentTaskId;
634
- if (input.customFields?.length) payload.custom_fields = input.customFields.map((field) => ({ id: field.id, value: field.value }));
635
- const result = await this.client.exchange(call, "createTask", "POST", `/list/${input.listId}/task`, void 0, payload);
762
+ const payload = createTaskPayload(input);
763
+ const sent = await write.dispatch((signal) => this.client.exchange(call, "createTask", "POST", `/list/${input.listId}/task`, void 0, payload, signal));
764
+ if ("attempt" in sent) return sent.attempt;
765
+ const result = sent.exchange;
636
766
  const responseReceipt = receipt(this.client, call, input.listId);
637
- if (result.kind !== "succeeded") {
638
- if (result.kind === "notSent" || result.kind === "rateLimited") {
639
- await clearDispatch(call);
640
- return newMutationRetry(result.failure, result.retryAfterMs);
641
- }
642
- if (result.kind === "unconfirmed" || result.kind === "invalid") return newMutationRetry(result.failure, result.retryAfterMs);
643
- if (result.kind === "defect") await clearDispatch(call);
644
- return newMutationBranch(result.kind === "notFound" ? "notFound" : result.kind === "defect" ? "defect" : "providerRejected", output, responseReceipt, result.failure);
645
- }
767
+ if (result.kind !== "succeeded") return write.unaccepted(result, output, responseReceipt);
768
+ let task;
646
769
  try {
647
- const task = taskBody(result.response.body, false);
648
- return newMutationBranch("created", { ...output, task }, receipt(this.client, call, task.id));
770
+ task = taskBody(result.response.body, false);
649
771
  } catch {
650
- return newMutationRetry(failure("PROTOCOL", "createTask", "ClickUp accepted the task but returned an invalid task, so the next attempt reads the List back"));
772
+ return write.retryAcceptedReadBackOrSelectUncertain(createdTaskReference(result.response.body), output, responseReceipt, "ClickUp accepted the task but returned an invalid task");
651
773
  }
774
+ await write.recordAccepted(task.id);
775
+ return newMutationBranch("created", { ...output, task }, receipt(this.client, call, task.id));
652
776
  }
653
- async reconcile(call, input, output, marker) {
654
- const since = marker.clickupDispatchedAt > 0 ? marker.clickupDispatchedAt - 3e5 : 0;
777
+ /** Never send; return undefined when read-back confirmed nothing and the fence permits a resend. */
778
+ async reconcile(call, input, output, write) {
779
+ const responseReceipt = receipt(this.client, call, input.listId);
780
+ if (write.providerId) {
781
+ const result2 = await this.client.exchange(call, "createTask", "GET", path(write.providerId));
782
+ if (result2.kind !== "succeeded") {
783
+ if (isRetryable(result2)) return newMutationRetry(result2.failure, result2.retryAfterMs);
784
+ if (result2.kind === "defect") return write.terminalCredentialFailure(output, result2.failure);
785
+ return write.missingReadBack(output, responseReceipt, "create", result2.failure);
786
+ }
787
+ let task2;
788
+ try {
789
+ task2 = taskBody(result2.response.body, false);
790
+ if (task2.id !== write.providerId) throw new TypeError("another task");
791
+ } catch {
792
+ return write.missingReadBack(output, responseReceipt, "create", failure("PROTOCOL", "createTask", "the accepted task read back is invalid"));
793
+ }
794
+ return newMutationBranch("created", { ...output, task: task2, wasAlreadyApplied: true }, receipt(this.client, call, task2.id));
795
+ }
796
+ const since = readBackCreatedSince(call);
655
797
  const query = new URLSearchParams({ include_closed: "true", subtasks: "true", page: "0" });
656
798
  if (since > 0) query.set("date_created_gt", String(since));
657
799
  const result = await this.client.exchange(call, "createTask", "GET", `/list/${input.listId}/task`, query);
658
- const responseReceipt = receipt(this.client, call, input.listId);
659
800
  if (result.kind !== "succeeded") {
660
801
  if (isRetryable(result)) return newMutationRetry(result.failure, result.retryAfterMs);
661
- if (result.kind === "notFound") return newMutationBranch("notFound", output, responseReceipt, result.failure);
662
- return newMutationUncertain(output, failure(result.failure.kind, "createTask", "an earlier attempt of this Step sent the create, and the List could not be read back: " + result.failure.message), responseReceipt);
802
+ if (result.kind === "defect") return write.terminalCredentialFailure(output, result.failure);
803
+ if (result.kind === "notFound") return unreadableParentAfterPossibleSend("createTask", "created the task", "List", output, responseReceipt, result.failure);
804
+ return write.missingReadBack(output, responseReceipt, "create", result.failure);
663
805
  }
664
806
  let matches;
665
807
  try {
666
808
  matches = (searchPage(result.response.body, 0).tasks ?? []).filter((task2) => task2.name.trim() === input.name.trim() && (task2.parentTaskId ?? "") === (input.parentTaskId ?? "") && (!since || task2.createdAt !== void 0 && Date.parse(task2.createdAt) >= since));
667
809
  } catch {
668
- return newMutationUncertain(output, failure("PROTOCOL", "createTask", "an earlier attempt of this Step sent the create, and the List read back is invalid"), responseReceipt);
810
+ return write.missingReadBack(output, responseReceipt, "create", failure("PROTOCOL", "createTask", "the List read back is invalid"));
669
811
  }
670
- if (matches.length !== 1) return newMutationUncertain(output, failure("TRANSPORT", "createTask", `an earlier attempt of this Step sent the create without a confirmed outcome, and the List shows ${matches.length} tasks with the name created since, so it is not sent again`), responseReceipt);
812
+ if (!matches.length) return write.missingReadBack(output, responseReceipt, "create", failure("TRANSPORT", "createTask", "the List shows no task with the name created since"));
813
+ if (matches.length > 1) return newMutationUncertain(output, failure("TRANSPORT", "createTask", `an earlier attempt of this Step sent the create without a confirmed outcome, and the List shows ${matches.length} tasks with the name created since, so it is not sent again`), responseReceipt);
671
814
  const task = matches[0];
672
815
  return newMutationBranch("created", { ...output, task, wasAlreadyApplied: true }, receipt(this.client, call, task.id));
673
816
  }
674
817
  };
818
+ function unreadableParentAfterPossibleSend(operation, effect, parent, output, responseReceipt, cause) {
819
+ return newMutationUncertain(output, failure(cause.kind, operation, `an earlier attempt of this Step may have ${effect}, and the ${parent} can no longer be read back, so it is not sent again: ${cause.message}`), responseReceipt);
820
+ }
821
+ function createdTaskReference(body) {
822
+ try {
823
+ const id = decodeObject(body).id;
824
+ return typeof id === "string" && taskIdPattern.test(id) ? id : "";
825
+ } catch {
826
+ return "";
827
+ }
828
+ }
675
829
  var AddCommentOperation = class {
676
830
  /** Bind a client. */
677
831
  constructor(client) {
@@ -686,7 +840,7 @@ var AddCommentOperation = class {
686
840
  idempotencyKey(callId) {
687
841
  return callId;
688
842
  }
689
- /** Add or reconcile one comment. */
843
+ /** Add, read back, or resend one comment. */
690
844
  async invoke(call, input) {
691
845
  const output = { taskId: input.taskId };
692
846
  try {
@@ -695,52 +849,54 @@ var AddCommentOperation = class {
695
849
  } catch (error) {
696
850
  return defect("addComment", output, String(error));
697
851
  }
698
- const prior = previousDispatch(call);
699
- if (prior) return this.reconcile(call, input, output, prior);
700
- try {
701
- await call.context.recordHeartbeat({ clickupDispatchedCallId: call.id, clickupDispatchedAt: this.client.currentTime().getTime() });
702
- } catch {
703
- return newMutationRetry(failure("AVAILABILITY", "addComment", "Dex did not record the dispatch checkpoint; nothing was sent"));
852
+ const write = FencedWrite.start(call, AddCommentDefinition, "addComment", output);
853
+ if (!(write instanceof FencedWrite)) return write;
854
+ if (write.needsReadBack) {
855
+ const reconciled = await this.reconcile(call, input, output, write);
856
+ if (reconciled) return reconciled;
704
857
  }
705
- const result = await this.client.exchange(call, "addComment", "POST", `${path(input.taskId)}/comment`, void 0, { comment_text: input.text, notify_all: input.isCreatorNotified ?? false });
858
+ const sent = await write.dispatch((signal) => this.client.exchange(call, "addComment", "POST", `${path(input.taskId)}/comment`, void 0, { comment_text: input.text, notify_all: input.isCreatorNotified ?? false }, signal));
859
+ if ("attempt" in sent) return sent.attempt;
860
+ const result = sent.exchange;
706
861
  const responseReceipt = receipt(this.client, call, input.taskId);
707
- if (result.kind !== "succeeded") {
708
- if (result.kind === "notSent" || result.kind === "rateLimited") {
709
- await clearDispatch(call);
710
- return newMutationRetry(result.failure, result.retryAfterMs);
711
- }
712
- if (result.kind === "unconfirmed" || result.kind === "invalid") return newMutationRetry(result.failure, result.retryAfterMs);
713
- if (result.kind === "defect") await clearDispatch(call);
714
- return newMutationBranch(result.kind === "notFound" ? "notFound" : result.kind === "defect" ? "defect" : "providerRejected", output, responseReceipt, result.failure);
715
- }
862
+ if (result.kind !== "succeeded") return write.unaccepted(result, output, responseReceipt);
863
+ let id = "", createdAt;
716
864
  try {
717
865
  const data = decodeObject(result.response.body);
718
- const id = identifier(data.id);
719
- if (!taskIdPattern.test(id)) throw new TypeError("invalid comment ID");
720
- const createdAt = milliseconds(data.date);
721
- return newMutationBranch("added", { ...output, commentId: id, ...createdAt ? { createdAt } : {} }, { ...responseReceipt, metadata: { commentId: id } });
866
+ id = identifier(data.id);
867
+ if (!taskIdPattern.test(id)) {
868
+ id = "";
869
+ throw new TypeError("invalid comment ID");
870
+ }
871
+ createdAt = milliseconds(data.date);
722
872
  } catch {
723
- return newMutationRetry(failure("PROTOCOL", "addComment", "ClickUp accepted the comment but returned no valid comment ID, so the next attempt reads the comments back"));
873
+ return write.retryAcceptedReadBackOrSelectUncertain(id, output, responseReceipt, "ClickUp accepted the comment but returned an invalid comment");
724
874
  }
875
+ await write.recordAccepted(id);
876
+ return newMutationBranch("added", { ...output, commentId: id, ...createdAt ? { createdAt } : {} }, { ...responseReceipt, metadata: { commentId: id } });
725
877
  }
726
- async reconcile(call, input, output, marker) {
878
+ /** Never send; return undefined when read-back confirmed nothing and the fence permits a resend. */
879
+ async reconcile(call, input, output, write) {
727
880
  const result = await this.client.exchange(call, "addComment", "GET", `${path(input.taskId)}/comment`);
728
881
  const responseReceipt = receipt(this.client, call, input.taskId);
729
882
  if (result.kind !== "succeeded") {
730
883
  if (isRetryable(result)) return newMutationRetry(result.failure, result.retryAfterMs);
731
- if (result.kind === "notFound") return newMutationBranch("notFound", output, responseReceipt, result.failure);
732
- return newMutationUncertain(output, failure(result.failure.kind, "addComment", "an earlier attempt of this Step sent the comment, and the task's comments could not be read back: " + result.failure.message), responseReceipt);
884
+ if (result.kind === "defect") return write.terminalCredentialFailure(output, result.failure);
885
+ if (result.kind === "notFound") return unreadableParentAfterPossibleSend("addComment", "added the comment", "task", output, responseReceipt, result.failure);
886
+ return write.missingReadBack(output, responseReceipt, "comment", result.failure);
733
887
  }
734
888
  let matches;
735
889
  try {
736
890
  const data = decodeObject(result.response.body);
737
891
  if (!Array.isArray(data.comments)) throw new TypeError("missing comments");
738
- const since = marker.clickupDispatchedAt > 0 ? marker.clickupDispatchedAt - 3e5 : 0;
739
- matches = data.comments.map((value) => object(value)).filter((value) => matchText(String(value.comment_text ?? "")) === matchText(input.text) && (!since || milliseconds(value.date) !== void 0 && Date.parse(milliseconds(value.date)) >= since)).map((value) => ({ id: identifier(value.id), ...milliseconds(value.date) ? { createdAt: milliseconds(value.date) } : {} }));
892
+ const since = readBackCreatedSince(call);
893
+ const isSentByThisStep = (value) => write.providerId ? identifier(value.id) === write.providerId : matchText(String(value.comment_text ?? "")) === matchText(input.text) && (!since || milliseconds(value.date) !== void 0 && Date.parse(milliseconds(value.date)) >= since);
894
+ matches = data.comments.map((value) => object(value)).filter(isSentByThisStep).map((value) => ({ id: identifier(value.id), ...milliseconds(value.date) ? { createdAt: milliseconds(value.date) } : {} }));
740
895
  } catch {
741
- return newMutationUncertain(output, failure("PROTOCOL", "addComment", "an earlier attempt of this Step sent the comment, and the comments read back are invalid"), responseReceipt);
896
+ return write.missingReadBack(output, responseReceipt, "comment", failure("PROTOCOL", "addComment", "the comments read back are invalid"));
742
897
  }
743
- if (matches.length !== 1 || !taskIdPattern.test(matches[0].id)) return newMutationUncertain(output, failure("TRANSPORT", "addComment", `an earlier attempt of this Step sent the comment without a confirmed outcome, and the task shows ${matches.length} matching comments since, so it is not sent again`), responseReceipt);
898
+ if (matches.length > 1) return newMutationUncertain(output, failure("TRANSPORT", "addComment", `an earlier attempt of this Step sent the comment without a confirmed outcome, and the task shows ${matches.length} matching comments since, so it is not sent again`), responseReceipt);
899
+ if (!matches.length || !taskIdPattern.test(matches[0].id)) return write.missingReadBack(output, responseReceipt, "comment", failure("TRANSPORT", "addComment", "the task shows no matching comment"));
744
900
  const match = matches[0];
745
901
  return newMutationBranch("added", { ...output, commentId: match.id, ...match.createdAt ? { createdAt: match.createdAt } : {}, wasAlreadyApplied: true }, { ...responseReceipt, metadata: { commentId: match.id } });
746
902
  }
@@ -753,6 +909,12 @@ var ClickUpClient = class {
753
909
  endpoint;
754
910
  maxResponseBytes;
755
911
  credentials;
912
+ /** Largest accepted webhook body in bytes. */
913
+ webhookMaxBodyBytes;
914
+ /** Destination of Trigger records. */
915
+ triggerLogger;
916
+ /** Clock for webhook receipt times. */
917
+ triggerNow;
756
918
  send;
757
919
  now;
758
920
  /** Validate the client configuration without contacting ClickUp. */
@@ -761,6 +923,10 @@ var ClickUpClient = class {
761
923
  this.endpoint = validateBaseURL(options.apiBaseURL ?? apiBaseURL);
762
924
  this.maxResponseBytes = config.maxResponseBytes ?? defaultMaxResponseBytes;
763
925
  if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0) throw new TypeError("ClickUp maxResponseBytes must be positive");
926
+ this.webhookMaxBodyBytes = config.webhookMaxBodyBytes ?? 1048576;
927
+ if (!Number.isSafeInteger(this.webhookMaxBodyBytes) || this.webhookMaxBodyBytes <= 0) throw new TypeError("ClickUp webhookMaxBodyBytes must be positive");
928
+ this.triggerLogger = options.logger ?? defaultTriggerLogger;
929
+ this.triggerNow = options.now ?? (() => /* @__PURE__ */ new Date());
764
930
  this.credentials = credentials;
765
931
  this.send = options.send ?? sendProviderRequest;
766
932
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
@@ -809,15 +975,15 @@ var ClickUpClient = class {
809
975
  }
810
976
  /** Send a bounded API request and classify its response; signal can bound a multi-request operation. */
811
977
  async exchange(call, operation, method, path2, query, payload, signal = call.context.cancellationSignal) {
812
- let token;
978
+ let credentials;
813
979
  try {
814
- const credentials = await this.credentials.resolve(call, signal);
815
- if (!(credentials.apiToken instanceof SecretString)) throw new TypeError("missing token");
816
- token = credentials.apiToken.reveal();
817
- if (!isHeaderSafeCredential(token) || !token.startsWith("pk_") || token.length <= 3) throw new TypeError("invalid token");
818
- } catch {
819
- return this.outcome("defect", operation, "AUTHENTICATION", "ClickUp connection credentials are unavailable");
980
+ credentials = await this.credentials.resolve(call, signal);
981
+ } catch (error) {
982
+ if (isTerminalCredentialError(error)) return this.outcome("defect", operation, "AUTHENTICATION", "ClickUp connection credentials are missing or need reauthorization");
983
+ return this.outcome("notSent", operation, "AVAILABILITY", "ClickUp connection credentials could not be read, so nothing was sent");
820
984
  }
985
+ const token = credentials.apiToken instanceof SecretString ? credentials.apiToken.reveal() : "";
986
+ if (!isHeaderSafeCredential(token) || !token.startsWith("pk_") || token.length <= 3) return this.outcome("defect", operation, "AUTHENTICATION", "ClickUp connection credentials are invalid");
821
987
  let body;
822
988
  try {
823
989
  if (payload !== void 0) body = Buffer.from(JSON.stringify(payload));
@@ -837,26 +1003,36 @@ var ClickUpClient = class {
837
1003
  signal
838
1004
  });
839
1005
  } catch (error) {
840
- if (error instanceof BodyTooLargeError) return this.outcome("invalid", operation, "RESPONSE_TOO_LARGE", "ClickUp response exceeds the configured maxResponseBytes limit");
1006
+ const status = error instanceof BodyTooLargeError || error instanceof ProviderTransportError || error instanceof ProviderStalledError ? error.status ?? 0 : 0;
1007
+ const isSuccessStatus = status >= 200 && status < 300;
1008
+ if (error instanceof BodyTooLargeError && (isSuccessStatus || status === 0)) return this.outcome("invalid", operation, "RESPONSE_TOO_LARGE", "ClickUp response exceeds the configured maxResponseBytes limit", 0, status);
1009
+ if (error instanceof BodyTooLargeError) {
1010
+ const classified = this.classifyFailureStatus(operation, { status, headers: error.headers ?? {}, body: new Uint8Array() });
1011
+ return classified.kind === "succeeded" ? classified : { ...classified, isErrorBodyTooLarge: true };
1012
+ }
841
1013
  if (error instanceof ProviderTransportError && error.isProvablyNotSent) return this.outcome("notSent", operation, "TRANSPORT", "ClickUp could not be reached; no request was sent");
1014
+ if (isSuccessStatus) return this.outcome("unconfirmed", operation, "TRANSPORT", "ClickUp response could not be read", 0, status);
842
1015
  return this.outcome("unconfirmed", operation, "TRANSPORT", "ClickUp request failed before a response arrived");
843
1016
  }
844
1017
  if (response.status >= 200 && response.status < 300) {
845
- if (Buffer.from(response.body).includes(Buffer.from(token))) return this.outcome("invalid", operation, "PROTOCOL", "ClickUp response reflected the connection credential");
1018
+ if (Buffer.from(response.body).includes(Buffer.from(token))) return this.outcome("invalid", operation, "PROTOCOL", "ClickUp response reflected the connection credential", 0, response.status);
846
1019
  return { kind: "succeeded", response };
847
1020
  }
1021
+ return this.classifyFailureStatus(operation, response);
1022
+ }
1023
+ classifyFailureStatus(operation, response) {
848
1024
  const status = response.status;
849
1025
  const code = readErrorCode(response.body);
850
1026
  const withCode = (message) => message + (code ? ` [${code}]` : "");
851
- if (status === 429) return this.outcome("rateLimited", operation, "RATE_LIMIT", withCode("ClickUp rate limited the token (HTTP 429)"), this.rateLimitDelay(response));
852
- if (status === 408 || status >= 500) return this.outcome("unconfirmed", operation, "AVAILABILITY", withCode(`ClickUp could not complete the request (HTTP ${status})`));
853
- if (status === 404 || status === 410) return this.outcome("notFound", operation, "NOT_FOUND", withCode(`ClickUp found no such resource (HTTP ${status})`));
1027
+ if (status === 429) return this.outcome("rateLimited", operation, "RATE_LIMIT", withCode("ClickUp rate limited the token (HTTP 429)"), this.rateLimitDelay(response), status);
1028
+ if (status === 408 || status >= 500) return this.outcome("unconfirmed", operation, "AVAILABILITY", withCode(`ClickUp could not complete the request (HTTP ${status})`), 0, status);
1029
+ if (status === 404 || status === 410) return this.outcome("notFound", operation, "NOT_FOUND", withCode(`ClickUp found no such resource (HTTP ${status})`), 0, status);
854
1030
  if (status === 401 && ["OAUTH_023", "OAUTH_026", "OAUTH_027", ...Array.from({ length: 17 }, (_, index) => `OAUTH_${String(index + 29).padStart(3, "0")}`)].includes(code))
855
- return this.outcome("notFound", operation, "AUTHORIZATION", withCode("ClickUp reports that the resource's Workspace is not authorized for the token (HTTP 401)"));
856
- if (status >= 300 && status < 400) return this.outcome("rejected", operation, "PROTOCOL", `ClickUp redirected the request (HTTP ${status})`);
857
- if (status === 401) return this.outcome("rejected", operation, "AUTHENTICATION", withCode("ClickUp rejected the personal API token (HTTP 401)"));
1031
+ return this.outcome("notFound", operation, "AUTHORIZATION", withCode("ClickUp reports that the resource's Workspace is not authorized for the token (HTTP 401)"), 0, status);
1032
+ if (status >= 300 && status < 400) return this.outcome("rejected", operation, "PROTOCOL", `ClickUp redirected the request (HTTP ${status})`, 0, status);
1033
+ if (status === 401) return this.outcome("rejected", operation, "AUTHENTICATION", withCode("ClickUp rejected the personal API token (HTTP 401)"), 0, status);
858
1034
  const kind = status === 403 ? "AUTHORIZATION" : status === 409 ? "CONFLICT" : [400, 422].includes(status) ? "VALIDATION" : "PROVIDER_REJECTION";
859
- return this.outcome("rejected", operation, kind, withCode(`ClickUp rejected the request (HTTP ${status})`));
1035
+ return this.outcome("rejected", operation, kind, withCode(`ClickUp rejected the request (HTTP ${status})`), 0, status);
860
1036
  }
861
1037
  rateLimitDelay(response) {
862
1038
  const header = (name) => {
@@ -868,10 +1044,13 @@ var ClickUpClient = class {
868
1044
  const reset = Number(header("x-ratelimit-reset"));
869
1045
  return Number.isSafeInteger(reset) && reset > 0 ? Math.min(6e4, Math.max(1e3, reset * 1e3 - this.now().getTime())) : 0;
870
1046
  }
871
- outcome(kind, operation, failureKind, message, retryAfterMs = 0) {
872
- return { kind, failure: { kind: failureKind, provider: "clickup", operation, message }, retryAfterMs };
1047
+ outcome(kind, operation, failureKind, message, retryAfterMs = 0, status = 0) {
1048
+ return { kind, failure: { kind: failureKind, provider: "clickup", operation, message }, retryAfterMs, status };
873
1049
  }
874
1050
  };
1051
+ function isTerminalCredentialError(error) {
1052
+ return error instanceof ReauthorizationRequiredError || error instanceof ConnectionNotSelectedError || error instanceof CredentialBrokerRejectedError || error instanceof ObjectNotFoundError || isCredentialMaterialError(error);
1053
+ }
875
1054
  function readErrorCode(body) {
876
1055
  try {
877
1056
  const value = JSON.parse(Buffer.from(body).toString());
@@ -882,7 +1061,7 @@ function readErrorCode(body) {
882
1061
  }
883
1062
 
884
1063
  // src/project.ts
885
- function newProjectConnection2(project, connectionName) {
1064
+ function newProjectConnection2(project, connectionName, options = {}) {
886
1065
  return newProjectConnection(project, connectionName, (loadedProject, name) => {
887
1066
  const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "clickup" && entry.connectionName === name);
888
1067
  if (!selected) throw new TypeError("ClickUp project connection is not configured");
@@ -895,9 +1074,309 @@ function newProjectConnection2(project, connectionName) {
895
1074
  return { apiToken: new SecretString2(decoded.api_token), ...decoded.webhook_secret ? { webhookSecret: new SecretString2(decoded.webhook_secret) } : {} };
896
1075
  }
897
1076
  };
898
- return new ClickUpClient(config, credentials);
1077
+ return new ClickUpClient(config, credentials, options);
1078
+ });
1079
+ }
1080
+
1081
+ // src/trigger.ts
1082
+ import { createHmac, timingSafeEqual } from "crypto";
1083
+ import {
1084
+ mustTriggerBindingDefinition,
1085
+ newTrigger
1086
+ } from "@superdurable/connectors-sdk";
1087
+ import {
1088
+ decodeTriggerConfiguration,
1089
+ newDurableTriggerTarget
1090
+ } from "@superdurable/connectors-sdk/projectconfig";
1091
+ import {
1092
+ WebhookEndpoint,
1093
+ WebhookEndpointRunner,
1094
+ WebhookVerificationUnavailableError
1095
+ } from "@superdurable/connectors-sdk/webhooktrigger";
1096
+ import { z as z2 } from "zod";
1097
+ var TaskEvents = [
1098
+ "taskCreated",
1099
+ "taskUpdated",
1100
+ "taskDeleted",
1101
+ "taskPriorityUpdated",
1102
+ "taskStatusUpdated",
1103
+ "taskAssigneeUpdated",
1104
+ "taskDueDateUpdated",
1105
+ "taskTagUpdated",
1106
+ "taskMoved",
1107
+ "taskCommentPosted",
1108
+ "taskCommentUpdated",
1109
+ "taskTimeEstimateUpdated",
1110
+ "taskTimeTrackedUpdated"
1111
+ ];
1112
+ var TaskEventTriggerConfigurationSchema = z2.strictObject({ events: z2.array(z2.string()).nullable().optional() }).superRefine((configuration, context) => {
1113
+ const events = configuration.events ?? [];
1114
+ if (events.some((event) => !TaskEvents.includes(event)) || new Set(events).size !== events.length)
1115
+ context.addIssue({
1116
+ code: "custom",
1117
+ message: "ClickUp webhook events must be distinct supported task events"
1118
+ });
1119
+ });
1120
+ var tokenJSON = JSON;
1121
+ function decodeNumberTokens(text) {
1122
+ return JSON.parse(
1123
+ text,
1124
+ (_key, value, context) => typeof value === "number" && context?.source ? tokenJSON.rawJSON(context.source) : value
1125
+ );
1126
+ }
1127
+ function positiveUserId(value) {
1128
+ const text = flexibleIdentifier(value);
1129
+ if (!text) return void 0;
1130
+ if (!/^[+-]?\d+$/.test(text)) throw new TypeError("ClickUp user ID must be an integer");
1131
+ const number = BigInt(text);
1132
+ if (number < -(1n << 63n) || number >= 1n << 63n)
1133
+ throw new TypeError("ClickUp user ID is outside signed 64-bit range");
1134
+ if (number <= 0n) return void 0;
1135
+ return number <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(number) : tokenJSON.rawJSON(String(number));
1136
+ }
1137
+ var TaskHistoryItemSchema = z2.object({
1138
+ id: z2.string(),
1139
+ field: z2.string(),
1140
+ occurredAt: z2.string().optional(),
1141
+ userId: z2.union([
1142
+ z2.number().int().positive(),
1143
+ z2.custom(
1144
+ (value) => tokenJSON.isRawJSON(value) && /^[1-9]\d*$/.test(value.rawJSON) && BigInt(value.rawJSON) < 1n << 63n
1145
+ )
1146
+ ]).optional(),
1147
+ parentId: z2.string().optional(),
1148
+ statusBefore: z2.string().optional(),
1149
+ statusAfter: z2.string().optional()
1150
+ });
1151
+ var TaskEventSchema = z2.object({
1152
+ eventId: z2.string(),
1153
+ webhookId: z2.string(),
1154
+ event: z2.string(),
1155
+ taskId: z2.string(),
1156
+ historyItems: z2.array(TaskHistoryItemSchema),
1157
+ occurredAt: z2.string()
1158
+ });
1159
+ var TaskEventTriggerDefinition = {
1160
+ trigger: { connectorId: ConnectorID, triggerName: "taskEvent" },
1161
+ description: "Receive one signed ClickUp task webhook event filtered by event name."
1162
+ };
1163
+ var UIUnitTaskEventPicker = "taskEventPicker";
1164
+ var UITaskEventPickerPortEvents = "events";
1165
+ function defineTaskEventTriggerBinding(config) {
1166
+ return mustTriggerBindingDefinition({ definition: TaskEventTriggerDefinition, ...config });
1167
+ }
1168
+ function newTaskEventTrigger(config) {
1169
+ if (config.connectionName !== config.connection.reference.name)
1170
+ throw new TypeError("ClickUp taskEvent connection name does not match its connection");
1171
+ const client = clickupClientOf(config.connection);
1172
+ const configuration = TaskEventTriggerConfigurationSchema.parse(config.configuration);
1173
+ const source = webhookEndpoint(client, config.connection.reference).newSource(
1174
+ (event) => !configuration.events?.length || configuration.events.includes(event.payload.event)
1175
+ );
1176
+ const definition = TaskEventTriggerDefinition;
1177
+ return newTrigger({
1178
+ definition,
1179
+ binding: {
1180
+ connection: config.connection.reference,
1181
+ trigger: definition.trigger,
1182
+ name: config.bindingName
1183
+ },
1184
+ source,
1185
+ target: config.target,
1186
+ logger: client.triggerLogger
899
1187
  });
900
1188
  }
1189
+ function taskEventWebhookHandler(connection) {
1190
+ return webhookEndpoint(clickupClientOf(connection), connection.reference);
1191
+ }
1192
+ var TaskEventEndpointRunner = class {
1193
+ /** @internal Construct through newProjectTaskEventEndpointRunner. */
1194
+ constructor(endpoint, runners) {
1195
+ this.endpoint = endpoint;
1196
+ this.#runner = new WebhookEndpointRunner(endpoint, runners);
1197
+ }
1198
+ endpoint;
1199
+ #runner;
1200
+ /** Verify, record, and acknowledge one delivery, or answer 503 until pending events have replayed. */
1201
+ serveHTTP(request, response) {
1202
+ return this.#runner.serveHTTP(request, response);
1203
+ }
1204
+ /** Replay durable inboxes, then deliver new events until stopped. */
1205
+ run(context) {
1206
+ return this.#runner.run(context);
1207
+ }
1208
+ /** Number of bindings ready to receive. */
1209
+ runningSourceCount() {
1210
+ return this.endpoint.runningSourceCount();
1211
+ }
1212
+ };
1213
+ function newProjectTaskEventEndpointRunner(project, connectionName, routes, options = {}) {
1214
+ if (routes.length === 0) throw new TypeError("ClickUp taskEvent routes are required");
1215
+ const connection = newProjectConnection2(project, connectionName, options);
1216
+ const client = clickupClientOf(connection);
1217
+ const triggerName = TaskEventTriggerDefinition.trigger.triggerName;
1218
+ const bindingNames = /* @__PURE__ */ new Set();
1219
+ const runners = routes.map((route) => {
1220
+ const bindingName = route.bindingName?.trim() ?? "";
1221
+ if (!bindingName || !route.target)
1222
+ throw new TypeError("ClickUp taskEvent binding name and target are required");
1223
+ if (bindingNames.has(bindingName))
1224
+ throw new TypeError(`ClickUp taskEvent binding name "${bindingName}" is duplicated`);
1225
+ bindingNames.add(bindingName);
1226
+ const key = { connectorId: ConnectorID, connectionName, triggerName, bindingName };
1227
+ const configuration = decodeTriggerConfiguration(
1228
+ project.configuration,
1229
+ key,
1230
+ TaskEventTriggerConfigurationSchema
1231
+ );
1232
+ const inbox = project.triggerInbox(key);
1233
+ const durable = newDurableTriggerTarget(inbox, key, route.target, {
1234
+ logger: client.triggerLogger,
1235
+ decodePayload(text) {
1236
+ return TaskEventSchema.parse(
1237
+ JSON.parse(
1238
+ text,
1239
+ (name, value, context) => name === "userId" && typeof value === "number" && context?.source ? positiveUserId(context.source) : value
1240
+ )
1241
+ );
1242
+ }
1243
+ });
1244
+ const target = {
1245
+ async prepareTrigger(context, event) {
1246
+ if (!event.payload.historyItems?.some((item) => tokenJSON.isRawJSON(item.userId))) {
1247
+ await durable.prepareTrigger(context, event);
1248
+ return;
1249
+ }
1250
+ context.signal.throwIfAborted();
1251
+ await inbox.add({
1252
+ id: event.id,
1253
+ event: Buffer.from(
1254
+ JSON.stringify({ eventId: event.id, occurredAt: event.occurredAt, payload: event.payload })
1255
+ )
1256
+ });
1257
+ },
1258
+ handleTrigger: (context, event) => durable.handleTrigger(context, event),
1259
+ replayTriggerDeliveries: (context) => durable.replayTriggerDeliveries(context)
1260
+ };
1261
+ return newTaskEventTrigger({ connection, connectionName, bindingName, configuration, target });
1262
+ });
1263
+ return new TaskEventEndpointRunner(webhookEndpoint(client, connection.reference), runners);
1264
+ }
1265
+ var endpoints = /* @__PURE__ */ new WeakMap();
1266
+ function webhookEndpoint(client, connection) {
1267
+ let byConnection = endpoints.get(client);
1268
+ if (!byConnection) {
1269
+ byConnection = /* @__PURE__ */ new Map();
1270
+ endpoints.set(client, byConnection);
1271
+ }
1272
+ const key = `${connection.provider}\0${connection.name}`;
1273
+ let endpoint = byConnection.get(key);
1274
+ if (!endpoint) {
1275
+ endpoint = new WebhookEndpoint({
1276
+ connectorId: ConnectorID,
1277
+ triggerName: "taskEvent",
1278
+ connection,
1279
+ credentials: client.credentials,
1280
+ maxBodyBytes: client.webhookMaxBodyBytes,
1281
+ verifyRequest,
1282
+ decodeEvent,
1283
+ now: client.triggerNow,
1284
+ logger: client.triggerLogger
1285
+ });
1286
+ byConnection.set(key, endpoint);
1287
+ }
1288
+ return endpoint;
1289
+ }
1290
+ function clickupClientOf(connection) {
1291
+ if (!(connection?.operations instanceof ClickUpClient))
1292
+ throw new TypeError("ClickUp Triggers require a ClickUpClient connection");
1293
+ return connection.operations;
1294
+ }
1295
+ async function verifyRequest(request, credentials) {
1296
+ const secret = credentials.webhookSecret?.reveal() ?? "";
1297
+ if (!secret) throw new WebhookVerificationUnavailableError();
1298
+ const header = request.headers["x-signature"];
1299
+ const signatureText = (Array.isArray(header) ? header[0] : header)?.trim() ?? "";
1300
+ if (!/^[0-9a-fA-F]{64}$/.test(signatureText)) throw new TypeError("invalid X-Signature");
1301
+ const expected = createHmac("sha256", secret).update(request.body).digest();
1302
+ if (!timingSafeEqual(Buffer.from(signatureText, "hex"), expected))
1303
+ throw new TypeError("X-Signature does not match the body");
1304
+ }
1305
+ function decodeEvent(request) {
1306
+ const wire = decodeNumberTokens(Buffer.from(request.body).toString("utf8"));
1307
+ if (!wire || typeof wire !== "object" || Array.isArray(wire))
1308
+ throw new TypeError("ClickUp webhook body is not a JSON object");
1309
+ const fields = wire;
1310
+ const event = fields.event;
1311
+ const webhookId = fields.webhook_id;
1312
+ if (typeof event !== "string" || !event || typeof webhookId !== "string" || !isPrintableIdentifier(webhookId))
1313
+ throw new TypeError("ClickUp webhook event has no event name or webhook_id");
1314
+ if (!TaskEvents.includes(event)) return void 0;
1315
+ const taskId = flexibleIdentifier(fields.task_id);
1316
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(taskId))
1317
+ throw new TypeError("ClickUp task event has no valid task_id");
1318
+ const rawHistory = fields.history_items;
1319
+ if (rawHistory != null && !Array.isArray(rawHistory))
1320
+ throw new TypeError("ClickUp history items are invalid");
1321
+ const historyItems = (rawHistory ?? []).slice(0, 20).map(decodeHistoryItem);
1322
+ const occurredAt = historyItems[0]?.occurredAt ?? goTimeJSON(request.receivedAt);
1323
+ const eventId = `${webhookId}:${event}:${historyItems[0]?.id ?? taskId}`;
1324
+ return {
1325
+ id: eventId,
1326
+ occurredAt: new Date(occurredAt),
1327
+ payload: { eventId, webhookId, event, taskId, historyItems, occurredAt }
1328
+ };
1329
+ }
1330
+ function decodeHistoryItem(value) {
1331
+ if (!value || typeof value !== "object" || Array.isArray(value))
1332
+ throw new TypeError("ClickUp history item is invalid");
1333
+ const wire = value;
1334
+ const id = flexibleIdentifier(wire.id);
1335
+ if (!isPrintableIdentifier(id)) throw new TypeError("ClickUp history item has no valid id");
1336
+ if (wire.field != null && typeof wire.field !== "string")
1337
+ throw new TypeError("ClickUp history item field is invalid");
1338
+ const field = wire.field ?? "";
1339
+ const occurredAt = unixMilliseconds(wire.date);
1340
+ if (wire.user != null && (typeof wire.user !== "object" || Array.isArray(wire.user) || tokenJSON.isRawJSON(wire.user)))
1341
+ throw new TypeError("Invalid ClickUp history user");
1342
+ const user = wire.user ?? {};
1343
+ const userId = positiveUserId(user.id);
1344
+ const statusBefore = field === "status" ? statusName(wire.before) : "";
1345
+ const statusAfter = field === "status" ? statusName(wire.after) : "";
1346
+ return {
1347
+ id,
1348
+ field,
1349
+ ...occurredAt ? { occurredAt } : {},
1350
+ ...userId !== void 0 ? { userId } : {},
1351
+ ...wire.parent_id != null ? { parentId: flexibleIdentifier(wire.parent_id) } : {},
1352
+ ...statusBefore ? { statusBefore } : {},
1353
+ ...statusAfter ? { statusAfter } : {}
1354
+ };
1355
+ }
1356
+ function flexibleIdentifier(value) {
1357
+ if (value == null) return "";
1358
+ if (typeof value === "string") return value;
1359
+ if (tokenJSON.isRawJSON(value)) return value.rawJSON;
1360
+ if (typeof value === "number" && Number.isSafeInteger(value)) return String(value);
1361
+ throw new TypeError("ClickUp identifier is not a string or number");
1362
+ }
1363
+ function unixMilliseconds(value) {
1364
+ if (value == null || value === "") return void 0;
1365
+ const text = flexibleIdentifier(value);
1366
+ if (!/^\d+$/.test(text)) throw new TypeError("ClickUp time is not Unix milliseconds");
1367
+ const milliseconds2 = Number(text);
1368
+ if (!Number.isSafeInteger(milliseconds2)) throw new TypeError("ClickUp time is not Unix milliseconds");
1369
+ return milliseconds2 > 0 ? goTimeJSON(new Date(milliseconds2)) : void 0;
1370
+ }
1371
+ function goTimeJSON(value) {
1372
+ return value.toISOString().replace(/\.000Z$/, "Z");
1373
+ }
1374
+ function statusName(value) {
1375
+ return value && typeof value === "object" && !Array.isArray(value) && typeof value.status === "string" ? value.status : "";
1376
+ }
1377
+ function isPrintableIdentifier(value) {
1378
+ return value.length > 0 && Buffer.byteLength(value) <= 64 && /^[!-~]+$/.test(value) && !value.includes(":");
1379
+ }
901
1380
  export {
902
1381
  AddCommentBranch,
903
1382
  AddCommentBranchAdded,
@@ -925,6 +1404,7 @@ export {
925
1404
  CreateTaskMetadata,
926
1405
  CreateTaskOperation,
927
1406
  CreateTaskOutputSchema,
1407
+ CredentialMaterialError,
928
1408
  CustomFieldInputSchema,
929
1409
  CustomFieldValueSchema,
930
1410
  FindMemberByEmailBranch,
@@ -960,8 +1440,16 @@ export {
960
1440
  SearchTasksMetadata,
961
1441
  SearchTasksOperation,
962
1442
  SearchTasksOutputSchema,
1443
+ TaskEventEndpointRunner,
1444
+ TaskEventSchema,
1445
+ TaskEventTriggerConfigurationSchema,
1446
+ TaskEventTriggerDefinition,
1447
+ TaskEvents,
1448
+ TaskHistoryItemSchema,
963
1449
  TaskSchema,
964
1450
  TaskStatusSchema,
1451
+ UITaskEventPickerPortEvents,
1452
+ UIUnitTaskEventPicker,
965
1453
  UpdateTaskBranch,
966
1454
  UpdateTaskBranchDefect,
967
1455
  UpdateTaskBranchInvalidResponse,
@@ -986,6 +1474,8 @@ export {
986
1474
  UpdateTaskTagsOutputSchema,
987
1475
  UserSchema,
988
1476
  decodeCredentials,
1477
+ defineTaskEventTriggerBinding,
1478
+ isCredentialMaterialError,
989
1479
  newAddCommentStep,
990
1480
  newConnection,
991
1481
  newConnectionWithOperations,
@@ -993,7 +1483,10 @@ export {
993
1483
  newFindMemberByEmailStep,
994
1484
  newGetTaskStep,
995
1485
  newProjectConnection2 as newProjectConnection,
1486
+ newProjectTaskEventEndpointRunner,
996
1487
  newSearchTasksStep,
1488
+ newTaskEventTrigger,
997
1489
  newUpdateTaskStep,
998
- newUpdateTaskTagsStep
1490
+ newUpdateTaskTagsStep,
1491
+ taskEventWebhookHandler
999
1492
  };