@superdurable/connector-clickup 0.1.1 → 0.1.3

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,
@@ -77,10 +78,12 @@ import {
77
78
  UpdateTaskTagsMetadata,
78
79
  UpdateTaskTagsOutputSchema,
79
80
  UserSchema,
81
+ decodeCredentials,
82
+ isCredentialMaterialError,
80
83
  newConnection,
81
84
  newConnectionWithOperations,
82
85
  newProjectConnection
83
- } from "./chunk-5MZPRO45.js";
86
+ } from "./chunk-PQCNNSDL.js";
84
87
 
85
88
  // src/generated/steps.ts
86
89
  import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
@@ -118,7 +121,7 @@ function newCreateTaskStep(configuration) {
118
121
  ] });
119
122
  }
120
123
  function newUpdateTaskStep(configuration) {
121
- const { connection, connectionName, updated, notFound, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
124
+ const { connection, connectionName, updated, notFound, providerRejected, invalidResponse, defect: defect2, maxSends, ...stepConfiguration } = configuration;
122
125
  if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
123
126
  return newMutationStep({ ...stepConfiguration, operation: connection.operations.updateTask(), connection: connection.reference, branches: [
124
127
  goToBranch("updated", updated),
@@ -129,7 +132,7 @@ function newUpdateTaskStep(configuration) {
129
132
  ] });
130
133
  }
131
134
  function newUpdateTaskTagsStep(configuration) {
132
- const { connection, connectionName, updated, notFound, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
135
+ const { connection, connectionName, updated, notFound, providerRejected, invalidResponse, defect: defect2, maxSends, ...stepConfiguration } = configuration;
133
136
  if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
134
137
  return newMutationStep({ ...stepConfiguration, operation: connection.operations.updateTaskTags(), connection: connection.reference, branches: [
135
138
  goToBranch("updated", updated),
@@ -167,11 +170,13 @@ import { SecretString as SecretString2 } from "@superdurable/connectors-sdk";
167
170
  import { z } from "zod";
168
171
 
169
172
  // src/client.ts
170
- import { BodyTooLargeError, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
171
- import { SecretString } from "@superdurable/connectors-sdk";
173
+ import { BodyTooLargeError, ProviderStalledError, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
174
+ import { ReauthorizationRequiredError, SecretString } from "@superdurable/connectors-sdk";
175
+ import { ConnectionNotSelectedError, CredentialBrokerRejectedError, ObjectNotFoundError } from "@superdurable/connectors-sdk/projectconfig";
172
176
 
173
177
  // src/operations.ts
174
- 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";
175
180
  var taskIdPattern = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
176
181
  var numericIdPattern = /^[0-9]{1,20}$/;
177
182
  var zeroTask = { id: "", name: "", status: { name: "" }, assignees: [], tags: [] };
@@ -192,6 +197,26 @@ function mutationExchange(exchange, output, receipt2, hasInvalidResponse = true)
192
197
  const branch = exchange.kind === "notFound" ? "notFound" : exchange.kind === "invalid" && hasInvalidResponse ? "invalidResponse" : exchange.kind === "defect" ? "defect" : "providerRejected";
193
198
  return newMutationBranch(branch, output, receipt2, exchange.failure);
194
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
+ }
195
220
  function defect(operation, output, message) {
196
221
  const cause = failure("VALIDATION", operation, message);
197
222
  return newQueryBranch("defect", output, {}, cause);
@@ -508,11 +533,11 @@ var UpdateTaskOperation = class {
508
533
  if (input.addAssigneeIds?.length || input.removeAssigneeIds?.length) payload.assignees = { add: input.addAssigneeIds ?? [], rem: input.removeAssigneeIds ?? [] };
509
534
  const result = await this.client.exchange(call, "updateTask", "PUT", path(input.taskId), void 0, payload);
510
535
  const responseReceipt = receipt(this.client, call, input.taskId);
511
- if (result.kind !== "succeeded") return mutationExchange(result, output, responseReceipt);
536
+ if (result.kind !== "succeeded") return repeatableWriteFailure(result, output, responseReceipt);
512
537
  try {
513
538
  return newMutationBranch("updated", { task: taskBody(result.response.body, false) }, responseReceipt);
514
539
  } catch {
515
- return failedDecode("updateTask", output, responseReceipt);
540
+ return newMutationRetry(failure("PROTOCOL", "updateTask", "ClickUp accepted the update but returned an invalid task"));
516
541
  }
517
542
  }
518
543
  };
@@ -550,35 +575,152 @@ var UpdateTaskTagsOperation = class {
550
575
  output.appliedChanges++;
551
576
  continue;
552
577
  }
553
- return mutationExchange(result2, output, responseReceipt);
578
+ return repeatableWriteFailure(result2, output, responseReceipt);
554
579
  }
555
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);
556
582
  if (result.kind !== "succeeded") return mutationExchange(result, output, responseReceipt);
557
583
  try {
558
584
  output.tags = taskBody(result.response.body, false).tags;
559
585
  return newMutationBranch("updated", output, responseReceipt);
560
586
  } catch {
561
- return failedDecode("updateTaskTags", output, responseReceipt);
587
+ return newMutationRetry(failure("PROTOCOL", "updateTaskTags", "ClickUp applied the tag changes but returned an invalid task"));
562
588
  }
563
589
  }
564
590
  };
565
- function previousDispatch(call) {
566
- if (!call.context.hasLastHeartbeatValue()) return void 0;
567
- const value = call.context.getLastHeartbeatValue();
568
- if (value === null) return void 0;
569
- if (!value || typeof value !== "object") return { clickupDispatchedCallId: call.id, clickupDispatchedAt: 0 };
570
- const marker = value;
571
- return { clickupDispatchedCallId: String(marker.clickupDispatchedCallId ?? ""), clickupDispatchedAt: Number(marker.clickupDispatchedAt ?? 0) };
572
- }
573
- async function clearDispatch(call) {
574
- try {
575
- await call.context.recordHeartbeat(null);
576
- } catch {
577
- }
578
- }
591
+ var writeReconciliationSkewMs = 3e5;
592
+ var unknownWriteSettleMs = 5e3;
579
593
  function matchText(value) {
580
594
  return value.trim().replace(/\s+/g, " ");
581
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
+ }
582
724
  var CreateTaskOperation = class {
583
725
  /** Bind a client. */
584
726
  constructor(client) {
@@ -593,7 +735,7 @@ var CreateTaskOperation = class {
593
735
  idempotencyKey(callId) {
594
736
  return callId;
595
737
  }
596
- /** Create or reconcile one task. */
738
+ /** Create, read back, or resend one task. */
597
739
  async invoke(call, input) {
598
740
  const output = { listId: input.listId, name: input.name, task: zeroTask };
599
741
  try {
@@ -611,66 +753,79 @@ var CreateTaskOperation = class {
611
753
  } catch (error) {
612
754
  return defect("createTask", output, String(error));
613
755
  }
614
- const prior = previousDispatch(call);
615
- if (prior) return this.reconcile(call, input, output, prior);
616
- try {
617
- await call.context.recordHeartbeat({ clickupDispatchedCallId: call.id, clickupDispatchedAt: this.client.currentTime().getTime() });
618
- } catch {
619
- return newMutationRetry(failure("AVAILABILITY", "createTask", "Dex did not record the dispatch checkpoint; nothing was sent"));
620
- }
621
- const payload = { name: input.name };
622
- if (input.isCreatorNotified) payload.notify_all = true;
623
- if (input.markdownDescription) payload.markdown_content = input.markdownDescription;
624
- if (input.status) payload.status = input.status;
625
- if (input.priority) payload.priority = input.priority;
626
- if (input.dueAt) {
627
- payload.due_date = dateMilliseconds(input.dueAt);
628
- payload.due_date_time = true;
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;
629
761
  }
630
- if (input.assigneeIds?.length) payload.assignees = input.assigneeIds;
631
- if (input.tags?.length) payload.tags = input.tags;
632
- if (input.parentTaskId) payload.parent = input.parentTaskId;
633
- if (input.customFields?.length) payload.custom_fields = input.customFields.map((field) => ({ id: field.id, value: field.value }));
634
- 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;
635
766
  const responseReceipt = receipt(this.client, call, input.listId);
636
- if (result.kind !== "succeeded") {
637
- if (result.kind === "notSent" || result.kind === "rateLimited") {
638
- await clearDispatch(call);
639
- return newMutationRetry(result.failure, result.retryAfterMs);
640
- }
641
- if (result.kind === "unconfirmed" || result.kind === "invalid") return newMutationRetry(result.failure, result.retryAfterMs);
642
- if (result.kind === "defect") await clearDispatch(call);
643
- return newMutationBranch(result.kind === "notFound" ? "notFound" : result.kind === "defect" ? "defect" : "providerRejected", output, responseReceipt, result.failure);
644
- }
767
+ if (result.kind !== "succeeded") return write.unaccepted(result, output, responseReceipt);
768
+ let task;
645
769
  try {
646
- const task = taskBody(result.response.body, false);
647
- return newMutationBranch("created", { ...output, task }, receipt(this.client, call, task.id));
770
+ task = taskBody(result.response.body, false);
648
771
  } catch {
649
- 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");
650
773
  }
774
+ await write.recordAccepted(task.id);
775
+ return newMutationBranch("created", { ...output, task }, receipt(this.client, call, task.id));
651
776
  }
652
- async reconcile(call, input, output, marker) {
653
- 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);
654
797
  const query = new URLSearchParams({ include_closed: "true", subtasks: "true", page: "0" });
655
798
  if (since > 0) query.set("date_created_gt", String(since));
656
799
  const result = await this.client.exchange(call, "createTask", "GET", `/list/${input.listId}/task`, query);
657
- const responseReceipt = receipt(this.client, call, input.listId);
658
800
  if (result.kind !== "succeeded") {
659
801
  if (isRetryable(result)) return newMutationRetry(result.failure, result.retryAfterMs);
660
- if (result.kind === "notFound") return newMutationBranch("notFound", output, responseReceipt, result.failure);
661
- 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);
662
805
  }
663
806
  let matches;
664
807
  try {
665
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));
666
809
  } catch {
667
- 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"));
668
811
  }
669
- 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);
670
814
  const task = matches[0];
671
815
  return newMutationBranch("created", { ...output, task, wasAlreadyApplied: true }, receipt(this.client, call, task.id));
672
816
  }
673
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
+ }
674
829
  var AddCommentOperation = class {
675
830
  /** Bind a client. */
676
831
  constructor(client) {
@@ -685,7 +840,7 @@ var AddCommentOperation = class {
685
840
  idempotencyKey(callId) {
686
841
  return callId;
687
842
  }
688
- /** Add or reconcile one comment. */
843
+ /** Add, read back, or resend one comment. */
689
844
  async invoke(call, input) {
690
845
  const output = { taskId: input.taskId };
691
846
  try {
@@ -694,52 +849,54 @@ var AddCommentOperation = class {
694
849
  } catch (error) {
695
850
  return defect("addComment", output, String(error));
696
851
  }
697
- const prior = previousDispatch(call);
698
- if (prior) return this.reconcile(call, input, output, prior);
699
- try {
700
- await call.context.recordHeartbeat({ clickupDispatchedCallId: call.id, clickupDispatchedAt: this.client.currentTime().getTime() });
701
- } catch {
702
- 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;
703
857
  }
704
- 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;
705
861
  const responseReceipt = receipt(this.client, call, input.taskId);
706
- if (result.kind !== "succeeded") {
707
- if (result.kind === "notSent" || result.kind === "rateLimited") {
708
- await clearDispatch(call);
709
- return newMutationRetry(result.failure, result.retryAfterMs);
710
- }
711
- if (result.kind === "unconfirmed" || result.kind === "invalid") return newMutationRetry(result.failure, result.retryAfterMs);
712
- if (result.kind === "defect") await clearDispatch(call);
713
- return newMutationBranch(result.kind === "notFound" ? "notFound" : result.kind === "defect" ? "defect" : "providerRejected", output, responseReceipt, result.failure);
714
- }
862
+ if (result.kind !== "succeeded") return write.unaccepted(result, output, responseReceipt);
863
+ let id = "", createdAt;
715
864
  try {
716
865
  const data = decodeObject(result.response.body);
717
- const id = identifier(data.id);
718
- if (!taskIdPattern.test(id)) throw new TypeError("invalid comment ID");
719
- const createdAt = milliseconds(data.date);
720
- 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);
721
872
  } catch {
722
- 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");
723
874
  }
875
+ await write.recordAccepted(id);
876
+ return newMutationBranch("added", { ...output, commentId: id, ...createdAt ? { createdAt } : {} }, { ...responseReceipt, metadata: { commentId: id } });
724
877
  }
725
- 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) {
726
880
  const result = await this.client.exchange(call, "addComment", "GET", `${path(input.taskId)}/comment`);
727
881
  const responseReceipt = receipt(this.client, call, input.taskId);
728
882
  if (result.kind !== "succeeded") {
729
883
  if (isRetryable(result)) return newMutationRetry(result.failure, result.retryAfterMs);
730
- if (result.kind === "notFound") return newMutationBranch("notFound", output, responseReceipt, result.failure);
731
- 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);
732
887
  }
733
888
  let matches;
734
889
  try {
735
890
  const data = decodeObject(result.response.body);
736
891
  if (!Array.isArray(data.comments)) throw new TypeError("missing comments");
737
- const since = marker.clickupDispatchedAt > 0 ? marker.clickupDispatchedAt - 3e5 : 0;
738
- 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) } : {} }));
739
895
  } catch {
740
- 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"));
741
897
  }
