@superdurable/connector-google-gmail 0.2.1 → 0.3.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/README.md +14 -2
- package/dex-connector.json +27 -3
- package/dist/{chunk-KVNIQW5Y.js → chunk-PW3NTBVH.js} +466 -23
- package/dist/index.cjs +468 -22
- package/dist/index.d.cts +218 -6
- package/dist/index.d.ts +218 -6
- package/dist/index.js +39 -1
- package/dist/mock/index.cjs +75 -2
- package/dist/mock/index.js +1 -1
- package/package.json +5 -4
package/dist/index.cjs
CHANGED
|
@@ -33,8 +33,15 @@ __export(index_exports, {
|
|
|
33
33
|
GmailMessageResourceSchema: () => GmailMessageResourceSchema,
|
|
34
34
|
GmailProvider: () => GmailProvider,
|
|
35
35
|
GoogleOAuthAuthMethodID: () => GoogleOAuthAuthMethodID,
|
|
36
|
+
MessageEventSchema: () => MessageEventSchema,
|
|
37
|
+
MessageMatcherSchema: () => MessageMatcherSchema,
|
|
38
|
+
MessageReceivedTriggerConfigurationSchema: () => MessageReceivedTriggerConfigurationSchema,
|
|
39
|
+
MessageReceivedTriggerDefinition: () => MessageReceivedTriggerDefinition,
|
|
36
40
|
MessageSchema: () => MessageSchema,
|
|
41
|
+
MessageTriggerRunner: () => MessageTriggerRunner,
|
|
37
42
|
ProviderID: () => ProviderID,
|
|
43
|
+
ReplyReceivedTriggerConfigurationSchema: () => ReplyReceivedTriggerConfigurationSchema,
|
|
44
|
+
ReplyReceivedTriggerDefinition: () => ReplyReceivedTriggerDefinition,
|
|
38
45
|
ReplyToMessageBranch: () => ReplyToMessageBranch,
|
|
39
46
|
ReplyToMessageDefinition: () => ReplyToMessageDefinition,
|
|
40
47
|
ReplyToMessageInputSchema: () => ReplyToMessageInputSchema,
|
|
@@ -44,18 +51,30 @@ __export(index_exports, {
|
|
|
44
51
|
SendMessageInputSchema: () => SendMessageInputSchema2,
|
|
45
52
|
SendMessageOperation: () => SendMessageOperation,
|
|
46
53
|
SendMessageOutputSchema: () => SendMessageOutputSchema2,
|
|
54
|
+
UIEmailListInputPortEmails: () => UIEmailListInputPortEmails,
|
|
55
|
+
UISearchQueryInputPortQuery: () => UISearchQueryInputPortQuery,
|
|
56
|
+
UITextInputPortText: () => UITextInputPortText,
|
|
57
|
+
UIUnitEmailListInput: () => UIUnitEmailListInput,
|
|
58
|
+
UIUnitSearchQueryInput: () => UIUnitSearchQueryInput,
|
|
59
|
+
UIUnitTextInput: () => UIUnitTextInput,
|
|
47
60
|
WorkspaceDomainDelegationAuthMethodID: () => WorkspaceDomainDelegationAuthMethodID,
|
|
48
61
|
buildMIMEMessage: () => buildMIMEMessage,
|
|
49
62
|
buildReplyMIMEMessage: () => buildReplyMIMEMessage,
|
|
50
63
|
decodeGmailMessage: () => decodeGmailMessage,
|
|
64
|
+
defineMessageReceivedTriggerBinding: () => defineMessageReceivedTriggerBinding,
|
|
65
|
+
defineReplyReceivedTriggerBinding: () => defineReplyReceivedTriggerBinding,
|
|
51
66
|
emptyMessage: () => emptyMessage,
|
|
52
67
|
gmailClientSettings: () => gmailClientSettings,
|
|
53
68
|
gmailFailure: () => gmailFailure,
|
|
54
69
|
gmailRequestID: () => gmailRequestID,
|
|
55
70
|
gmailRetryAfterMs: () => gmailRetryAfterMs,
|
|
56
71
|
newGetMessageStep: () => newGetMessageStep2,
|
|
72
|
+
newMessageReceivedTrigger: () => newMessageReceivedTrigger,
|
|
73
|
+
newMessageTriggerRunner: () => newMessageTriggerRunner,
|
|
57
74
|
newProjectConnection: () => newProjectConnection,
|
|
58
75
|
newProjectGmailClient: () => newProjectGmailClient,
|
|
76
|
+
newProjectMessageTriggerRunner: () => newProjectMessageTriggerRunner,
|
|
77
|
+
newReplyReceivedTrigger: () => newReplyReceivedTrigger,
|
|
59
78
|
newReplyToMessageStep: () => newReplyToMessageStep2,
|
|
60
79
|
newSendMessageStep: () => newSendMessageStep2,
|
|
61
80
|
parseMailbox: () => parseMailbox,
|
|
@@ -276,7 +295,9 @@ var SendMessageDefinition = {
|
|
|
276
295
|
{ id: "providerRejected", description: "Gmail conclusively rejected the message.", optional: true },
|
|
277
296
|
{ id: "defect", description: "Local input, connection configuration, or connector definition is invalid.", optional: true }
|
|
278
297
|
],
|
|
279
|
-
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 5, totalDurationMs: 12e4 } }
|
|
298
|
+
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 5, totalDurationMs: 12e4 } },
|
|
299
|
+
repeatOnUnknown: "limited",
|
|
300
|
+
maxSends: 3
|
|
280
301
|
};
|
|
281
302
|
var ReplyToMessageBranch = {
|
|
282
303
|
Sent: "sent",
|
|
@@ -296,7 +317,9 @@ var ReplyToMessageDefinition = {
|
|
|
296
317
|
{ id: "invalidResponse", description: "Gmail returned an invalid or oversized source message response before sending the reply.", optional: true },
|
|
297
318
|
{ id: "defect", description: "Local input, connection configuration, or connector definition is invalid.", optional: true }
|
|
298
319
|
],
|
|
299
|
-
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 5, totalDurationMs: 12e4 } }
|
|
320
|
+
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 5, totalDurationMs: 12e4 } },
|
|
321
|
+
repeatOnUnknown: "limited",
|
|
322
|
+
maxSends: 3
|
|
300
323
|
};
|
|
301
324
|
|
|
302
325
|
// src/message.ts
|
|
@@ -338,7 +361,8 @@ function decodeGmailMessage(resource) {
|
|
|
338
361
|
...textBodies.length ? { textBody: textBodies.join("\n") } : {},
|
|
339
362
|
...htmlBodies.length ? { htmlBody: htmlBodies.join("\n") } : {},
|
|
340
363
|
...resource.snippet ? { snippet: resource.snippet } : {},
|
|
341
|
-
|
|
364
|
+
// Go's time.Time JSON (RFC 3339 with trailing fractional zeros removed), such as .12Z for 120 ms.
|
|
365
|
+
receivedAt: receivedAt.toISOString().replace(/\.(\d*?)0*Z$/, (_match, digits) => digits ? `.${digits}Z` : "Z"),
|
|
342
366
|
...resource.labelIds?.length ? { labelIds: resource.labelIds } : {}
|
|
343
367
|
};
|
|
344
368
|
}
|
|
@@ -417,7 +441,8 @@ function validateSendInput(input, sender) {
|
|
|
417
441
|
return recipients;
|
|
418
442
|
}
|
|
419
443
|
function rfcMessageIDAddress(idempotencyKey, runId, flowStartedAt) {
|
|
420
|
-
|
|
444
|
+
if (!runId) throw new TypeError("Dex run ID is required");
|
|
445
|
+
const runIdentity = flowStartedAt instanceof Date && Number.isFinite(flowStartedAt.getTime()) ? `${runId}\0${Math.floor(flowStartedAt.getTime() / 1e3)}` : `${runId}\0no-flow-start`;
|
|
421
446
|
return `${(0, import_node_crypto.createHash)("sha256").update(`${idempotencyKey}\0${runIdentity}`).digest("hex")}@dex.superdurable.dev`;
|
|
422
447
|
}
|
|
423
448
|
function buildMIMEMessage(callId, idempotencyKey, messageIdAddress, sender, recipients, subject, textBody, htmlBody = "", replyHeaders) {
|
|
@@ -483,9 +508,11 @@ function gmailClientSettings(config = {}) {
|
|
|
483
508
|
if (!Number.isSafeInteger(maxResponseBytes) || maxResponseBytes < 1 || !Number.isSafeInteger(maxMessageBytes) || maxMessageBytes < 1) {
|
|
484
509
|
throw new TypeError("Gmail response and message limits must be positive integers");
|
|
485
510
|
}
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
511
|
+
const pollIntervalMs = config.pollIntervalMs ?? 1e4;
|
|
512
|
+
const pollPageSize = config.pollPageSize ?? 25;
|
|
513
|
+
if (!Number.isSafeInteger(pollIntervalMs) || pollIntervalMs < 1e3) throw new TypeError("Gmail poll interval is invalid");
|
|
514
|
+
if (!Number.isSafeInteger(pollPageSize) || pollPageSize < 1 || pollPageSize > 100) throw new TypeError("Gmail poll page size is invalid");
|
|
515
|
+
return Object.freeze({ endpoint, maxResponseBytes, maxMessageBytes, addressPolicy: endpoint.startsWith("http://") ? "privateNetworkHTTP" : "publicHTTPS", pollIntervalMs, pollPageSize });
|
|
489
516
|
}
|
|
490
517
|
var GmailCredentialError = class extends Error {
|
|
491
518
|
constructor() {
|
|
@@ -594,6 +621,7 @@ function validateCredentials(credentials) {
|
|
|
594
621
|
var import_zod4 = require("zod");
|
|
595
622
|
var SentMessageSchema = import_zod4.z.object({ id: import_zod4.z.string().optional(), threadId: import_zod4.z.string().optional() });
|
|
596
623
|
var SentSearchSchema = import_zod4.z.object({ messages: import_zod4.z.array(SentMessageSchema).nullish() });
|
|
624
|
+
var MessageListSchema = import_zod4.z.object({ messages: import_zod4.z.array(import_zod4.z.object({ id: import_zod4.z.string().nullish(), threadId: import_zod4.z.string().nullish() })).nullish() });
|
|
597
625
|
var GmailProvider = class {
|
|
598
626
|
#http;
|
|
599
627
|
/** Bind the shared authenticated transport. */
|
|
@@ -618,6 +646,23 @@ var GmailProvider = class {
|
|
|
618
646
|
return result;
|
|
619
647
|
}
|
|
620
648
|
}
|
|
649
|
+
/**
|
|
650
|
+
* List the newest inbox page that matches searchQuery, as the Go Trigger poller does. It rejects with
|
|
651
|
+
* an error that names no query value when Gmail does not answer 2xx with a usable listing.
|
|
652
|
+
*/
|
|
653
|
+
async listInboxMessages(call, credentials, searchQuery, pageSize, signal) {
|
|
654
|
+
const query = new URLSearchParams({ labelIds: "INBOX", maxResults: String(pageSize) });
|
|
655
|
+
if (searchQuery.trim()) query.set("q", searchQuery);
|
|
656
|
+
const result = await this.#http.request(call, credentials, "GET", `/users/me/messages?${query.toString()}`, void 0, signal);
|
|
657
|
+
if (result.response.status < 200 || result.response.status >= 300) throw new Error("Gmail message list is unavailable");
|
|
658
|
+
let parsed;
|
|
659
|
+
try {
|
|
660
|
+
parsed = MessageListSchema.parse(JSON.parse(Buffer.from(result.response.body).toString("utf8")));
|
|
661
|
+
} catch {
|
|
662
|
+
throw new Error("Gmail message list is invalid");
|
|
663
|
+
}
|
|
664
|
+
return { messages: (parsed.messages ?? []).map((message) => ({ id: message.id ?? "", threadId: message.threadId ?? "" })), credentials: result.credentials };
|
|
665
|
+
}
|
|
621
666
|
/** Search Sent Mail once for the run-specific RFC Message-ID. */
|
|
622
667
|
async findSentMessage(call, credentials, messageIdAddress, signal) {
|
|
623
668
|
const query = new URLSearchParams();
|
|
@@ -880,6 +925,7 @@ var ReplyToMessageOutcomes = {
|
|
|
880
925
|
sentBranch: ReplyToMessageBranch.Sent,
|
|
881
926
|
providerRejectedBranch: ReplyToMessageBranch.ProviderRejected
|
|
882
927
|
};
|
|
928
|
+
var MissingRunIDMessage = "the Dex call context has no run ID, so nothing was sent";
|
|
883
929
|
var GmailSendAttemptBudget = class {
|
|
884
930
|
/** Read-back cutoff in Unix milliseconds. */
|
|
885
931
|
attemptDeadline;
|
|
@@ -970,6 +1016,8 @@ var GmailSender = class {
|
|
|
970
1016
|
/** Send one new message under the Dex attempt deadline. */
|
|
971
1017
|
async sendMessage(call, input, dexDeadline) {
|
|
972
1018
|
if (call.context.attempt < 1) return defect("sendMessage", "LOCAL_DEFECT", "Dex Execute attempt number is invalid");
|
|
1019
|
+
const messageIdAddress = this.#messageID(call);
|
|
1020
|
+
if (!messageIdAddress) return defect("sendMessage", "LOCAL_DEFECT", MissingRunIDMessage);
|
|
973
1021
|
const fence = (0, import_singledispatch.newFence)(call, SendMessageDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4);
|
|
974
1022
|
if (fence.decide().kind === "failClosed") return defect("sendMessage", "LOCAL_DEFECT", "Dex send checkpoint is unreadable");
|
|
975
1023
|
const budget = new GmailSendAttemptBudget(call.context.cancellationSignal, dexDeadline);
|
|
@@ -992,16 +1040,18 @@ var GmailSender = class {
|
|
|
992
1040
|
}
|
|
993
1041
|
let raw;
|
|
994
1042
|
try {
|
|
995
|
-
raw = buildMIMEMessage(call.id, call.idempotencyKey ?? call.id,
|
|
1043
|
+
raw = buildMIMEMessage(call.id, call.idempotencyKey ?? call.id, messageIdAddress, credentials.primaryEmail, recipients, input.subject, input.textBody, input.htmlBody);
|
|
996
1044
|
} catch {
|
|
997
1045
|
return defect("sendMessage", "VALIDATION", "message could not be encoded");
|
|
998
1046
|
}
|
|
999
1047
|
if (raw.length > this.#http.settings().maxMessageBytes) return defect("sendMessage", "VALIDATION", "message exceeds configured size limit");
|
|
1000
|
-
return this.#sendAndConfirm(call, fence, budget, credentials, SendMessageOutcomes, { raw, recipients, requestedThreadId: "", hasPreSendSearch: false });
|
|
1048
|
+
return this.#sendAndConfirm(call, fence, budget, credentials, SendMessageOutcomes, { raw, recipients, requestedThreadId: "", hasPreSendSearch: false, messageIdAddress });
|
|
1001
1049
|
}
|
|
1002
1050
|
/** Read the source then reply in its Gmail thread under the Dex attempt deadline. */
|
|
1003
1051
|
async replyToMessage(call, input, dexDeadline) {
|
|
1004
1052
|
if (call.context.attempt < 1) return defect("replyToMessage", "LOCAL_DEFECT", "Dex Execute attempt number is invalid");
|
|
1053
|
+
const messageIdAddress = this.#messageID(call);
|
|
1054
|
+
if (!messageIdAddress) return defect("replyToMessage", "LOCAL_DEFECT", MissingRunIDMessage);
|
|
1005
1055
|
const fence = (0, import_singledispatch.newFence)(call, ReplyToMessageDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4);
|
|
1006
1056
|
if (fence.decide().kind === "failClosed") return defect("replyToMessage", "LOCAL_DEFECT", "Dex send checkpoint is unreadable");
|
|
1007
1057
|
const budget = new GmailSendAttemptBudget(call.context.cancellationSignal, dexDeadline);
|
|
@@ -1023,15 +1073,15 @@ var GmailSender = class {
|
|
|
1023
1073
|
budget,
|
|
1024
1074
|
credentials,
|
|
1025
1075
|
ReplyToMessageOutcomes,
|
|
1026
|
-
{ raw: new Uint8Array(), recipients: [], requestedThreadId: "", hasPreSendSearch: true },
|
|
1076
|
+
{ raw: new Uint8Array(), recipients: [], requestedThreadId: "", hasPreSendSearch: true, messageIdAddress },
|
|
1027
1077
|
{ id: priorProviderId, threadId: "" },
|
|
1028
1078
|
this.#receipt(call, "", priorProviderId)
|
|
1029
1079
|
);
|
|
1030
1080
|
}
|
|
1031
1081
|
if (call.context.attempt > 1 || fence.decide().kind === "readBackRequired") {
|
|
1032
1082
|
try {
|
|
1033
|
-
const found = await this.#provider.findSentMessage(call, credentials,
|
|
1034
|
-
if (found) return this.#sentMessage(call, budget, credentials, ReplyToMessageOutcomes, { raw: new Uint8Array(), recipients: [], requestedThreadId: "", hasPreSendSearch: true }, found, this.#receipt(call));
|
|
1083
|
+
const found = await this.#provider.findSentMessage(call, credentials, messageIdAddress, budget.preSendSignal());
|
|
1084
|
+
if (found) return this.#sentMessage(call, budget, credentials, ReplyToMessageOutcomes, { raw: new Uint8Array(), recipients: [], requestedThreadId: "", hasPreSendSearch: true, messageIdAddress }, found, this.#receipt(call));
|
|
1035
1085
|
} catch {
|
|
1036
1086
|
await recordPreSendRetry(fence);
|
|
1037
1087
|
return (0, import_connectors_sdk4.newMutationRetry)(failure("replyToMessage", "AVAILABILITY", "Gmail sent-mail search did not answer before the reply"));
|
|
@@ -1071,12 +1121,12 @@ var GmailSender = class {
|
|
|
1071
1121
|
if (/[\r\n]/.test(message.subject + message.rfcMessageId + (message.references ?? ""))) return (0, import_connectors_sdk4.newMutationBranch)(ReplyToMessageBranch.InvalidResponse, emptySend(), this.#receipt(call, gmailRequestID(source.response.headers), input.messageId), failure("replyToMessage", "PROTOCOL", "Gmail returned invalid source reply headers"));
|
|
1072
1122
|
let raw;
|
|
1073
1123
|
try {
|
|
1074
|
-
raw = buildReplyMIMEMessage(call.id, call.idempotencyKey ?? call.id,
|
|
1124
|
+
raw = buildReplyMIMEMessage(call.id, call.idempotencyKey ?? call.id, messageIdAddress, credentials.primaryEmail, message, input);
|
|
1075
1125
|
} catch {
|
|
1076
1126
|
return defect("replyToMessage", "VALIDATION", "reply could not be encoded within the configured limit");
|
|
1077
1127
|
}
|
|
1078
1128
|
if (raw.length > this.#http.settings().maxMessageBytes) return defect("replyToMessage", "VALIDATION", "reply could not be encoded within the configured limit");
|
|
1079
|
-
return this.#sendAndConfirm(call, fence, budget, credentials, ReplyToMessageOutcomes, { raw, recipients: [recipient], requestedThreadId: message.threadId, hasPreSendSearch: call.context.attempt > 1 });
|
|
1129
|
+
return this.#sendAndConfirm(call, fence, budget, credentials, ReplyToMessageOutcomes, { raw, recipients: [recipient], requestedThreadId: message.threadId, hasPreSendSearch: call.context.attempt > 1, messageIdAddress });
|
|
1080
1130
|
}
|
|
1081
1131
|
async #sendAndConfirm(call, fence, budget, credentials, operation, message) {
|
|
1082
1132
|
const priorProviderId = fence.decide().marker?.providerId;
|
|
@@ -1093,7 +1143,7 @@ var GmailSender = class {
|
|
|
1093
1143
|
}
|
|
1094
1144
|
if ((call.context.attempt > 1 || fence.decide().kind === "readBackRequired") && !message.hasPreSendSearch) {
|
|
1095
1145
|
try {
|
|
1096
|
-
const found = await this.#provider.findSentMessage(call, credentials,
|
|
1146
|
+
const found = await this.#provider.findSentMessage(call, credentials, message.messageIdAddress, budget.preSendSignal());
|
|
1097
1147
|
if (found) return this.#sentMessage(call, budget, credentials, operation, message, found, this.#receipt(call));
|
|
1098
1148
|
} catch {
|
|
1099
1149
|
await recordPreSendRetry(fence);
|
|
@@ -1125,7 +1175,7 @@ var GmailSender = class {
|
|
|
1125
1175
|
return retryAfterRefusal(operation.operationId, "RATE_LIMIT", `Gmail temporarily rejected the ${operation.requestName}`, headers);
|
|
1126
1176
|
}
|
|
1127
1177
|
if (status === 503) {
|
|
1128
|
-
const lookup = await this.#pollSentMessage(call, budget, credentials);
|
|
1178
|
+
const lookup = await this.#pollSentMessage(call, budget, credentials, message);
|
|
1129
1179
|
if (lookup.sent) return this.#sentAfterDispatch(call, fence, budget, credentials, operation, message, lookup.sent, receipt);
|
|
1130
1180
|
return retryAfterRefusal(operation.operationId, "AVAILABILITY", `Gmail ${operation.requestName} is temporarily unavailable`, headers);
|
|
1131
1181
|
}
|
|
@@ -1133,7 +1183,7 @@ var GmailSender = class {
|
|
|
1133
1183
|
if (status < 200 || status >= 300) {
|
|
1134
1184
|
if (call.context.attempt > 1) {
|
|
1135
1185
|
try {
|
|
1136
|
-
const found = await this.#provider.findSentMessage(call, credentials,
|
|
1186
|
+
const found = await this.#provider.findSentMessage(call, credentials, message.messageIdAddress, budget.attemptSignal());
|
|
1137
1187
|
if (found) return this.#sentMessage(call, budget, credentials, operation, message, found, receipt);
|
|
1138
1188
|
} catch {
|
|
1139
1189
|
}
|
|
@@ -1141,14 +1191,14 @@ var GmailSender = class {
|
|
|
1141
1191
|
return (0, import_connectors_sdk4.newMutationBranch)(operation.providerRejectedBranch, emptySend(), receipt, failure(operation.operationId, statusFailureKind(status), operation.rejectionMessage));
|
|
1142
1192
|
}
|
|
1143
1193
|
if (!sentResponse) {
|
|
1144
|
-
const lookup = await this.#pollSentMessage(call, budget, credentials);
|
|
1194
|
+
const lookup = await this.#pollSentMessage(call, budget, credentials, message);
|
|
1145
1195
|
if (lookup.sent) return this.#sentAfterDispatch(call, fence, budget, credentials, operation, message, lookup.sent, receipt);
|
|
1146
1196
|
return this.#sentMessage(call, budget, credentials, operation, message, { id: "", threadId: message.requestedThreadId }, receipt);
|
|
1147
1197
|
}
|
|
1148
1198
|
return this.#sentMessage(call, budget, credentials, operation, message, sentResponse, receipt);
|
|
1149
1199
|
}
|
|
1150
1200
|
async #confirmPossiblySent(call, fence, budget, credentials, operation, message, kind, reason, receipt) {
|
|
1151
|
-
const lookup = await this.#pollSentMessage(call, budget, credentials);
|
|
1201
|
+
const lookup = await this.#pollSentMessage(call, budget, credentials, message);
|
|
1152
1202
|
if (lookup.sent) return this.#sentAfterDispatch(call, fence, budget, credentials, operation, message, lookup.sent, receipt);
|
|
1153
1203
|
const suffix = lookup.hadError ? "the sent-mail search did not answer" : "the sent-mail search found no message";
|
|
1154
1204
|
return (0, import_connectors_sdk4.newMutationRetry)(failure(operation.operationId, kind, `${reason}; ${suffix}`));
|
|
@@ -1169,7 +1219,7 @@ var GmailSender = class {
|
|
|
1169
1219
|
}
|
|
1170
1220
|
return (0, import_connectors_sdk4.newMutationBranch)(operation.sentBranch, { sender: credentials.primaryEmail, recipients: message.recipients, messageId: sent.id, threadId }, { ...receipt, providerObjectId: sent.id });
|
|
1171
1221
|
}
|
|
1172
|
-
async #pollSentMessage(call, budget, credentials) {
|
|
1222
|
+
async #pollSentMessage(call, budget, credentials, message) {
|
|
1173
1223
|
let hadError = false;
|
|
1174
1224
|
for (let lookup = 0; lookup < 4; lookup++) {
|
|
1175
1225
|
if (lookup > 0) {
|
|
@@ -1180,7 +1230,7 @@ var GmailSender = class {
|
|
|
1180
1230
|
}
|
|
1181
1231
|
}
|
|
1182
1232
|
try {
|
|
1183
|
-
const found = await this.#provider.findSentMessage(call, credentials,
|
|
1233
|
+
const found = await this.#provider.findSentMessage(call, credentials, message.messageIdAddress, budget.attemptSignal());
|
|
1184
1234
|
if (found) return { sent: found, hadError: false };
|
|
1185
1235
|
hadError = false;
|
|
1186
1236
|
} catch {
|
|
@@ -1191,7 +1241,9 @@ var GmailSender = class {
|
|
|
1191
1241
|
return { hadError };
|
|
1192
1242
|
}
|
|
1193
1243
|
#messageID(call) {
|
|
1194
|
-
|
|
1244
|
+
const { runId, flowStartedAt } = call.context;
|
|
1245
|
+
if (typeof runId !== "string" || !runId) return void 0;
|
|
1246
|
+
return rfcMessageIDAddress(call.idempotencyKey ?? call.id, runId, flowStartedAt);
|
|
1195
1247
|
}
|
|
1196
1248
|
#receipt(call, requestId = "", objectId = "") {
|
|
1197
1249
|
return { callId: call.id, ...call.idempotencyKey ? { idempotencyKey: call.idempotencyKey } : {}, provider: "gmail", providerObjectId: objectId, providerRequestId: requestId, observedAt: this.#now().toISOString() };
|
|
@@ -1246,12 +1298,19 @@ var GmailClient = class {
|
|
|
1246
1298
|
#provider;
|
|
1247
1299
|
#sender;
|
|
1248
1300
|
#now;
|
|
1301
|
+
/** Trigger record destination. */
|
|
1302
|
+
triggerLogger;
|
|
1249
1303
|
/** Validate settings and inject a host-owned credential source. */
|
|
1250
1304
|
constructor(config, credentials, options = {}) {
|
|
1251
1305
|
this.#http = new GmailHTTPClient(config, credentials, options.refreshDriver ?? new GmailCredentialRefreshDriver(), options.transport);
|
|
1252
1306
|
this.#provider = new GmailProvider(this.#http);
|
|
1253
1307
|
this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
1254
1308
|
this.#sender = new GmailSender(this.#http, this.#provider, this.#now);
|
|
1309
|
+
this.triggerLogger = options.logger ?? import_connectors_sdk5.defaultTriggerLogger;
|
|
1310
|
+
}
|
|
1311
|
+
/** @internal The authenticated transport and provider methods that the Trigger pollers share. */
|
|
1312
|
+
triggerTransport() {
|
|
1313
|
+
return { http: this.#http, provider: this.#provider };
|
|
1255
1314
|
}
|
|
1256
1315
|
/** Return the getMessage Query bound to this connection. */
|
|
1257
1316
|
getMessage() {
|
|
@@ -1517,6 +1576,374 @@ function newReplyToMessageStep2(configuration) {
|
|
|
1517
1576
|
requireGmailConnection(configuration.connection, configuration.connectionName);
|
|
1518
1577
|
return newReplyToMessageStep(configuration);
|
|
1519
1578
|
}
|
|
1579
|
+
|
|
1580
|
+
// src/trigger.ts
|
|
1581
|
+
var import_connectors_sdk12 = require("@superdurable/connectors-sdk");
|
|
1582
|
+
var import_projectconfig2 = require("@superdurable/connectors-sdk/projectconfig");
|
|
1583
|
+
var import_zod6 = require("zod");
|
|
1584
|
+
|
|
1585
|
+
// src/trigger_source.ts
|
|
1586
|
+
var import_node_crypto2 = require("crypto");
|
|
1587
|
+
var import_connectors_sdk11 = require("@superdurable/connectors-sdk");
|
|
1588
|
+
var GmailPollError = class extends Error {
|
|
1589
|
+
constructor(message, cause) {
|
|
1590
|
+
super(message, cause === void 0 ? void 0 : { cause });
|
|
1591
|
+
this.name = "GmailPollError";
|
|
1592
|
+
}
|
|
1593
|
+
};
|
|
1594
|
+
var uuidNamespaceURL = Buffer.from("6ba7b8119dad11d180b400c04fd430c8", "hex");
|
|
1595
|
+
var MessagePollingTriggerSource = class {
|
|
1596
|
+
#client;
|
|
1597
|
+
#connection;
|
|
1598
|
+
#searchQuery;
|
|
1599
|
+
#matcher;
|
|
1600
|
+
#requiresReply;
|
|
1601
|
+
#logger;
|
|
1602
|
+
#triggerName;
|
|
1603
|
+
#delivered = /* @__PURE__ */ new Set();
|
|
1604
|
+
// Every later poll delivers this event before any listed message, until the target consumes it.
|
|
1605
|
+
#retry;
|
|
1606
|
+
#pollFailures = 0;
|
|
1607
|
+
/** Bind one binding's query and matcher; an empty bindingName omits the binding log attribute. */
|
|
1608
|
+
constructor(client, connection, triggerName, bindingName, searchQuery, matcher, requiresReply) {
|
|
1609
|
+
this.#client = client;
|
|
1610
|
+
this.#connection = connection;
|
|
1611
|
+
this.#triggerName = triggerName;
|
|
1612
|
+
this.#searchQuery = searchQuery;
|
|
1613
|
+
this.#matcher = matcher;
|
|
1614
|
+
this.#requiresReply = requiresReply;
|
|
1615
|
+
this.#logger = (0, import_connectors_sdk11.withTriggerLoggerAttributes)(client.triggerLogger, { connector: ConnectorID, connection: connection.name, trigger: triggerName, ...bindingName ? { binding: bindingName } : {} });
|
|
1616
|
+
}
|
|
1617
|
+
/** Scan, then wait one poll interval, until the context ends. */
|
|
1618
|
+
async run(context, target) {
|
|
1619
|
+
await runMessageTriggerRoutes(context, () => this.scan(context, target), this.#pollIntervalMs());
|
|
1620
|
+
}
|
|
1621
|
+
/** List the inbox and deliver the listed messages. */
|
|
1622
|
+
async scan(context, target) {
|
|
1623
|
+
await this.deliver(context, target, await this.list(context));
|
|
1624
|
+
}
|
|
1625
|
+
/** Read the newest inbox page that matches the source's search query. */
|
|
1626
|
+
async list(context) {
|
|
1627
|
+
const { http, provider } = this.#client.triggerTransport();
|
|
1628
|
+
const call = this.#credentialCall(context.signal);
|
|
1629
|
+
let credentials;
|
|
1630
|
+
try {
|
|
1631
|
+
credentials = await http.resolveCredentials(call, context.signal);
|
|
1632
|
+
} catch (error) {
|
|
1633
|
+
throw this.#pollFailed(context, new GmailPollError("Gmail Trigger credentials are unavailable", error));
|
|
1634
|
+
}
|
|
1635
|
+
try {
|
|
1636
|
+
const listed = await provider.listInboxMessages(call, credentials, this.#searchQuery, http.settings().pollPageSize, context.signal);
|
|
1637
|
+
return { credentials: listed.credentials, messages: listed.messages };
|
|
1638
|
+
} catch (error) {
|
|
1639
|
+
throw this.#pollFailed(context, new GmailPollError("Gmail message list is unavailable", error));
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
/**
|
|
1643
|
+
* Hand target the event that failed on an earlier poll, if any, then every new matching message in
|
|
1644
|
+
* listing, oldest first. It stops at the first failure, so the next poll retries that event before any
|
|
1645
|
+
* later message, even after newer mail pushes it off the listed page.
|
|
1646
|
+
*/
|
|
1647
|
+
async deliver(context, target, listing) {
|
|
1648
|
+
if (this.#retry) await this.#handle(context, target, this.#retry.event);
|
|
1649
|
+
const { provider } = this.#client.triggerTransport();
|
|
1650
|
+
let credentials = listing.credentials;
|
|
1651
|
+
const current = /* @__PURE__ */ new Set();
|
|
1652
|
+
for (let index = listing.messages.length - 1; index >= 0; index--) {
|
|
1653
|
+
const reference = listing.messages[index];
|
|
1654
|
+
if (!reference.id) continue;
|
|
1655
|
+
current.add(reference.id);
|
|
1656
|
+
if (this.#delivered.has(reference.id)) continue;
|
|
1657
|
+
const messageAttributes = { thread_id: reference.threadId, event_id: reference.id };
|
|
1658
|
+
let message;
|
|
1659
|
+
try {
|
|
1660
|
+
const read = await provider.readMessage(this.#credentialCall(context.signal), credentials, reference.id, "metadata", context.signal);
|
|
1661
|
+
credentials = read.credentials;
|
|
1662
|
+
if (!read.resource) throw new GmailPollError("Gmail message lookup failed");
|
|
1663
|
+
message = decodeGmailMessage(read.resource);
|
|
1664
|
+
} catch (error) {
|
|
1665
|
+
throw this.#pollFailed(context, error instanceof GmailPollError ? error : new GmailPollError("Gmail message lookup failed", error), messageAttributes);
|
|
1666
|
+
}
|
|
1667
|
+
const isReply = (message.inReplyTo ?? "").trim() !== "" || (message.references ?? "").trim() !== "";
|
|
1668
|
+
const reason = this.#ignoreReason(isReply, message);
|
|
1669
|
+
if (reason) {
|
|
1670
|
+
this.#log(context, "debug", "trigger event ignored", { ...messageAttributes, reason });
|
|
1671
|
+
continue;
|
|
1672
|
+
}
|
|
1673
|
+
const event = {
|
|
1674
|
+
id: message.messageId,
|
|
1675
|
+
occurredAt: new Date(message.receivedAt),
|
|
1676
|
+
payload: {
|
|
1677
|
+
primaryEmail: credentials.primaryEmail,
|
|
1678
|
+
messageId: message.messageId,
|
|
1679
|
+
threadId: message.threadId,
|
|
1680
|
+
from: message.from,
|
|
1681
|
+
subject: message.subject,
|
|
1682
|
+
...message.snippet ? { snippet: message.snippet } : {},
|
|
1683
|
+
receivedAt: message.receivedAt,
|
|
1684
|
+
isReply
|
|
1685
|
+
}
|
|
1686
|
+
};
|
|
1687
|
+
try {
|
|
1688
|
+
await (0, import_connectors_sdk11.prepareTriggerDelivery)(context, target, event);
|
|
1689
|
+
} catch (error) {
|
|
1690
|
+
throw this.#pollFailed(context, new GmailPollError("Gmail Trigger delivery could not be recorded", error), messageAttributes);
|
|
1691
|
+
}
|
|
1692
|
+
await this.#handle(context, target, event);
|
|
1693
|
+
}
|
|
1694
|
+
this.#delivered = current;
|
|
1695
|
+
this.#pollFailures = 0;
|
|
1696
|
+
}
|
|
1697
|
+
#pollIntervalMs() {
|
|
1698
|
+
return this.#client.triggerTransport().http.settings().pollIntervalMs;
|
|
1699
|
+
}
|
|
1700
|
+
/**
|
|
1701
|
+
* Make one delivery attempt and log its outcome. It resolves when target consumes the event, and
|
|
1702
|
+
* otherwise keeps the event as the source's retry and rethrows. A durable inbox or a newTrigger runner
|
|
1703
|
+
* logs the undeliverable events it consumes itself, so the source then logs no recovery.
|
|
1704
|
+
*/
|
|
1705
|
+
async #handle(context, target, event) {
|
|
1706
|
+
const failures = this.#retry?.event.id === event.id ? this.#retry.failures : 0;
|
|
1707
|
+
const threadAttributes = { thread_id: event.payload.threadId };
|
|
1708
|
+
const messageAttributes = { ...threadAttributes, event_id: event.id };
|
|
1709
|
+
const attempt = (0, import_connectors_sdk11.triggerAttempt)((0, import_connectors_sdk11.withTriggerLogAttributes)(context, threadAttributes));
|
|
1710
|
+
try {
|
|
1711
|
+
await target.handleTrigger(attempt.context, event);
|
|
1712
|
+
if (failures > 0 && !attempt.wasSkipped()) this.#log(context, "info", "trigger delivered after retry", { ...messageAttributes, attempts: failures + 1 });
|
|
1713
|
+
} catch (error) {
|
|
1714
|
+
if ((0, import_connectors_sdk11.isTriggerUndeliverable)(error)) {
|
|
1715
|
+
this.#log(context, "warn", "trigger event skipped: undeliverable", { ...messageAttributes, ...(0, import_connectors_sdk11.triggerErrorAttributes)(error) });
|
|
1716
|
+
} else if (context.signal.aborted) {
|
|
1717
|
+
throw error;
|
|
1718
|
+
} else {
|
|
1719
|
+
this.#pollFailures = 0;
|
|
1720
|
+
this.#retry = { event, failures: failures + 1 };
|
|
1721
|
+
this.#log(context, "warn", "trigger delivery failed; retrying", { ...messageAttributes, attempt: failures + 1, delay_ms: this.#pollIntervalMs(), ...(0, import_connectors_sdk11.triggerErrorAttributes)(error) });
|
|
1722
|
+
throw error;
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
this.#retry = void 0;
|
|
1726
|
+
this.#delivered.add(event.id);
|
|
1727
|
+
}
|
|
1728
|
+
/** Explain why the source does not deliver a listed message, or return '' when it matches. */
|
|
1729
|
+
#ignoreReason(isReply, message) {
|
|
1730
|
+
if (this.#requiresReply && !isReply) return "not_a_reply";
|
|
1731
|
+
if (!this.#requiresReply && isReply) return "not_a_root";
|
|
1732
|
+
if (!messageMatcherMatches(this.#matcher, message)) return "matcher_mismatch";
|
|
1733
|
+
return "";
|
|
1734
|
+
}
|
|
1735
|
+
/** Log a poll that ended early and return error; the next poll, one interval later, retries. */
|
|
1736
|
+
#pollFailed(context, error, attributes = {}) {
|
|
1737
|
+
if (context.signal.aborted) return new import_connectors_sdk11.TriggerDeliveryAbortedError();
|
|
1738
|
+
this.#pollFailures++;
|
|
1739
|
+
const causeAttributes = error.cause === void 0 ? {} : { error_cause_type: (0, import_connectors_sdk11.triggerErrorAttributes)(error.cause).error_type ?? "Error" };
|
|
1740
|
+
this.#log(context, "warn", "gmail poll failed; retrying", { ...attributes, attempt: this.#pollFailures, delay_ms: this.#pollIntervalMs(), error: error.message, ...causeAttributes });
|
|
1741
|
+
return error;
|
|
1742
|
+
}
|
|
1743
|
+
#log(context, level, message, attributes) {
|
|
1744
|
+
(0, import_connectors_sdk11.logTriggerRecord)(this.#logger, context, level, message, attributes);
|
|
1745
|
+
}
|
|
1746
|
+
/** The Go connector's stable credential call: a version 5 UUID of the connection and Trigger. */
|
|
1747
|
+
#credentialCall(signal) {
|
|
1748
|
+
const identity = ["https://superdurable.dev/dex-connectors/trigger-credential/v1", this.#connection.provider, this.#connection.name, this.#triggerName].join("/");
|
|
1749
|
+
return (0, import_connectors_sdk11.createTriggerCall)(this.#connection, { connectorId: ConnectorID, operationId: this.#triggerName }, nameBasedUUID(identity), signal);
|
|
1750
|
+
}
|
|
1751
|
+
};
|
|
1752
|
+
function messageMatcherMatches(matcher, message) {
|
|
1753
|
+
if (matcher.messageContains) {
|
|
1754
|
+
const haystack = `${message.subject}
|
|
1755
|
+
${message.snippet ?? ""}`.toLowerCase();
|
|
1756
|
+
if (!haystack.includes(matcher.messageContains.toLowerCase())) return false;
|
|
1757
|
+
}
|
|
1758
|
+
const senders = matcher.senderEmails ?? [];
|
|
1759
|
+
if (senders.length === 0) return true;
|
|
1760
|
+
const sender = parseMailbox(message.from)?.address.toLowerCase();
|
|
1761
|
+
if (!sender) return false;
|
|
1762
|
+
return senders.some((allowed) => parseMailbox(allowed)?.address.toLowerCase() === sender);
|
|
1763
|
+
}
|
|
1764
|
+
async function runMessageTriggerRoutes(context, poll, intervalMs) {
|
|
1765
|
+
for (; ; ) {
|
|
1766
|
+
(0, import_connectors_sdk11.throwIfTriggerAborted)(context.signal);
|
|
1767
|
+
try {
|
|
1768
|
+
await poll();
|
|
1769
|
+
} catch {
|
|
1770
|
+
(0, import_connectors_sdk11.throwIfTriggerAborted)(context.signal);
|
|
1771
|
+
}
|
|
1772
|
+
await (0, import_connectors_sdk11.waitForTriggerDelay)(context.signal, intervalMs);
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
async function pollMessageTriggerRoutes(context, rootRoutes, replyRoutes) {
|
|
1776
|
+
const replyListings = [];
|
|
1777
|
+
for (const route of replyRoutes) replyListings.push(await route.source.list(context));
|
|
1778
|
+
for (const route of rootRoutes) await route.source.scan(context, route.target);
|
|
1779
|
+
for (const [index, route] of replyRoutes.entries()) await route.source.deliver(context, route.target, replyListings[index]);
|
|
1780
|
+
}
|
|
1781
|
+
async function replayMessageTriggerRoutes(context, routes) {
|
|
1782
|
+
for (const route of routes) {
|
|
1783
|
+
if (!route.target.replayTriggerDeliveries) continue;
|
|
1784
|
+
try {
|
|
1785
|
+
await route.target.replayTriggerDeliveries(context);
|
|
1786
|
+
} catch (error) {
|
|
1787
|
+
if (error instanceof import_connectors_sdk11.TriggerDeliveryAbortedError) throw error;
|
|
1788
|
+
throw new Error(`replay Gmail Trigger deliveries: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1789
|
+
}
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1792
|
+
function nameBasedUUID(name) {
|
|
1793
|
+
const bytes = (0, import_node_crypto2.createHash)("sha1").update(uuidNamespaceURL).update(name, "utf8").digest().subarray(0, 16);
|
|
1794
|
+
bytes[6] = bytes[6] & 15 | 80;
|
|
1795
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
1796
|
+
const hex = bytes.toString("hex");
|
|
1797
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
1798
|
+
}
|
|
1799
|
+
|
|
1800
|
+
// src/trigger.ts
|
|
1801
|
+
var MessageMatcherSchema = import_zod6.z.strictObject({
|
|
1802
|
+
/** Case-insensitive substring of the subject or snippet, required when non-empty. */
|
|
1803
|
+
messageContains: import_zod6.z.string().optional(),
|
|
1804
|
+
/** Sender addresses allowed to match when non-empty; compared case-insensitively. */
|
|
1805
|
+
senderEmails: import_zod6.z.array(import_zod6.z.string()).nullable().optional()
|
|
1806
|
+
});
|
|
1807
|
+
var MessageReceivedTriggerConfigurationSchema = import_zod6.z.strictObject({ searchQuery: import_zod6.z.string().optional(), messageMatcher: MessageMatcherSchema.optional() }).superRefine((configuration, context) => validateMessageMatcher(configuration.messageMatcher, context));
|
|
1808
|
+
var ReplyReceivedTriggerConfigurationSchema = import_zod6.z.strictObject({ searchQuery: import_zod6.z.string().optional(), replyMatcher: MessageMatcherSchema.optional() }).superRefine((configuration, context) => validateMessageMatcher(configuration.replyMatcher, context));
|
|
1809
|
+
var MessageEventSchema = import_zod6.z.object({
|
|
1810
|
+
/** Mailbox that received the message. */
|
|
1811
|
+
primaryEmail: import_zod6.z.string(),
|
|
1812
|
+
/** Gmail message ID. */
|
|
1813
|
+
messageId: import_zod6.z.string(),
|
|
1814
|
+
/** Gmail thread ID. */
|
|
1815
|
+
threadId: import_zod6.z.string(),
|
|
1816
|
+
/** Sender header. */
|
|
1817
|
+
from: import_zod6.z.string(),
|
|
1818
|
+
/** Decoded subject. */
|
|
1819
|
+
subject: import_zod6.z.string(),
|
|
1820
|
+
/** Gmail snippet, omitted when empty. */
|
|
1821
|
+
snippet: import_zod6.z.string().optional(),
|
|
1822
|
+
/** Receive time as RFC 3339 UTC. */
|
|
1823
|
+
receivedAt: import_zod6.z.string(),
|
|
1824
|
+
/** Whether the message has In-Reply-To or References headers. */
|
|
1825
|
+
isReply: import_zod6.z.boolean()
|
|
1826
|
+
});
|
|
1827
|
+
var MessageReceivedTriggerDefinition = { trigger: { connectorId: ConnectorID, triggerName: "messageReceived" }, description: "Receive a matching message that begins a Gmail thread." };
|
|
1828
|
+
var ReplyReceivedTriggerDefinition = { trigger: { connectorId: ConnectorID, triggerName: "replyReceived" }, description: "Receive a matching reply in an existing Gmail thread." };
|
|
1829
|
+
var UIUnitSearchQueryInput = "searchQueryInput";
|
|
1830
|
+
var UISearchQueryInputPortQuery = "query";
|
|
1831
|
+
var UIUnitEmailListInput = "emailListInput";
|
|
1832
|
+
var UIEmailListInputPortEmails = "emails";
|
|
1833
|
+
var UIUnitTextInput = "textInput";
|
|
1834
|
+
var UITextInputPortText = "text";
|
|
1835
|
+
function defineMessageReceivedTriggerBinding(config) {
|
|
1836
|
+
return (0, import_connectors_sdk12.mustTriggerBindingDefinition)({ definition: MessageReceivedTriggerDefinition, ...config });
|
|
1837
|
+
}
|
|
1838
|
+
function defineReplyReceivedTriggerBinding(config) {
|
|
1839
|
+
return (0, import_connectors_sdk12.mustTriggerBindingDefinition)({ definition: ReplyReceivedTriggerDefinition, ...config });
|
|
1840
|
+
}
|
|
1841
|
+
function newMessageReceivedTrigger(config) {
|
|
1842
|
+
const configuration = MessageReceivedTriggerConfigurationSchema.parse(config.configuration);
|
|
1843
|
+
return newStandaloneTrigger(config, MessageReceivedTriggerDefinition, configuration.searchQuery ?? "", configuration.messageMatcher ?? {}, false);
|
|
1844
|
+
}
|
|
1845
|
+
function newReplyReceivedTrigger(config) {
|
|
1846
|
+
const configuration = ReplyReceivedTriggerConfigurationSchema.parse(config.configuration);
|
|
1847
|
+
return newStandaloneTrigger(config, ReplyReceivedTriggerDefinition, configuration.searchQuery ?? "", configuration.replyMatcher ?? {}, true);
|
|
1848
|
+
}
|
|
1849
|
+
function newStandaloneTrigger(config, definition, searchQuery, matcher, requiresReply) {
|
|
1850
|
+
const client = gmailClientOf(config.connection);
|
|
1851
|
+
if (config.connectionName !== config.connection.reference.name) throw new TypeError(`gmail connector trigger connectionName "${config.connectionName}" must equal its connection's name "${config.connection.reference.name}"`);
|
|
1852
|
+
const source = new MessagePollingTriggerSource(client, config.connection.reference, definition.trigger.triggerName, "", searchQuery, matcher, requiresReply);
|
|
1853
|
+
const triggerSource = { run: (context, target) => source.run(context, target) };
|
|
1854
|
+
return (0, import_connectors_sdk12.newTrigger)({ definition, binding: { connection: config.connection.reference, trigger: definition.trigger, name: config.bindingName }, source: triggerSource, target: config.target, logger: client.triggerLogger });
|
|
1855
|
+
}
|
|
1856
|
+
var MessageTriggerRunner = class {
|
|
1857
|
+
#rootRoutes;
|
|
1858
|
+
#replyRoutes;
|
|
1859
|
+
#pollIntervalMs;
|
|
1860
|
+
/** @internal Use newMessageTriggerRunner or newProjectMessageTriggerRunner. */
|
|
1861
|
+
constructor(rootRoutes, replyRoutes, pollIntervalMs) {
|
|
1862
|
+
this.#rootRoutes = rootRoutes;
|
|
1863
|
+
this.#replyRoutes = replyRoutes;
|
|
1864
|
+
this.#pollIntervalMs = pollIntervalMs;
|
|
1865
|
+
}
|
|
1866
|
+
/**
|
|
1867
|
+
* Replay each route's durable inbox in order, roots first, then poll until the context ends. Each poll
|
|
1868
|
+
* lists every reply route before any root route, then delivers every root before any reply, and ends
|
|
1869
|
+
* at the first failure. Every later poll retries the failed event before that route's listed messages,
|
|
1870
|
+
* even after Gmail stops listing it. Gmail receives a thread's root before any reply to it, so the
|
|
1871
|
+
* root of every listed reply is in the later root listing and reaches Dex first.
|
|
1872
|
+
*
|
|
1873
|
+
* It logs through the client's logger: WARN "gmail poll failed; retrying" with the consecutive failed
|
|
1874
|
+
* polls as attempt and the poll interval as delay_ms when a list or read fails, WARN "trigger delivery
|
|
1875
|
+
* failed; retrying" with the attempt number when a target fails, INFO "trigger delivered after retry"
|
|
1876
|
+
* when a later poll delivers that message, DEBUG "trigger event ignored" with its reason, and the
|
|
1877
|
+
* durable inbox records. It rejects with TriggerDeliveryAbortedError once the context ends, and when
|
|
1878
|
+
* an inbox replay fails.
|
|
1879
|
+
*/
|
|
1880
|
+
async run(context) {
|
|
1881
|
+
await replayMessageTriggerRoutes(context, [...this.#rootRoutes, ...this.#replyRoutes]);
|
|
1882
|
+
await runMessageTriggerRoutes(context, () => pollMessageTriggerRoutes(context, this.#rootRoutes, this.#replyRoutes), this.#pollIntervalMs);
|
|
1883
|
+
}
|
|
1884
|
+
};
|
|
1885
|
+
function newMessageTriggerRunner(config) {
|
|
1886
|
+
const client = gmailClientOf(config.connection);
|
|
1887
|
+
const bindingKeys = /* @__PURE__ */ new Set();
|
|
1888
|
+
const route = (triggerName, bindingName, target, searchQuery, matcher, requiresReply) => {
|
|
1889
|
+
const trimmedBindingName = bindingName?.trim();
|
|
1890
|
+
if (!trimmedBindingName || !target) throw new TypeError("Gmail message Trigger binding name and target are required");
|
|
1891
|
+
const bindingKey = `${triggerName}\0${trimmedBindingName}`;
|
|
1892
|
+
if (bindingKeys.has(bindingKey)) throw new TypeError(`Gmail message Trigger binding name "${trimmedBindingName}" is duplicated`);
|
|
1893
|
+
bindingKeys.add(bindingKey);
|
|
1894
|
+
return { source: new MessagePollingTriggerSource(client, config.connection.reference, triggerName, bindingName, searchQuery ?? "", matcher ?? {}, requiresReply), target };
|
|
1895
|
+
};
|
|
1896
|
+
const rootRoutes = (config.messageReceivedRoutes ?? []).map((root) => {
|
|
1897
|
+
const configuration = MessageReceivedTriggerConfigurationSchema.parse(root.configuration);
|
|
1898
|
+
return route("messageReceived", root.bindingName, root.target, configuration.searchQuery, configuration.messageMatcher, false);
|
|
1899
|
+
});
|
|
1900
|
+
const replyRoutes = (config.replyReceivedRoutes ?? []).map((reply) => {
|
|
1901
|
+
const configuration = ReplyReceivedTriggerConfigurationSchema.parse(reply.configuration);
|
|
1902
|
+
return route("replyReceived", reply.bindingName, reply.target, configuration.searchQuery, configuration.replyMatcher, true);
|
|
1903
|
+
});
|
|
1904
|
+
if (rootRoutes.length + replyRoutes.length === 0) throw new TypeError("Gmail message Trigger routes are required");
|
|
1905
|
+
return new MessageTriggerRunner(rootRoutes, replyRoutes, client.triggerTransport().http.settings().pollIntervalMs);
|
|
1906
|
+
}
|
|
1907
|
+
function newProjectMessageTriggerRunner(project, connectionName, config, options = {}) {
|
|
1908
|
+
const connection = newProjectConnection(project, connectionName, options);
|
|
1909
|
+
const client = gmailClientOf(connection);
|
|
1910
|
+
const durable = (triggerName, bindingName, target, schema) => {
|
|
1911
|
+
const key = { connectorId: ConnectorID, connectionName, triggerName, bindingName };
|
|
1912
|
+
let configuration;
|
|
1913
|
+
try {
|
|
1914
|
+
configuration = (0, import_projectconfig2.decodeTriggerConfiguration)(project.configuration, key, schema);
|
|
1915
|
+
} catch (error) {
|
|
1916
|
+
throw new Error(`gmail ${triggerName} binding "${bindingName}" configuration: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1917
|
+
}
|
|
1918
|
+
const durableTarget = (0, import_projectconfig2.newDurableTriggerTarget)(project.triggerInbox(key), key, target, { logger: client.triggerLogger, decodePayload: (_payloadJSON, payloadBytes) => MessageEventSchema.parse((0, import_projectconfig2.parseTriggerPayloadJSON)(payloadBytes)) });
|
|
1919
|
+
return { bindingName, configuration, target: durableTarget };
|
|
1920
|
+
};
|
|
1921
|
+
return newMessageTriggerRunner({
|
|
1922
|
+
connection,
|
|
1923
|
+
messageReceivedRoutes: (config.messageReceivedRoutes ?? []).map((route) => durable("messageReceived", route.bindingName, route.target, MessageReceivedTriggerConfigurationSchema)),
|
|
1924
|
+
replyReceivedRoutes: (config.replyReceivedRoutes ?? []).map((route) => durable("replyReceived", route.bindingName, route.target, ReplyReceivedTriggerConfigurationSchema))
|
|
1925
|
+
});
|
|
1926
|
+
}
|
|
1927
|
+
function gmailClientOf(connection) {
|
|
1928
|
+
if (!(connection?.operations instanceof GmailClient)) throw new TypeError("Gmail Triggers require a connection bound to a GmailClient");
|
|
1929
|
+
return connection.operations;
|
|
1930
|
+
}
|
|
1931
|
+
function validateMessageMatcher(matcher, context) {
|
|
1932
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1933
|
+
for (const sender of matcher?.senderEmails ?? []) {
|
|
1934
|
+
const address = parseMailbox(sender)?.address;
|
|
1935
|
+
if (!address) {
|
|
1936
|
+
context.addIssue({ code: "custom", message: "Gmail sender email is invalid" });
|
|
1937
|
+
return;
|
|
1938
|
+
}
|
|
1939
|
+
const canonical = address.toLowerCase();
|
|
1940
|
+
if (seen.has(canonical)) {
|
|
1941
|
+
context.addIssue({ code: "custom", message: "Gmail sender emails must be unique" });
|
|
1942
|
+
return;
|
|
1943
|
+
}
|
|
1944
|
+
seen.add(canonical);
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1520
1947
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1521
1948
|
0 && (module.exports = {
|
|
1522
1949
|
ConnectorID,
|
|
@@ -1532,8 +1959,15 @@ function newReplyToMessageStep2(configuration) {
|
|
|
1532
1959
|
GmailMessageResourceSchema,
|
|
1533
1960
|
GmailProvider,
|
|
1534
1961
|
GoogleOAuthAuthMethodID,
|
|
1962
|
+
MessageEventSchema,
|
|
1963
|
+
MessageMatcherSchema,
|
|
1964
|
+
MessageReceivedTriggerConfigurationSchema,
|
|
1965
|
+
MessageReceivedTriggerDefinition,
|
|
1535
1966
|
MessageSchema,
|
|
1967
|
+
MessageTriggerRunner,
|
|
1536
1968
|
ProviderID,
|
|
1969
|
+
ReplyReceivedTriggerConfigurationSchema,
|
|
1970
|
+
ReplyReceivedTriggerDefinition,
|
|
1537
1971
|
ReplyToMessageBranch,
|
|
1538
1972
|
ReplyToMessageDefinition,
|
|
1539
1973
|
ReplyToMessageInputSchema,
|
|
@@ -1543,18 +1977,30 @@ function newReplyToMessageStep2(configuration) {
|
|
|
1543
1977
|
SendMessageInputSchema,
|
|
1544
1978
|
SendMessageOperation,
|
|
1545
1979
|
SendMessageOutputSchema,
|
|
1980
|
+
UIEmailListInputPortEmails,
|
|
1981
|
+
UISearchQueryInputPortQuery,
|
|
1982
|
+
UITextInputPortText,
|
|
1983
|
+
UIUnitEmailListInput,
|
|
1984
|
+
UIUnitSearchQueryInput,
|
|
1985
|
+
UIUnitTextInput,
|
|
1546
1986
|
WorkspaceDomainDelegationAuthMethodID,
|
|
1547
1987
|
buildMIMEMessage,
|
|
1548
1988
|
buildReplyMIMEMessage,
|
|
1549
1989
|
decodeGmailMessage,
|
|
1990
|
+
defineMessageReceivedTriggerBinding,
|
|
1991
|
+
defineReplyReceivedTriggerBinding,
|
|
1550
1992
|
emptyMessage,
|
|
1551
1993
|
gmailClientSettings,
|
|
1552
1994
|
gmailFailure,
|
|
1553
1995
|
gmailRequestID,
|
|
1554
1996
|
gmailRetryAfterMs,
|
|
1555
1997
|
newGetMessageStep,
|
|
1998
|
+
newMessageReceivedTrigger,
|
|
1999
|
+
newMessageTriggerRunner,
|
|
1556
2000
|
newProjectConnection,
|
|
1557
2001
|
newProjectGmailClient,
|
|
2002
|
+
newProjectMessageTriggerRunner,
|
|
2003
|
+
newReplyReceivedTrigger,
|
|
1558
2004
|
newReplyToMessageStep,
|
|
1559
2005
|
newSendMessageStep,
|
|
1560
2006
|
parseMailbox,
|