@superdurable/connector-google-gmail 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -1
- package/dex-connector.json +108 -5
- package/dist/{chunk-TWBWDIC7.js → chunk-KVNIQW5Y.js} +334 -110
- package/dist/{connection-NE_da2Az.d.cts → connection-D8OV_Hfe.d.cts} +1 -1
- package/dist/{connection-NE_da2Az.d.ts → connection-D8OV_Hfe.d.ts} +1 -1
- package/dist/index.cjs +394 -164
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +1 -1
- package/dist/mock/index.cjs +44 -33
- package/dist/mock/index.d.cts +1 -1
- package/dist/mock/index.d.ts +1 -1
- package/dist/mock/index.js +1 -1
- package/package.json +4 -3
package/dist/index.cjs
CHANGED
|
@@ -73,6 +73,30 @@ var import_zod2 = require("zod");
|
|
|
73
73
|
|
|
74
74
|
// src/generated/models.ts
|
|
75
75
|
var import_zod = require("zod");
|
|
76
|
+
var import_connectors_sdk = require("@superdurable/connectors-sdk");
|
|
77
|
+
var goTimeJSONPattern = /^(\d{4})-(\d{2})-(\d{2})T(\d{1,2}):(\d{2}):(\d{2})(?:[.,](\d+))?(Z|([+-])(\d{2}):(\d{2}))$/;
|
|
78
|
+
function isGoTimeJSON(value) {
|
|
79
|
+
const match = goTimeJSONPattern.exec(value);
|
|
80
|
+
if (!match) return false;
|
|
81
|
+
const [, yearText, monthText, dayText, hourText, minuteText, secondText, , zone, , zoneHourText, zoneMinuteText] = match;
|
|
82
|
+
const year = Number(yearText);
|
|
83
|
+
const month = Number(monthText);
|
|
84
|
+
const day = Number(dayText);
|
|
85
|
+
const isLeap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
86
|
+
const monthDays = [31, isLeap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
87
|
+
return month >= 1 && month <= 12 && day >= 1 && day <= monthDays[month - 1] && Number(hourText) <= 23 && Number(minuteText) <= 59 && Number(secondText) <= 59 && (zone === "Z" || Number(zoneHourText) <= 24 && Number(zoneMinuteText) <= 60);
|
|
88
|
+
}
|
|
89
|
+
function canonicalGoTimeJSON(value) {
|
|
90
|
+
const match = goTimeJSONPattern.exec(value);
|
|
91
|
+
const [, year, month, day, hour, minute, second, fraction, zone, sign, zoneHour, zoneMinute] = match;
|
|
92
|
+
const clock = year + "-" + month + "-" + day + "T" + hour.padStart(2, "0") + ":" + minute + ":" + second;
|
|
93
|
+
const digits = (fraction ?? "").slice(0, 9).replace(/0+$/, "");
|
|
94
|
+
const offsetMinutes = zone === "Z" ? 0 : (Number(zoneHour) * 60 + Number(zoneMinute)) * (sign === "+" ? 1 : -1);
|
|
95
|
+
if (Math.abs(offsetMinutes) >= 1440) return value;
|
|
96
|
+
const offset = offsetMinutes === 0 ? "Z" : (offsetMinutes > 0 ? "+" : "-") + String(Math.floor(Math.abs(offsetMinutes) / 60)).padStart(2, "0") + ":" + String(Math.abs(offsetMinutes) % 60).padStart(2, "0");
|
|
97
|
+
return clock + (digits ? "." + digits : "") + offset;
|
|
98
|
+
}
|
|
99
|
+
var GoTimeJSONSchema = import_zod.z.string().refine(isGoTimeJSON, "invalid Go time.Time JSON timestamp").transform(canonicalGoTimeJSON);
|
|
76
100
|
var ConfigSchema = import_zod.z.object({
|
|
77
101
|
"endpoint": import_zod.z.string().optional(),
|
|
78
102
|
"maxResponseBytes": import_zod.z.number().int().optional(),
|
|
@@ -80,6 +104,82 @@ var ConfigSchema = import_zod.z.object({
|
|
|
80
104
|
"pollIntervalMs": import_zod.z.number().int().optional(),
|
|
81
105
|
"pollPageSize": import_zod.z.number().int().optional()
|
|
82
106
|
});
|
|
107
|
+
function decodeCredentials(value) {
|
|
108
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("credential fields are invalid");
|
|
109
|
+
const fields = value;
|
|
110
|
+
const allowed = /* @__PURE__ */ new Set(["auth_method", "access_token", "delegated_user", "oauth_client_id", "oauth_client_secret", "primary_email", "refresh_token", "service_account_key"]);
|
|
111
|
+
if (Object.keys(fields).some((key) => !allowed.has(key))) throw new TypeError("stored credential does not match the connector credential fields");
|
|
112
|
+
if (fields["access_token"] != null && !(typeof fields["access_token"] === "string")) throw new TypeError("credential access_token has an invalid type");
|
|
113
|
+
if (fields["delegated_user"] != null && !(typeof fields["delegated_user"] === "string")) throw new TypeError("credential delegated_user has an invalid type");
|
|
114
|
+
if (fields["oauth_client_id"] != null && !(typeof fields["oauth_client_id"] === "string")) throw new TypeError("credential oauth_client_id has an invalid type");
|
|
115
|
+
if (fields["oauth_client_secret"] != null && !(typeof fields["oauth_client_secret"] === "string")) throw new TypeError("credential oauth_client_secret has an invalid type");
|
|
116
|
+
if (fields["primary_email"] != null && !(typeof fields["primary_email"] === "string")) throw new TypeError("credential primary_email has an invalid type");
|
|
117
|
+
if (fields["refresh_token"] != null && !(typeof fields["refresh_token"] === "string")) throw new TypeError("credential refresh_token has an invalid type");
|
|
118
|
+
if (fields["service_account_key"] != null && !(typeof fields["service_account_key"] === "string")) throw new TypeError("credential service_account_key has an invalid type");
|
|
119
|
+
const selectedMethod = fields["auth_method"] ?? "";
|
|
120
|
+
if (typeof selectedMethod !== "string") throw new TypeError("credential auth_method is invalid");
|
|
121
|
+
const method = selectedMethod || "google-oauth";
|
|
122
|
+
const credentials = { authMethodId: method };
|
|
123
|
+
if (method === "google-oauth") {
|
|
124
|
+
if (!fields["oauth_client_id"]) throw new TypeError("credential oauth_client_id is required");
|
|
125
|
+
if (fields["oauth_client_id"]) credentials.oauthClientId = fields["oauth_client_id"];
|
|
126
|
+
if (!fields["oauth_client_secret"]) throw new TypeError("credential oauth_client_secret is required");
|
|
127
|
+
if (fields["oauth_client_secret"]) credentials.oauthClientSecret = new import_connectors_sdk.SecretString(fields["oauth_client_secret"]);
|
|
128
|
+
if (!fields["access_token"]) throw new TypeError("credential access_token is required");
|
|
129
|
+
if (fields["access_token"]) credentials.accessToken = new import_connectors_sdk.SecretString(fields["access_token"]);
|
|
130
|
+
if (!fields["refresh_token"]) throw new TypeError("credential refresh_token is required");
|
|
131
|
+
if (fields["refresh_token"]) credentials.refreshToken = new import_connectors_sdk.SecretString(fields["refresh_token"]);
|
|
132
|
+
if (!fields["primary_email"]) throw new TypeError("credential primary_email is required");
|
|
133
|
+
if (fields["primary_email"]) credentials.primaryEmail = fields["primary_email"];
|
|
134
|
+
} else if (method === "workspace-domain-delegation") {
|
|
135
|
+
if (!fields["service_account_key"]) throw new TypeError("credential service_account_key is required");
|
|
136
|
+
if (fields["service_account_key"]) credentials.serviceAccountKey = new import_connectors_sdk.SecretString(fields["service_account_key"]);
|
|
137
|
+
if (!fields["delegated_user"]) throw new TypeError("credential delegated_user is required");
|
|
138
|
+
if (fields["delegated_user"]) credentials.delegatedUser = fields["delegated_user"];
|
|
139
|
+
credentials.accessToken = new import_connectors_sdk.SecretString(fields["access_token"] ?? "");
|
|
140
|
+
credentials.primaryEmail = fields["primary_email"] ?? "";
|
|
141
|
+
} else {
|
|
142
|
+
throw new TypeError("credential auth_method is invalid");
|
|
143
|
+
}
|
|
144
|
+
return credentials;
|
|
145
|
+
}
|
|
146
|
+
function decodeSharedCredentials(value) {
|
|
147
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("credential fields are invalid");
|
|
148
|
+
const fields = value;
|
|
149
|
+
const allowed = /* @__PURE__ */ new Set(["auth_method", "access_token", "delegated_user", "oauth_client_id", "oauth_client_secret", "primary_email", "refresh_token", "service_account_key"]);
|
|
150
|
+
if (Object.keys(fields).some((key) => !allowed.has(key))) throw new TypeError("stored credential does not match the connector credential fields");
|
|
151
|
+
if (fields["access_token"] != null && !(typeof fields["access_token"] === "string")) throw new TypeError("credential access_token has an invalid type");
|
|
152
|
+
if (fields["delegated_user"] != null && !(typeof fields["delegated_user"] === "string")) throw new TypeError("credential delegated_user has an invalid type");
|
|
153
|
+
if (fields["oauth_client_id"] != null && !(typeof fields["oauth_client_id"] === "string")) throw new TypeError("credential oauth_client_id has an invalid type");
|
|
154
|
+
if (fields["oauth_client_secret"] != null && !(typeof fields["oauth_client_secret"] === "string")) throw new TypeError("credential oauth_client_secret has an invalid type");
|
|
155
|
+
if (fields["primary_email"] != null && !(typeof fields["primary_email"] === "string")) throw new TypeError("credential primary_email has an invalid type");
|
|
156
|
+
if (fields["refresh_token"] != null && !(typeof fields["refresh_token"] === "string")) throw new TypeError("credential refresh_token has an invalid type");
|
|
157
|
+
if (fields["service_account_key"] != null && !(typeof fields["service_account_key"] === "string")) throw new TypeError("credential service_account_key has an invalid type");
|
|
158
|
+
const selectedMethod = fields["auth_method"] ?? "";
|
|
159
|
+
if (typeof selectedMethod !== "string") throw new TypeError("credential auth_method is invalid");
|
|
160
|
+
const method = selectedMethod || "google-oauth";
|
|
161
|
+
const credentials = { authMethodId: method };
|
|
162
|
+
if (method === "google-oauth") {
|
|
163
|
+
if (!fields["oauth_client_id"]) throw new TypeError("credential oauth_client_id is required");
|
|
164
|
+
if (fields["oauth_client_id"]) credentials.oauthClientId = fields["oauth_client_id"];
|
|
165
|
+
if (fields["oauth_client_secret"]) credentials.oauthClientSecret = new import_connectors_sdk.SecretString(fields["oauth_client_secret"]);
|
|
166
|
+
if (!fields["access_token"]) throw new TypeError("credential access_token is required");
|
|
167
|
+
if (fields["access_token"]) credentials.accessToken = new import_connectors_sdk.SecretString(fields["access_token"]);
|
|
168
|
+
if (fields["refresh_token"]) credentials.refreshToken = new import_connectors_sdk.SecretString(fields["refresh_token"]);
|
|
169
|
+
if (!fields["primary_email"]) throw new TypeError("credential primary_email is required");
|
|
170
|
+
if (fields["primary_email"]) credentials.primaryEmail = fields["primary_email"];
|
|
171
|
+
} else if (method === "workspace-domain-delegation") {
|
|
172
|
+
if (fields["service_account_key"]) credentials.serviceAccountKey = new import_connectors_sdk.SecretString(fields["service_account_key"]);
|
|
173
|
+
if (!fields["delegated_user"]) throw new TypeError("credential delegated_user is required");
|
|
174
|
+
if (fields["delegated_user"]) credentials.delegatedUser = fields["delegated_user"];
|
|
175
|
+
if (!fields["access_token"]) throw new TypeError("credential access_token is required");
|
|
176
|
+
credentials.accessToken = new import_connectors_sdk.SecretString(fields["access_token"] ?? "");
|
|
177
|
+
credentials.primaryEmail = fields["primary_email"] ?? "";
|
|
178
|
+
} else {
|
|
179
|
+
throw new TypeError("credential auth_method is invalid");
|
|
180
|
+
}
|
|
181
|
+
return credentials;
|
|
182
|
+
}
|
|
83
183
|
var GetMessageInputSchema = import_zod.z.strictObject({
|
|
84
184
|
"messageId": import_zod.z.string()
|
|
85
185
|
});
|
|
@@ -96,7 +196,7 @@ var MessageSchema = import_zod.z.strictObject({
|
|
|
96
196
|
"textBody": import_zod.z.string().optional(),
|
|
97
197
|
"htmlBody": import_zod.z.string().optional(),
|
|
98
198
|
"snippet": import_zod.z.string().optional(),
|
|
99
|
-
"receivedAt":
|
|
199
|
+
"receivedAt": GoTimeJSONSchema,
|
|
100
200
|
"labelIds": import_zod.z.array(import_zod.z.string()).optional()
|
|
101
201
|
});
|
|
102
202
|
var SendMessageInputSchema = import_zod.z.strictObject({
|
|
@@ -374,7 +474,7 @@ function encodeSubject(value) {
|
|
|
374
474
|
}
|
|
375
475
|
|
|
376
476
|
// src/http.ts
|
|
377
|
-
var
|
|
477
|
+
var import_connectors_sdk2 = require("@superdurable/connectors-sdk");
|
|
378
478
|
var import_providerhttp = require("@superdurable/connectors-sdk/providerhttp");
|
|
379
479
|
function gmailClientSettings(config = {}) {
|
|
380
480
|
const endpoint = (0, import_providerhttp.validateBaseURL)(config.endpoint ?? "https://gmail.googleapis.com/gmail/v1");
|
|
@@ -413,7 +513,7 @@ var GmailHTTPClient = class {
|
|
|
413
513
|
/** Resolve a private token at call time; never put it in a receipt or Flow value. */
|
|
414
514
|
async resolveCredentials(call, signal) {
|
|
415
515
|
try {
|
|
416
|
-
const credentials = await (0,
|
|
516
|
+
const credentials = await (0, import_connectors_sdk2.resolveCredential)(this.#credentials, call, this.#refreshDriver, signal);
|
|
417
517
|
validateCredentials(credentials);
|
|
418
518
|
return credentials;
|
|
419
519
|
} catch {
|
|
@@ -445,7 +545,7 @@ var GmailHTTPClient = class {
|
|
|
445
545
|
}
|
|
446
546
|
if (response.status !== 401 || attempt !== 0 || !("resolveAfterRejection" in this.#credentials)) return { response, credentials: currentCredentials };
|
|
447
547
|
try {
|
|
448
|
-
const refreshed = await (0,
|
|
548
|
+
const refreshed = await (0, import_connectors_sdk2.resolveCredentialAfterRejection)(this.#credentials, call, this.#refreshDriver, signal);
|
|
449
549
|
validateCredentials(refreshed);
|
|
450
550
|
currentCredentials = refreshed;
|
|
451
551
|
} catch {
|
|
@@ -554,81 +654,215 @@ function parseSentResponse(response) {
|
|
|
554
654
|
}
|
|
555
655
|
|
|
556
656
|
// src/refresh.ts
|
|
557
|
-
var
|
|
657
|
+
var import_connectors_sdk3 = require("@superdurable/connectors-sdk");
|
|
558
658
|
var import_oauthtoken = require("@superdurable/connectors-sdk/oauthtoken");
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
var
|
|
562
|
-
|
|
563
|
-
|
|
659
|
+
|
|
660
|
+
// src/generated/refresh.ts
|
|
661
|
+
var Authorization = {
|
|
662
|
+
"defaultMethod": "google-oauth",
|
|
663
|
+
"methods": [
|
|
664
|
+
{
|
|
665
|
+
"fields": [
|
|
666
|
+
{
|
|
667
|
+
"name": "oauth_client_id",
|
|
668
|
+
"required": true,
|
|
669
|
+
"type": "string"
|
|
670
|
+
},
|
|
671
|
+
{
|
|
672
|
+
"name": "oauth_client_secret",
|
|
673
|
+
"required": true,
|
|
674
|
+
"type": "secretString"
|
|
675
|
+
},
|
|
676
|
+
{
|
|
677
|
+
"name": "access_token",
|
|
678
|
+
"required": true,
|
|
679
|
+
"type": "secretString"
|
|
680
|
+
},
|
|
681
|
+
{
|
|
682
|
+
"name": "refresh_token",
|
|
683
|
+
"required": true,
|
|
684
|
+
"type": "secretString"
|
|
685
|
+
},
|
|
686
|
+
{
|
|
687
|
+
"name": "primary_email",
|
|
688
|
+
"required": true,
|
|
689
|
+
"type": "string"
|
|
690
|
+
}
|
|
691
|
+
],
|
|
692
|
+
"id": "google-oauth",
|
|
693
|
+
"oauth2": {
|
|
694
|
+
"clientIDCredential": "oauth_client_id",
|
|
695
|
+
"clientSecretCredential": "oauth_client_secret",
|
|
696
|
+
"credentialMappings": [
|
|
697
|
+
{
|
|
698
|
+
"credential": "access_token",
|
|
699
|
+
"source": "access_token"
|
|
700
|
+
},
|
|
701
|
+
{
|
|
702
|
+
"credential": "refresh_token",
|
|
703
|
+
"source": "refresh_token"
|
|
704
|
+
}
|
|
705
|
+
],
|
|
706
|
+
"refresh": {
|
|
707
|
+
"missingExpiry": "reject",
|
|
708
|
+
"requiredScopes": [
|
|
709
|
+
"https://www.googleapis.com/auth/gmail.readonly",
|
|
710
|
+
"https://www.googleapis.com/auth/gmail.send"
|
|
711
|
+
],
|
|
712
|
+
"scopeSeparators": "whitespace",
|
|
713
|
+
"storedMissingExpiry": "refresh",
|
|
714
|
+
"terminalErrorCodes": [
|
|
715
|
+
"invalid_grant",
|
|
716
|
+
"invalid_client",
|
|
717
|
+
"unauthorized_client"
|
|
718
|
+
],
|
|
719
|
+
"tokenExchangeTimeout": "25s"
|
|
720
|
+
},
|
|
721
|
+
"scopes": [
|
|
722
|
+
"openid",
|
|
723
|
+
"https://www.googleapis.com/auth/userinfo.email",
|
|
724
|
+
"https://www.googleapis.com/auth/gmail.readonly",
|
|
725
|
+
"https://www.googleapis.com/auth/gmail.send"
|
|
726
|
+
],
|
|
727
|
+
"tokenEndpoint": "https://oauth2.googleapis.com/token"
|
|
728
|
+
},
|
|
729
|
+
"type": "oauth2"
|
|
730
|
+
},
|
|
731
|
+
{
|
|
732
|
+
"fields": [
|
|
733
|
+
{
|
|
734
|
+
"name": "service_account_key",
|
|
735
|
+
"required": true,
|
|
736
|
+
"type": "secretString"
|
|
737
|
+
},
|
|
738
|
+
{
|
|
739
|
+
"name": "delegated_user",
|
|
740
|
+
"required": true,
|
|
741
|
+
"type": "string"
|
|
742
|
+
},
|
|
743
|
+
{
|
|
744
|
+
"name": "access_token",
|
|
745
|
+
"required": false,
|
|
746
|
+
"type": "secretString"
|
|
747
|
+
},
|
|
748
|
+
{
|
|
749
|
+
"name": "primary_email",
|
|
750
|
+
"required": false,
|
|
751
|
+
"type": "string"
|
|
752
|
+
}
|
|
753
|
+
],
|
|
754
|
+
"id": "workspace-domain-delegation",
|
|
755
|
+
"serviceAccount": {
|
|
756
|
+
"jwtBearer": {
|
|
757
|
+
"audience": {
|
|
758
|
+
"fromKey": "token_uri"
|
|
759
|
+
},
|
|
760
|
+
"credentialCopies": [
|
|
761
|
+
{
|
|
762
|
+
"credential": "primary_email",
|
|
763
|
+
"fromCredential": "delegated_user"
|
|
764
|
+
}
|
|
765
|
+
],
|
|
766
|
+
"credentialMappings": [
|
|
767
|
+
{
|
|
768
|
+
"credential": "access_token",
|
|
769
|
+
"source": "access_token"
|
|
770
|
+
}
|
|
771
|
+
],
|
|
772
|
+
"issuer": {
|
|
773
|
+
"fromKey": "client_email"
|
|
774
|
+
},
|
|
775
|
+
"keyCredential": "service_account_key",
|
|
776
|
+
"lifetime": "1h",
|
|
777
|
+
"missingExpiry": "reject",
|
|
778
|
+
"privateKey": {
|
|
779
|
+
"fromKey": "private_key"
|
|
780
|
+
},
|
|
781
|
+
"scopes": [
|
|
782
|
+
"https://www.googleapis.com/auth/gmail.readonly",
|
|
783
|
+
"https://www.googleapis.com/auth/gmail.send"
|
|
784
|
+
],
|
|
785
|
+
"storedMissingExpiry": "refresh",
|
|
786
|
+
"subject": {
|
|
787
|
+
"fromCredential": "delegated_user"
|
|
788
|
+
},
|
|
789
|
+
"terminalErrorCodes": [
|
|
790
|
+
"invalid_grant",
|
|
791
|
+
"invalid_client",
|
|
792
|
+
"unauthorized_client"
|
|
793
|
+
],
|
|
794
|
+
"tokenEndpoint": {
|
|
795
|
+
"fromKey": "token_uri"
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
},
|
|
799
|
+
"type": "serviceAccount"
|
|
800
|
+
}
|
|
801
|
+
],
|
|
802
|
+
"refreshable": true
|
|
803
|
+
};
|
|
804
|
+
var CredentialFields = {
|
|
805
|
+
"access_token": "accessToken",
|
|
806
|
+
"delegated_user": "delegatedUser",
|
|
807
|
+
"oauth_client_id": "oauthClientId",
|
|
808
|
+
"oauth_client_secret": "oauthClientSecret",
|
|
809
|
+
"primary_email": "primaryEmail",
|
|
810
|
+
"refresh_token": "refreshToken",
|
|
811
|
+
"service_account_key": "serviceAccountKey"
|
|
812
|
+
};
|
|
813
|
+
|
|
814
|
+
// src/refresh.ts
|
|
564
815
|
var GmailCredentialRefreshDriver = class {
|
|
565
|
-
#
|
|
566
|
-
|
|
567
|
-
/** Inject the token request transport and clock for deterministic verification. */
|
|
816
|
+
#manifestDriver;
|
|
817
|
+
/** Inject the token transport and clock without transferring ownership. */
|
|
568
818
|
constructor(fetchImplementation = fetch, now = () => /* @__PURE__ */ new Date()) {
|
|
569
819
|
if (!fetchImplementation || !now) throw new TypeError("Gmail token transport and clock are required");
|
|
570
|
-
this.#
|
|
571
|
-
|
|
820
|
+
this.#manifestDriver = new import_oauthtoken.ManifestCredentialRefreshDriver({
|
|
821
|
+
providerName: "Google",
|
|
822
|
+
auth: Authorization,
|
|
823
|
+
credentialFields: CredentialFields,
|
|
824
|
+
fetch: fetchImplementation,
|
|
825
|
+
now
|
|
826
|
+
});
|
|
572
827
|
}
|
|
573
|
-
/** Refresh absent credentials
|
|
828
|
+
/** Refresh absent credentials and tokens approaching expiry, including missing expiry. */
|
|
574
829
|
refreshRequired(state) {
|
|
575
830
|
return (0, import_oauthtoken.isRefreshRequired)(Boolean(state.credentials.accessToken.reveal()), state.expiresAt, state.now, "refresh");
|
|
576
831
|
}
|
|
577
|
-
/**
|
|
832
|
+
/** Apply Gmail's method and delegated mailbox checks before the declared token exchange. */
|
|
578
833
|
async refresh(state, signal) {
|
|
579
834
|
const credentials = state.credentials;
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
};
|
|
592
|
-
}
|
|
593
|
-
if (credentials.authMethodId !== WorkspaceDomainDelegationAuthMethodID) throw new import_connectors_sdk2.ReauthorizationRequiredError();
|
|
835
|
+
const method = credentials.authMethodId || GoogleOAuthAuthMethodID;
|
|
836
|
+
if (method !== GoogleOAuthAuthMethodID && method !== WorkspaceDomainDelegationAuthMethodID)
|
|
837
|
+
throw new TypeError("Gmail authorization method is not supported");
|
|
838
|
+
if (method !== WorkspaceDomainDelegationAuthMethodID) return this.#manifestDriver.refresh(state, signal);
|
|
839
|
+
this.#validateServiceAccountKey(credentials.serviceAccountKey?.reveal() ?? "");
|
|
840
|
+
const delegatedUser = (credentials.delegatedUser ?? "").trim();
|
|
841
|
+
if (!delegatedUser || !delegatedUser.includes("@")) throw new import_connectors_sdk3.ReauthorizationRequiredError();
|
|
842
|
+
const result = await this.#manifestDriver.refresh({ ...state, credentials: { ...credentials, delegatedUser } }, signal);
|
|
843
|
+
return { ...result, credentials: { ...result.credentials, delegatedUser: credentials.delegatedUser } };
|
|
844
|
+
}
|
|
845
|
+
#validateServiceAccountKey(raw) {
|
|
594
846
|
let key;
|
|
595
847
|
try {
|
|
596
|
-
|
|
848
|
+
const parsed = JSON.parse(raw);
|
|
849
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new TypeError();
|
|
850
|
+
key = parsed;
|
|
597
851
|
} catch {
|
|
598
|
-
throw new
|
|
852
|
+
throw new import_connectors_sdk3.ReauthorizationRequiredError();
|
|
599
853
|
}
|
|
600
|
-
|
|
601
|
-
if (new URL(key.token_uri).protocol !== "https:" || !delegatedUser || !parseMailbox(delegatedUser)) throw new import_connectors_sdk2.ReauthorizationRequiredError();
|
|
602
|
-
let assertion;
|
|
854
|
+
if (typeof key.client_email !== "string" || !key.client_email || typeof key.private_key !== "string" || !key.private_key || typeof key.token_uri !== "string" || !key.token_uri) throw new import_connectors_sdk3.ReauthorizationRequiredError();
|
|
603
855
|
try {
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
subject: delegatedUser,
|
|
607
|
-
audience: key.token_uri,
|
|
608
|
-
scope: RequiredGmailScopes.join(" "),
|
|
609
|
-
issuedAt: this.#now(),
|
|
610
|
-
lifetimeMs: 36e5
|
|
611
|
-
}, (0, import_oauthtoken.parseRSAPrivateKeyPEM)(key.private_key));
|
|
856
|
+
const endpoint = new URL(key.token_uri);
|
|
857
|
+
if (endpoint.protocol !== "https:" || !endpoint.hostname) throw new TypeError();
|
|
612
858
|
} catch {
|
|
613
|
-
throw new
|
|
859
|
+
throw new import_connectors_sdk3.ReauthorizationRequiredError();
|
|
614
860
|
}
|
|
615
|
-
const token = await this.#tokenEndpoint(key.token_uri).exchangeJWTBearerAssertion(assertion, signal);
|
|
616
|
-
this.#verifyScopes(token.scope);
|
|
617
|
-
return {
|
|
618
|
-
credentials: { ...credentials, accessToken: token.accessToken, primaryEmail: credentials.delegatedUser ?? "" },
|
|
619
|
-
expiresAt: new Date(this.#now().getTime() + token.expiresInMs)
|
|
620
|
-
};
|
|
621
|
-
}
|
|
622
|
-
#tokenEndpoint(url) {
|
|
623
|
-
return new import_oauthtoken.TokenEndpoint({ providerName: "Google", url, terminalErrorCodes: TerminalErrorCodes, fetch: this.#fetch });
|
|
624
|
-
}
|
|
625
|
-
#verifyScopes(scope) {
|
|
626
|
-
if (scope && !(0, import_oauthtoken.hasAllScopes)(scope, RequiredGmailScopes)) throw new import_connectors_sdk2.ReauthorizationRequiredError();
|
|
627
861
|
}
|
|
628
862
|
};
|
|
629
863
|
|
|
630
864
|
// src/send.ts
|
|
631
|
-
var
|
|
865
|
+
var import_connectors_sdk4 = require("@superdurable/connectors-sdk");
|
|
632
866
|
var import_providerhttp2 = require("@superdurable/connectors-sdk/providerhttp");
|
|
633
867
|
var import_singledispatch = require("@superdurable/connectors-sdk/singledispatch");
|
|
634
868
|
var import_promises = require("timers/promises");
|
|
@@ -741,7 +975,7 @@ var GmailSender = class {
|
|
|
741
975
|
const budget = new GmailSendAttemptBudget(call.context.cancellationSignal, dexDeadline);
|
|
742
976
|
if (!budget.sendSignal()) {
|
|
743
977
|
await recordPreSendRetry(fence);
|
|
744
|
-
return (0,
|
|
978
|
+
return (0, import_connectors_sdk4.newMutationRetry)(failure("sendMessage", "AVAILABILITY", "too little of the Execute attempt is left to send safely, so nothing was sent"));
|
|
745
979
|
}
|
|
746
980
|
let credentials;
|
|
747
981
|
try {
|
|
@@ -773,7 +1007,7 @@ var GmailSender = class {
|
|
|
773
1007
|
const budget = new GmailSendAttemptBudget(call.context.cancellationSignal, dexDeadline);
|
|
774
1008
|
if (!budget.sendSignal()) {
|
|
775
1009
|
await recordPreSendRetry(fence);
|
|
776
|
-
return (0,
|
|
1010
|
+
return (0, import_connectors_sdk4.newMutationRetry)(failure("replyToMessage", "AVAILABILITY", "too little of the Execute attempt is left to send safely, so nothing was sent"));
|
|
777
1011
|
}
|
|
778
1012
|
let credentials;
|
|
779
1013
|
try {
|
|
@@ -800,9 +1034,9 @@ var GmailSender = class {
|
|
|
800
1034
|
if (found) return this.#sentMessage(call, budget, credentials, ReplyToMessageOutcomes, { raw: new Uint8Array(), recipients: [], requestedThreadId: "", hasPreSendSearch: true }, found, this.#receipt(call));
|
|
801
1035
|
} catch {
|
|
802
1036
|
await recordPreSendRetry(fence);
|
|
803
|
-
return (0,
|
|
1037
|
+
return (0, import_connectors_sdk4.newMutationRetry)(failure("replyToMessage", "AVAILABILITY", "Gmail sent-mail search did not answer before the reply"));
|
|
804
1038
|
}
|
|
805
|
-
if (fence.decide().kind === "readBackRequired") return (0,
|
|
1039
|
+
if (fence.decide().kind === "readBackRequired") return (0, import_connectors_sdk4.newMutationRetry)(failure("replyToMessage", "AVAILABILITY", "Gmail reply outcome is unknown; the sent-mail search found no message"));
|
|
806
1040
|
}
|
|
807
1041
|
let source;
|
|
808
1042
|
try {
|
|
@@ -825,16 +1059,16 @@ var GmailSender = class {
|
|
|
825
1059
|
try {
|
|
826
1060
|
message = decodeGmailMessage(source.resource);
|
|
827
1061
|
} catch {
|
|
828
|
-
return (0,
|
|
1062
|
+
return (0, import_connectors_sdk4.newMutationBranch)(ReplyToMessageBranch.InvalidResponse, emptySend(), this.#receipt(call, gmailRequestID(source.response.headers), input.messageId), failure("replyToMessage", "PROTOCOL", "source message lacks reply metadata"));
|
|
829
1063
|
}
|
|
830
|
-
if (!message.threadId || !message.rfcMessageId) return (0,
|
|
1064
|
+
if (!message.threadId || !message.rfcMessageId) return (0, import_connectors_sdk4.newMutationBranch)(ReplyToMessageBranch.InvalidResponse, emptySend(), this.#receipt(call, gmailRequestID(source.response.headers), input.messageId), failure("replyToMessage", "PROTOCOL", "source message lacks reply metadata"));
|
|
831
1065
|
let recipient;
|
|
832
1066
|
try {
|
|
833
1067
|
recipient = replyRecipient(message);
|
|
834
1068
|
} catch {
|
|
835
|
-
return (0,
|
|
1069
|
+
return (0, import_connectors_sdk4.newMutationBranch)(ReplyToMessageBranch.InvalidResponse, emptySend(), this.#receipt(call, gmailRequestID(source.response.headers), input.messageId), failure("replyToMessage", "PROTOCOL", "Gmail returned an invalid source sender"));
|
|
836
1070
|
}
|
|
837
|
-
if (/[\r\n]/.test(message.subject + message.rfcMessageId + (message.references ?? ""))) return (0,
|
|
1071
|
+
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"));
|
|
838
1072
|
let raw;
|
|
839
1073
|
try {
|
|
840
1074
|
raw = buildReplyMIMEMessage(call.id, call.idempotencyKey ?? call.id, this.#messageID(call), credentials.primaryEmail, message, input);
|
|
@@ -863,21 +1097,21 @@ var GmailSender = class {
|
|
|
863
1097
|
if (found) return this.#sentMessage(call, budget, credentials, operation, message, found, this.#receipt(call));
|
|
864
1098
|
} catch {
|
|
865
1099
|
await recordPreSendRetry(fence);
|
|
866
|
-
return (0,
|
|
1100
|
+
return (0, import_connectors_sdk4.newMutationRetry)(failure(operation.operationId, "AVAILABILITY", `Gmail sent-mail search did not answer before the ${operation.requestName}`));
|
|
867
1101
|
}
|
|
868
1102
|
}
|
|
869
|
-
if (fence.decide().kind === "readBackRequired") return (0,
|
|
1103
|
+
if (fence.decide().kind === "readBackRequired") return (0, import_connectors_sdk4.newMutationRetry)(failure(operation.operationId, "AVAILABILITY", `Gmail ${operation.requestName} outcome is unknown; the sent-mail search found no message`));
|
|
870
1104
|
let response;
|
|
871
1105
|
try {
|
|
872
1106
|
response = await fence.dispatch((signal) => this.#provider.sendMessage(call, credentials, message.raw, message.requestedThreadId, signal));
|
|
873
1107
|
} catch (error) {
|
|
874
|
-
if (error instanceof import_singledispatch.InsufficientTimeError || error instanceof import_singledispatch.CheckpointError) return (0,
|
|
1108
|
+
if (error instanceof import_singledispatch.InsufficientTimeError || error instanceof import_singledispatch.CheckpointError) return (0, import_connectors_sdk4.newMutationRetry)(failure(operation.operationId, "AVAILABILITY", "too little of the Execute attempt is left to send safely, so nothing was sent"));
|
|
875
1109
|
if (error instanceof import_providerhttp2.ProviderTransportError && error.isProvablyNotSent || error instanceof import_providerhttp2.AddressRefusal) {
|
|
876
1110
|
await recordSafeResend(fence);
|
|
877
|
-
return (0,
|
|
1111
|
+
return (0, import_connectors_sdk4.newMutationRetry)(failure(operation.operationId, "TRANSPORT", `Gmail ${operation.requestName} request was not dispatched`));
|
|
878
1112
|
}
|
|
879
1113
|
if (error instanceof import_providerhttp2.BodyTooLargeError && error.status) return this.#classifySendStatus(call, fence, budget, credentials, operation, message, error.status, error.headers ?? {}, void 0);
|
|
880
|
-
return this.#confirmPossiblySent(call, budget, credentials, operation, message, "TRANSPORT", `Gmail ${operation.requestName} outcome is unknown`, this.#receipt(call));
|
|
1114
|
+
return this.#confirmPossiblySent(call, fence, budget, credentials, operation, message, "TRANSPORT", `Gmail ${operation.requestName} outcome is unknown`, this.#receipt(call));
|
|
881
1115
|
}
|
|
882
1116
|
const receipt = this.#receipt(call, gmailRequestID(response.response.headers));
|
|
883
1117
|
const isAccepted = response.response.status >= 200 && response.response.status < 300;
|
|
@@ -892,11 +1126,10 @@ var GmailSender = class {
|
|
|
892
1126
|
}
|
|
893
1127
|
if (status === 503) {
|
|
894
1128
|
const lookup = await this.#pollSentMessage(call, budget, credentials);
|
|
895
|
-
if (lookup.sent) return this.#
|
|
896
|
-
await recordSafeResend(fence);
|
|
1129
|
+
if (lookup.sent) return this.#sentAfterDispatch(call, fence, budget, credentials, operation, message, lookup.sent, receipt);
|
|
897
1130
|
return retryAfterRefusal(operation.operationId, "AVAILABILITY", `Gmail ${operation.requestName} is temporarily unavailable`, headers);
|
|
898
1131
|
}
|
|
899
|
-
if (status >= 500) return this.#confirmPossiblySent(call, budget, credentials, operation, message, "AVAILABILITY", `Gmail ${operation.requestName} outcome is unknown`, receipt);
|
|
1132
|
+
if (status >= 500) return this.#confirmPossiblySent(call, fence, budget, credentials, operation, message, "AVAILABILITY", `Gmail ${operation.requestName} outcome is unknown`, receipt);
|
|
900
1133
|
if (status < 200 || status >= 300) {
|
|
901
1134
|
if (call.context.attempt > 1) {
|
|
902
1135
|
try {
|
|
@@ -905,19 +1138,24 @@ var GmailSender = class {
|
|
|
905
1138
|
} catch {
|
|
906
1139
|
}
|
|
907
1140
|
}
|
|
908
|
-
return (0,
|
|
1141
|
+
return (0, import_connectors_sdk4.newMutationBranch)(operation.providerRejectedBranch, emptySend(), receipt, failure(operation.operationId, statusFailureKind(status), operation.rejectionMessage));
|
|
909
1142
|
}
|
|
910
1143
|
if (!sentResponse) {
|
|
911
1144
|
const lookup = await this.#pollSentMessage(call, budget, credentials);
|
|
912
|
-
return this.#
|
|
1145
|
+
if (lookup.sent) return this.#sentAfterDispatch(call, fence, budget, credentials, operation, message, lookup.sent, receipt);
|
|
1146
|
+
return this.#sentMessage(call, budget, credentials, operation, message, { id: "", threadId: message.requestedThreadId }, receipt);
|
|
913
1147
|
}
|
|
914
1148
|
return this.#sentMessage(call, budget, credentials, operation, message, sentResponse, receipt);
|
|
915
1149
|
}
|
|
916
|
-
async #confirmPossiblySent(call, budget, credentials, operation, message, kind, reason, receipt) {
|
|
1150
|
+
async #confirmPossiblySent(call, fence, budget, credentials, operation, message, kind, reason, receipt) {
|
|
917
1151
|
const lookup = await this.#pollSentMessage(call, budget, credentials);
|
|
918
|
-
if (lookup.sent) return this.#
|
|
1152
|
+
if (lookup.sent) return this.#sentAfterDispatch(call, fence, budget, credentials, operation, message, lookup.sent, receipt);
|
|
919
1153
|
const suffix = lookup.hadError ? "the sent-mail search did not answer" : "the sent-mail search found no message";
|
|
920
|
-
return (0,
|
|
1154
|
+
return (0, import_connectors_sdk4.newMutationRetry)(failure(operation.operationId, kind, `${reason}; ${suffix}`));
|
|
1155
|
+
}
|
|
1156
|
+
async #sentAfterDispatch(call, fence, budget, credentials, operation, message, sent, receipt) {
|
|
1157
|
+
if (sent.id) await recordProviderIdentity(fence, sent.id);
|
|
1158
|
+
return this.#sentMessage(call, budget, credentials, operation, message, sent, receipt);
|
|
921
1159
|
}
|
|
922
1160
|
async #sentMessage(call, budget, credentials, operation, message, sent, receipt) {
|
|
923
1161
|
let threadId = sent.threadId;
|
|
@@ -929,7 +1167,7 @@ var GmailSender = class {
|
|
|
929
1167
|
threadId = message.requestedThreadId;
|
|
930
1168
|
}
|
|
931
1169
|
}
|
|
932
|
-
return (0,
|
|
1170
|
+
return (0, import_connectors_sdk4.newMutationBranch)(operation.sentBranch, { sender: credentials.primaryEmail, recipients: message.recipients, messageId: sent.id, threadId }, { ...receipt, providerObjectId: sent.id });
|
|
933
1171
|
}
|
|
934
1172
|
async #pollSentMessage(call, budget, credentials) {
|
|
935
1173
|
let hadError = false;
|
|
@@ -985,23 +1223,23 @@ function emptySend() {
|
|
|
985
1223
|
return { sender: "", recipients: [], messageId: "", threadId: "" };
|
|
986
1224
|
}
|
|
987
1225
|
function defect(operation, kind, message) {
|
|
988
|
-
return (0,
|
|
1226
|
+
return (0, import_connectors_sdk4.newMutationBranch)("defect", emptySend(), (0, import_connectors_sdk4.zeroReceipt)(), failure(operation, kind, message));
|
|
989
1227
|
}
|
|
990
1228
|
function retryAfterRefusal(operation, kind, message, headers) {
|
|
991
1229
|
try {
|
|
992
|
-
return (0,
|
|
1230
|
+
return (0, import_connectors_sdk4.newMutationRetry)(failure(operation, kind, message), gmailRetryAfterMs(headers));
|
|
993
1231
|
} catch {
|
|
994
|
-
return (0,
|
|
1232
|
+
return (0, import_connectors_sdk4.newMutationRetry)(failure(operation, "PROTOCOL", "Gmail returned an invalid Retry-After header"));
|
|
995
1233
|
}
|
|
996
1234
|
}
|
|
997
1235
|
function classifySourceFailure(status, headers, receipt) {
|
|
998
1236
|
if (status === 0 || status === 429 || status >= 500) return retryAfterRefusal("replyToMessage", "AVAILABILITY", "Gmail source message is temporarily unavailable", headers);
|
|
999
|
-
if (status >= 200 && status < 300) return (0,
|
|
1000
|
-
return (0,
|
|
1237
|
+
if (status >= 200 && status < 300) return (0, import_connectors_sdk4.newMutationBranch)(ReplyToMessageBranch.InvalidResponse, emptySend(), receipt, failure("replyToMessage", "PROTOCOL", "Gmail returned an invalid source message response"));
|
|
1238
|
+
return (0, import_connectors_sdk4.newMutationBranch)(ReplyToMessageBranch.ProviderRejected, emptySend(), receipt, failure("replyToMessage", statusFailureKind(status), "Gmail rejected the source message lookup"));
|
|
1001
1239
|
}
|
|
1002
1240
|
|
|
1003
1241
|
// src/client.ts
|
|
1004
|
-
var
|
|
1242
|
+
var import_connectors_sdk5 = require("@superdurable/connectors-sdk");
|
|
1005
1243
|
var import_providerhttp3 = require("@superdurable/connectors-sdk/providerhttp");
|
|
1006
1244
|
var GmailClient = class {
|
|
1007
1245
|
#http;
|
|
@@ -1046,21 +1284,21 @@ var GetMessageOperation = class {
|
|
|
1046
1284
|
/** Classify one Gmail message read as a branch or safe retry. */
|
|
1047
1285
|
async invoke(call, input) {
|
|
1048
1286
|
if (!GetMessageInputSchema.safeParse(input).success || !input.messageId.trim()) {
|
|
1049
|
-
return (0,
|
|
1287
|
+
return (0, import_connectors_sdk5.newQueryBranch)(GetMessageBranch.Defect, emptyMessage(), (0, import_connectors_sdk5.zeroReceipt)(), gmailFailure("getMessage", "VALIDATION", "message ID is required"));
|
|
1050
1288
|
}
|
|
1051
1289
|
let credentials;
|
|
1052
1290
|
try {
|
|
1053
1291
|
credentials = await this.#http.resolveCredentials(call, call.context.cancellationSignal);
|
|
1054
1292
|
} catch {
|
|
1055
|
-
return (0,
|
|
1293
|
+
return (0, import_connectors_sdk5.newQueryBranch)(GetMessageBranch.Defect, emptyMessage(), (0, import_connectors_sdk5.zeroReceipt)(), gmailFailure("getMessage", "AUTHENTICATION", "connection credentials are unavailable"));
|
|
1056
1294
|
}
|
|
1057
1295
|
let result;
|
|
1058
1296
|
try {
|
|
1059
1297
|
result = await this.#provider.readMessage(call, credentials, input.messageId, "full", call.context.cancellationSignal);
|
|
1060
1298
|
} catch (error) {
|
|
1061
|
-
if (error instanceof GmailCredentialError) return (0,
|
|
1299
|
+
if (error instanceof GmailCredentialError) return (0, import_connectors_sdk5.newQueryBranch)(GetMessageBranch.Defect, emptyMessage(), (0, import_connectors_sdk5.zeroReceipt)(), gmailFailure("getMessage", "AUTHENTICATION", "connection credentials are unavailable"));
|
|
1062
1300
|
if (error instanceof import_providerhttp3.BodyTooLargeError && error.status && error.status >= 200 && error.status < 300) {
|
|
1063
|
-
return (0,
|
|
1301
|
+
return (0, import_connectors_sdk5.newQueryBranch)(GetMessageBranch.InvalidResponse, emptyMessage(), (0, import_connectors_sdk5.zeroReceipt)(), gmailFailure("getMessage", "PROTOCOL", "Gmail returned an invalid or oversized message response"));
|
|
1064
1302
|
}
|
|
1065
1303
|
const status = error instanceof import_providerhttp3.BodyTooLargeError ? error.status ?? 0 : 0;
|
|
1066
1304
|
const headers = error instanceof import_providerhttp3.BodyTooLargeError ? error.headers ?? {} : {};
|
|
@@ -1071,9 +1309,9 @@ var GetMessageOperation = class {
|
|
|
1071
1309
|
try {
|
|
1072
1310
|
message = decodeGmailMessage(result.resource);
|
|
1073
1311
|
} catch {
|
|
1074
|
-
return (0,
|
|
1312
|
+
return (0, import_connectors_sdk5.newQueryBranch)(GetMessageBranch.InvalidResponse, emptyMessage(), receiptFor(call, this.#now(), gmailRequestID(result.response.headers), input.messageId), gmailFailure("getMessage", "PROTOCOL", "Gmail returned an invalid message"));
|
|
1075
1313
|
}
|
|
1076
|
-
return (0,
|
|
1314
|
+
return (0, import_connectors_sdk5.newQueryBranch)(GetMessageBranch.Read, message, {
|
|
1077
1315
|
provider: "gmail",
|
|
1078
1316
|
providerObjectId: message.messageId,
|
|
1079
1317
|
providerRequestId: gmailRequestID(result.response.headers),
|
|
@@ -1103,22 +1341,23 @@ function classifyReadFailure(status, headers) {
|
|
|
1103
1341
|
try {
|
|
1104
1342
|
retryAfterMs = gmailRetryAfterMs(headers);
|
|
1105
1343
|
} catch {
|
|
1106
|
-
return (0,
|
|
1344
|
+
return (0, import_connectors_sdk5.newQueryRetry)(gmailFailure("getMessage", "PROTOCOL", "Gmail returned an invalid Retry-After header"));
|
|
1107
1345
|
}
|
|
1108
|
-
return (0,
|
|
1346
|
+
return (0, import_connectors_sdk5.newQueryRetry)(gmailFailure("getMessage", "AVAILABILITY", "Gmail message is temporarily unavailable"), retryAfterMs);
|
|
1109
1347
|
}
|
|
1110
|
-
if (status === 404) return (0,
|
|
1348
|
+
if (status === 404) return (0, import_connectors_sdk5.newQueryBranch)(GetMessageBranch.NotFound, emptyMessage(), (0, import_connectors_sdk5.zeroReceipt)());
|
|
1111
1349
|
if (status >= 200 && status < 300) {
|
|
1112
|
-
return (0,
|
|
1350
|
+
return (0, import_connectors_sdk5.newQueryBranch)(GetMessageBranch.InvalidResponse, emptyMessage(), (0, import_connectors_sdk5.zeroReceipt)(), gmailFailure("getMessage", "PROTOCOL", "Gmail returned an invalid or oversized message response"));
|
|
1113
1351
|
}
|
|
1114
|
-
return (0,
|
|
1352
|
+
return (0, import_connectors_sdk5.newQueryBranch)(GetMessageBranch.ProviderRejected, emptyMessage(), (0, import_connectors_sdk5.zeroReceipt)(), gmailFailure("getMessage", statusFailureKind(status), "Gmail message lookup failed"));
|
|
1115
1353
|
}
|
|
1116
1354
|
|
|
1117
1355
|
// src/connection.ts
|
|
1118
|
-
var
|
|
1356
|
+
var import_connectors_sdk7 = require("@superdurable/connectors-sdk");
|
|
1119
1357
|
|
|
1120
1358
|
// src/generated/connection.ts
|
|
1121
|
-
var
|
|
1359
|
+
var import_connectors_sdk6 = require("@superdurable/connectors-sdk");
|
|
1360
|
+
var import_projectconfig = require("@superdurable/connectors-sdk/projectconfig");
|
|
1122
1361
|
var Connection = class {
|
|
1123
1362
|
/** Stable provider and connection name. */
|
|
1124
1363
|
reference;
|
|
@@ -1126,47 +1365,38 @@ var Connection = class {
|
|
|
1126
1365
|
operations;
|
|
1127
1366
|
/** Validate a reference and bind operations. */
|
|
1128
1367
|
constructor(reference, operations) {
|
|
1129
|
-
this.reference =
|
|
1368
|
+
this.reference = import_connectors_sdk6.ConnectionRefSchema.parse(reference);
|
|
1130
1369
|
if (this.reference.provider !== ProviderID2) throw new TypeError("connection provider differs from the manifest");
|
|
1131
1370
|
if (!operations) throw new TypeError("connector operations are required");
|
|
1132
1371
|
this.operations = operations;
|
|
1133
1372
|
}
|
|
1134
1373
|
};
|
|
1374
|
+
function newProjectCredentialProvider(project, connectionName, decode, encode, decodeShared) {
|
|
1375
|
+
return (0, import_projectconfig.newRefreshingCredentialProvider)(project.connections, { connectorId: ConnectorID2, connectionName }, decode, encode, decodeShared);
|
|
1376
|
+
}
|
|
1135
1377
|
|
|
1136
1378
|
// src/connection.ts
|
|
1137
1379
|
var GmailConnection = class extends Connection {
|
|
1138
1380
|
/** Bind operation implementations to a static named Google connection. */
|
|
1139
1381
|
constructor(operations, reference) {
|
|
1140
1382
|
if (!operations) throw new TypeError("Gmail connector operations are required");
|
|
1141
|
-
const validatedReference =
|
|
1383
|
+
const validatedReference = import_connectors_sdk7.ConnectionRefSchema.parse(reference);
|
|
1142
1384
|
if (validatedReference.provider !== "google") throw new TypeError("Gmail connection provider must be google");
|
|
1143
1385
|
super(validatedReference, operations);
|
|
1144
1386
|
}
|
|
1145
1387
|
};
|
|
1146
1388
|
|
|
1147
1389
|
// src/project.ts
|
|
1148
|
-
var
|
|
1149
|
-
var
|
|
1150
|
-
var import_zod7 = require("zod");
|
|
1390
|
+
var import_connectors_sdk9 = require("@superdurable/connectors-sdk");
|
|
1391
|
+
var import_zod5 = require("zod");
|
|
1151
1392
|
|
|
1152
1393
|
// src/credential_codec.ts
|
|
1153
|
-
var
|
|
1154
|
-
var import_zod6 = require("zod");
|
|
1155
|
-
var StoredCredentialsSchema = import_zod6.z.object({
|
|
1156
|
-
auth_method: import_zod6.z.string().optional(),
|
|
1157
|
-
oauth_client_id: import_zod6.z.string().optional(),
|
|
1158
|
-
oauth_client_secret: import_zod6.z.string().optional(),
|
|
1159
|
-
access_token: import_zod6.z.string().optional(),
|
|
1160
|
-
refresh_token: import_zod6.z.string().optional(),
|
|
1161
|
-
primary_email: import_zod6.z.string().optional(),
|
|
1162
|
-
service_account_key: import_zod6.z.string().optional(),
|
|
1163
|
-
delegated_user: import_zod6.z.string().optional()
|
|
1164
|
-
});
|
|
1394
|
+
var import_connectors_sdk8 = require("@superdurable/connectors-sdk");
|
|
1165
1395
|
function decodeGmailCredentials(value) {
|
|
1166
|
-
return
|
|
1396
|
+
return completeCredentials(decodeGmailFields(value, false));
|
|
1167
1397
|
}
|
|
1168
1398
|
function decodeGmailSharedCredentials(value) {
|
|
1169
|
-
return
|
|
1399
|
+
return completeCredentials(decodeGmailFields(value, true));
|
|
1170
1400
|
}
|
|
1171
1401
|
function encodeGmailCredentials(credentials) {
|
|
1172
1402
|
const fields = { auth_method: credentials.authMethodId ?? GoogleOAuthAuthMethodID };
|
|
@@ -1181,46 +1411,46 @@ function encodeGmailCredentials(credentials) {
|
|
|
1181
1411
|
]) if (value) fields[name] = value;
|
|
1182
1412
|
return fields;
|
|
1183
1413
|
}
|
|
1184
|
-
function
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
primaryEmail: stored.primary_email ?? "",
|
|
1195
|
-
serviceAccountKey: new import_connectors_sdk7.SecretString(stored.service_account_key ?? ""),
|
|
1196
|
-
delegatedUser: stored.delegated_user ?? ""
|
|
1414
|
+
function completeCredentials(decoded) {
|
|
1415
|
+
return {
|
|
1416
|
+
authMethodId: decoded.authMethodId ?? GoogleOAuthAuthMethodID,
|
|
1417
|
+
oauthClientId: decoded.oauthClientId ?? "",
|
|
1418
|
+
oauthClientSecret: decoded.oauthClientSecret ?? new import_connectors_sdk8.SecretString(""),
|
|
1419
|
+
accessToken: decoded.accessToken ?? new import_connectors_sdk8.SecretString(""),
|
|
1420
|
+
refreshToken: decoded.refreshToken ?? new import_connectors_sdk8.SecretString(""),
|
|
1421
|
+
primaryEmail: decoded.primaryEmail ?? "",
|
|
1422
|
+
serviceAccountKey: decoded.serviceAccountKey ?? new import_connectors_sdk8.SecretString(""),
|
|
1423
|
+
delegatedUser: decoded.delegatedUser ?? ""
|
|
1197
1424
|
};
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
}
|
|
1203
|
-
|
|
1204
|
-
|
|
1425
|
+
}
|
|
1426
|
+
function decodeGmailFields(value, isShared) {
|
|
1427
|
+
try {
|
|
1428
|
+
return isShared ? decodeSharedCredentials(value) : decodeCredentials(value);
|
|
1429
|
+
} catch (error) {
|
|
1430
|
+
const message = error instanceof Error ? error.message : "";
|
|
1431
|
+
if (message.includes("is required")) {
|
|
1432
|
+
const method = value && typeof value === "object" && "auth_method" in value ? value.auth_method : "";
|
|
1433
|
+
throw new TypeError(method === "workspace-domain-delegation" ? "Gmail Workspace connection credentials are incomplete" : "Gmail OAuth connection credentials are incomplete");
|
|
1205
1434
|
}
|
|
1206
|
-
|
|
1207
|
-
|
|
1435
|
+
if (message.includes("auth_method is invalid")) throw new TypeError("Gmail authorization method is invalid");
|
|
1436
|
+
throw new TypeError("Gmail credential fields are invalid");
|
|
1437
|
+
}
|
|
1208
1438
|
}
|
|
1209
1439
|
|
|
1210
1440
|
// src/project.ts
|
|
1211
|
-
var ProjectGmailConfigurationSchema =
|
|
1212
|
-
endpoint:
|
|
1213
|
-
maxResponseBytes:
|
|
1214
|
-
maxMessageBytes:
|
|
1215
|
-
pollInterval:
|
|
1216
|
-
pollPageSize:
|
|
1441
|
+
var ProjectGmailConfigurationSchema = import_zod5.z.object({
|
|
1442
|
+
endpoint: import_zod5.z.string().optional(),
|
|
1443
|
+
maxResponseBytes: import_zod5.z.number().int().safe().optional(),
|
|
1444
|
+
maxMessageBytes: import_zod5.z.number().int().safe().optional(),
|
|
1445
|
+
pollInterval: import_zod5.z.number().int().safe().optional(),
|
|
1446
|
+
pollPageSize: import_zod5.z.number().int().safe().optional()
|
|
1217
1447
|
});
|
|
1218
1448
|
function newProjectConnection(project, connectionName, options = {}) {
|
|
1219
1449
|
return new GmailConnection(newProjectGmailClient(project, connectionName, options), { provider: ProviderID, name: connectionName });
|
|
1220
1450
|
}
|
|
1221
1451
|
function newProjectGmailClient(project, connectionName, options = {}) {
|
|
1222
1452
|
if (!project) throw new TypeError("Gmail connection requires the loaded project configuration");
|
|
1223
|
-
|
|
1453
|
+
import_connectors_sdk9.ConnectionRefSchema.parse({ provider: ProviderID, name: connectionName });
|
|
1224
1454
|
const entry = project.configuration.connections.find((connection) => connection.connectorId === ConnectorID && connection.connectionName === connectionName);
|
|
1225
1455
|
if (!entry) throw new TypeError("Gmail project connection is not configured");
|
|
1226
1456
|
if (entry.provider !== ProviderID) throw new TypeError("Gmail project connection provider differs from the manifest");
|
|
@@ -1232,40 +1462,40 @@ function newProjectGmailClient(project, connectionName, options = {}) {
|
|
|
1232
1462
|
...fields.pollInterval ? { pollIntervalMs: Math.ceil(fields.pollInterval / 1e6) } : {},
|
|
1233
1463
|
...fields.pollPageSize ? { pollPageSize: fields.pollPageSize } : {}
|
|
1234
1464
|
};
|
|
1235
|
-
const provider = (
|
|
1465
|
+
const provider = newProjectCredentialProvider(project, connectionName, decodeGmailCredentials, encodeGmailCredentials, decodeGmailSharedCredentials);
|
|
1236
1466
|
return new GmailClient(config, provider, options);
|
|
1237
1467
|
}
|
|
1238
1468
|
|
|
1239
1469
|
// src/generated/steps.ts
|
|
1240
|
-
var
|
|
1470
|
+
var import_connectors_sdk10 = require("@superdurable/connectors-sdk");
|
|
1241
1471
|
function newGetMessageStep(configuration) {
|
|
1242
1472
|
const { connection, connectionName, read, notFound, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
|
|
1243
1473
|
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
1244
|
-
return (0,
|
|
1245
|
-
(0,
|
|
1246
|
-
...notFound ? [(0,
|
|
1247
|
-
...providerRejected ? [(0,
|
|
1248
|
-
...invalidResponse ? [(0,
|
|
1249
|
-
...defect2 ? [(0,
|
|
1474
|
+
return (0, import_connectors_sdk10.newQueryStep)({ ...stepConfiguration, operation: connection.operations.getMessage(), connection: connection.reference, branches: [
|
|
1475
|
+
(0, import_connectors_sdk10.goToBranch)("read", read),
|
|
1476
|
+
...notFound ? [(0, import_connectors_sdk10.goToBranch)("notFound", notFound)] : [],
|
|
1477
|
+
...providerRejected ? [(0, import_connectors_sdk10.goToBranch)("providerRejected", providerRejected)] : [],
|
|
1478
|
+
...invalidResponse ? [(0, import_connectors_sdk10.goToBranch)("invalidResponse", invalidResponse)] : [],
|
|
1479
|
+
...defect2 ? [(0, import_connectors_sdk10.goToBranch)("defect", defect2)] : []
|
|
1250
1480
|
] });
|
|
1251
1481
|
}
|
|
1252
1482
|
function newSendMessageStep(configuration) {
|
|
1253
1483
|
const { connection, connectionName, sent, providerRejected, defect: defect2, ...stepConfiguration } = configuration;
|
|
1254
1484
|
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
1255
|
-
return (0,
|
|
1256
|
-
(0,
|
|
1257
|
-
...providerRejected ? [(0,
|
|
1258
|
-
...defect2 ? [(0,
|
|
1485
|
+
return (0, import_connectors_sdk10.newMutationStep)({ ...stepConfiguration, operation: connection.operations.sendMessage(), connection: connection.reference, branches: [
|
|
1486
|
+
(0, import_connectors_sdk10.goToBranch)("sent", sent),
|
|
1487
|
+
...providerRejected ? [(0, import_connectors_sdk10.goToBranch)("providerRejected", providerRejected)] : [],
|
|
1488
|
+
...defect2 ? [(0, import_connectors_sdk10.goToBranch)("defect", defect2)] : []
|
|
1259
1489
|
] });
|
|
1260
1490
|
}
|
|
1261
1491
|
function newReplyToMessageStep(configuration) {
|
|
1262
1492
|
const { connection, connectionName, sent, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
|
|
1263
1493
|
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
1264
|
-
return (0,
|
|
1265
|
-
(0,
|
|
1266
|
-
...providerRejected ? [(0,
|
|
1267
|
-
...invalidResponse ? [(0,
|
|
1268
|
-
...defect2 ? [(0,
|
|
1494
|
+
return (0, import_connectors_sdk10.newMutationStep)({ ...stepConfiguration, operation: connection.operations.replyToMessage(), connection: connection.reference, branches: [
|
|
1495
|
+
(0, import_connectors_sdk10.goToBranch)("sent", sent),
|
|
1496
|
+
...providerRejected ? [(0, import_connectors_sdk10.goToBranch)("providerRejected", providerRejected)] : [],
|
|
1497
|
+
...invalidResponse ? [(0, import_connectors_sdk10.goToBranch)("invalidResponse", invalidResponse)] : [],
|
|
1498
|
+
...defect2 ? [(0, import_connectors_sdk10.goToBranch)("defect", defect2)] : []
|
|
1269
1499
|
] });
|
|
1270
1500
|
}
|
|
1271
1501
|
|