742
- 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"));
743
900
  const match = matches[0];
744
901
  return newMutationBranch("added", { ...output, commentId: match.id, ...match.createdAt ? { createdAt: match.createdAt } : {}, wasAlreadyApplied: true }, { ...responseReceipt, metadata: { commentId: match.id } });
745
902
  }
@@ -808,15 +965,15 @@ var ClickUpClient = class {
808
965
  }
809
966
  /** Send a bounded API request and classify its response; signal can bound a multi-request operation. */
810
967
  async exchange(call, operation, method, path2, query, payload, signal = call.context.cancellationSignal) {
811
- let token;
968
+ let credentials;
812
969
  try {
813
- const credentials = await this.credentials.resolve(call, signal);
814
- if (!(credentials.apiToken instanceof SecretString)) throw new TypeError("missing token");
815
- token = credentials.apiToken.reveal();
816
- if (!isHeaderSafeCredential(token) || !token.startsWith("pk_") || token.length <= 3) throw new TypeError("invalid token");
817
- } catch {
818
- return this.outcome("defect", operation, "AUTHENTICATION", "ClickUp connection credentials are unavailable");
970
+ credentials = await this.credentials.resolve(call, signal);
971
+ } catch (error) {
972
+ if (isTerminalCredentialError(error)) return this.outcome("defect", operation, "AUTHENTICATION", "ClickUp connection credentials are missing or need reauthorization");
973
+ return this.outcome("notSent", operation, "AVAILABILITY", "ClickUp connection credentials could not be read, so nothing was sent");
819
974
  }
975
+ const token = credentials.apiToken instanceof SecretString ? credentials.apiToken.reveal() : "";
976
+ if (!isHeaderSafeCredential(token) || !token.startsWith("pk_") || token.length <= 3) return this.outcome("defect", operation, "AUTHENTICATION", "ClickUp connection credentials are invalid");
820
977
  let body;
821
978
  try {
822
979
  if (payload !== void 0) body = Buffer.from(JSON.stringify(payload));
@@ -836,26 +993,36 @@ var ClickUpClient = class {
836
993
  signal
837
994
  });
838
995
  } catch (error) {
839
- if (error instanceof BodyTooLargeError) return this.outcome("invalid", operation, "RESPONSE_TOO_LARGE", "ClickUp response exceeds the configured maxResponseBytes limit");
996
+ const status = error instanceof BodyTooLargeError || error instanceof ProviderTransportError || error instanceof ProviderStalledError ? error.status ?? 0 : 0;
997
+ const isSuccessStatus = status >= 200 && status < 300;
998
+ if (error instanceof BodyTooLargeError && (isSuccessStatus || status === 0)) return this.outcome("invalid", operation, "RESPONSE_TOO_LARGE", "ClickUp response exceeds the configured maxResponseBytes limit", 0, status);
999
+ if (error instanceof BodyTooLargeError) {
1000
+ const classified = this.classifyFailureStatus(operation, { status, headers: error.headers ?? {}, body: new Uint8Array() });
1001
+ return classified.kind === "succeeded" ? classified : { ...classified, isErrorBodyTooLarge: true };
1002
+ }
840
1003
  if (error instanceof ProviderTransportError && error.isProvablyNotSent) return this.outcome("notSent", operation, "TRANSPORT", "ClickUp could not be reached; no request was sent");
1004
+ if (isSuccessStatus) return this.outcome("unconfirmed", operation, "TRANSPORT", "ClickUp response could not be read", 0, status);
841
1005
  return this.outcome("unconfirmed", operation, "TRANSPORT", "ClickUp request failed before a response arrived");
842
1006
  }
843
1007
  if (response.status >= 200 && response.status < 300) {
844
- if (Buffer.from(response.body).includes(Buffer.from(token))) return this.outcome("invalid", operation, "PROTOCOL", "ClickUp response reflected the connection credential");
1008
+ if (Buffer.from(response.body).includes(Buffer.from(token))) return this.outcome("invalid", operation, "PROTOCOL", "ClickUp response reflected the connection credential", 0, response.status);
845
1009
  return { kind: "succeeded", response };
846
1010
  }
1011
+ return this.classifyFailureStatus(operation, response);
1012
+ }
1013
+ classifyFailureStatus(operation, response) {
847
1014
  const status = response.status;
848
1015
  const code = readErrorCode(response.body);
849
1016
  const withCode = (message) => message + (code ? ` [${code}]` : "");
850
- if (status === 429) return this.outcome("rateLimited", operation, "RATE_LIMIT", withCode("ClickUp rate limited the token (HTTP 429)"), this.rateLimitDelay(response));
851
- if (status === 408 || status >= 500) return this.outcome("unconfirmed", operation, "AVAILABILITY", withCode(`ClickUp could not complete the request (HTTP ${status})`));
852
- if (status === 404 || status === 410) return this.outcome("notFound", operation, "NOT_FOUND", withCode(`ClickUp found no such resource (HTTP ${status})`));
1017
+ if (status === 429) return this.outcome("rateLimited", operation, "RATE_LIMIT", withCode("ClickUp rate limited the token (HTTP 429)"), this.rateLimitDelay(response), status);
1018
+ if (status === 408 || status >= 500) return this.outcome("unconfirmed", operation, "AVAILABILITY", withCode(`ClickUp could not complete the request (HTTP ${status})`), 0, status);
1019
+ if (status === 404 || status === 410) return this.outcome("notFound", operation, "NOT_FOUND", withCode(`ClickUp found no such resource (HTTP ${status})`), 0, status);
853
1020
  if (status === 401 && ["OAUTH_023", "OAUTH_026", "OAUTH_027", ...Array.from({ length: 17 }, (_, index) => `OAUTH_${String(index + 29).padStart(3, "0")}`)].includes(code))
854
- return this.outcome("notFound", operation, "AUTHORIZATION", withCode("ClickUp reports that the resource's Workspace is not authorized for the token (HTTP 401)"));
855
- if (status >= 300 && status < 400) return this.outcome("rejected", operation, "PROTOCOL", `ClickUp redirected the request (HTTP ${status})`);
856
- if (status === 401) return this.outcome("rejected", operation, "AUTHENTICATION", withCode("ClickUp rejected the personal API token (HTTP 401)"));
1021
+ return this.outcome("notFound", operation, "AUTHORIZATION", withCode("ClickUp reports that the resource's Workspace is not authorized for the token (HTTP 401)"), 0, status);
1022
+ if (status >= 300 && status < 400) return this.outcome("rejected", operation, "PROTOCOL", `ClickUp redirected the request (HTTP ${status})`, 0, status);
1023
+ if (status === 401) return this.outcome("rejected", operation, "AUTHENTICATION", withCode("ClickUp rejected the personal API token (HTTP 401)"), 0, status);
857
1024
  const kind = status === 403 ? "AUTHORIZATION" : status === 409 ? "CONFLICT" : [400, 422].includes(status) ? "VALIDATION" : "PROVIDER_REJECTION";
858
- return this.outcome("rejected", operation, kind, withCode(`ClickUp rejected the request (HTTP ${status})`));
1025
+ return this.outcome("rejected", operation, kind, withCode(`ClickUp rejected the request (HTTP ${status})`), 0, status);
859
1026
  }
860
1027
  rateLimitDelay(response) {
861
1028
  const header = (name) => {
@@ -867,10 +1034,13 @@ var ClickUpClient = class {
867
1034
  const reset = Number(header("x-ratelimit-reset"));
868
1035
  return Number.isSafeInteger(reset) && reset > 0 ? Math.min(6e4, Math.max(1e3, reset * 1e3 - this.now().getTime())) : 0;
869
1036
  }
870
- outcome(kind, operation, failureKind, message, retryAfterMs = 0) {
871
- return { kind, failure: { kind: failureKind, provider: "clickup", operation, message }, retryAfterMs };
1037
+ outcome(kind, operation, failureKind, message, retryAfterMs = 0, status = 0) {
1038
+ return { kind, failure: { kind: failureKind, provider: "clickup", operation, message }, retryAfterMs, status };
872
1039
  }
873
1040
  };
1041
+ function isTerminalCredentialError(error) {
1042
+ return error instanceof ReauthorizationRequiredError || error instanceof ConnectionNotSelectedError || error instanceof CredentialBrokerRejectedError || error instanceof ObjectNotFoundError || isCredentialMaterialError(error);
1043
+ }
874
1044
  function readErrorCode(body) {
875
1045
  try {
876
1046
  const value = JSON.parse(Buffer.from(body).toString());
@@ -924,6 +1094,7 @@ export {
924
1094
  CreateTaskMetadata,
925
1095
  CreateTaskOperation,
926
1096
  CreateTaskOutputSchema,
1097
+ CredentialMaterialError,
927
1098
  CustomFieldInputSchema,
928
1099
  CustomFieldValueSchema,
929
1100
  FindMemberByEmailBranch,
@@ -984,6 +1155,8 @@ export {
984
1155
  UpdateTaskTagsOperation,
985
1156
  UpdateTaskTagsOutputSchema,
986
1157
  UserSchema,
1158
+ decodeCredentials,
1159
+ isCredentialMaterialError,
987
1160
  newAddCommentStep,
988
1161
  newConnection,
989
1162
  newConnectionWithOperations,
package/dist/mock.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { MockQuery, MockMutation, Case } from '@superdurable/connectors-sdk/connectormock';
2
2
  import { Failure } from '@superdurable/connectors-sdk';
3
- import { O as Operations, C as Connection, S as SearchTasksInput, d as SearchTasksOutput, G as GetTaskInput, T as Task, b as CreateTaskInput, c as CreateTaskOutput, U as UpdateTaskInput, e as UpdateTaskOutput, f as UpdateTaskTagsInput, g as UpdateTaskTagsOutput, A as AddCommentInput, a as AddCommentOutput, F as FindMemberByEmailInput, M as Member, p as CustomFieldInput, r as CustomFieldValue, z as TaskStatus, J as User } from './connection-DYuseKLI.js';
3
+ import { O as Operations, C as Connection, S as SearchTasksInput, d as SearchTasksOutput, G as GetTaskInput, T as Task, b as CreateTaskInput, c as CreateTaskOutput, U as UpdateTaskInput, e as UpdateTaskOutput, f as UpdateTaskTagsInput, g as UpdateTaskTagsOutput, A as AddCommentInput, a as AddCommentOutput, F as FindMemberByEmailInput, M as Member, q as CustomFieldInput, s as CustomFieldValue, B as TaskStatus, K as User } from './connection-CyZGpZRT.js';
4
4
  import 'zod';
5
5
 
6
6
  /** Go zero value for SearchTasksInput in scripted cases. */
package/dist/mock.js CHANGED
@@ -27,7 +27,7 @@ import {
27
27
  UpdateTaskTagsOutputSchema,
28
28
  UserSchema,
29
29
  newConnectionWithOperations
30
- } from "./chunk-5MZPRO45.js";
30
+ } from "./chunk-PQCNNSDL.js";
31
31
 
32
32
  // src/generated/mock.ts
33
33
  import { branchCase, retryCase, uncertainCase, newMutation, newQuery } from "@superdurable/connectors-sdk/connectormock";