@superdurable/connector-google-gmail 0.1.2 → 0.2.1

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.
@@ -4,6 +4,29 @@ import { z as z2 } from "zod";
4
4
  // src/generated/models.ts
5
5
  import { z } from "zod";
6
6
  import { SecretString } from "@superdurable/connectors-sdk";
7
+ var goTimeJSONPattern = /^(\d{4})-(\d{2})-(\d{2})T(\d{1,2}):(\d{2}):(\d{2})(?:[.,](\d+))?(Z|([+-])(\d{2}):(\d{2}))$/;
8
+ function isGoTimeJSON(value) {
9
+ const match = goTimeJSONPattern.exec(value);
10
+ if (!match) return false;
11
+ const [, yearText, monthText, dayText, hourText, minuteText, secondText, , zone, , zoneHourText, zoneMinuteText] = match;
12
+ const year = Number(yearText);
13
+ const month = Number(monthText);
14
+ const day = Number(dayText);
15
+ const isLeap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
16
+ const monthDays = [31, isLeap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
17
+ 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);
18
+ }
19
+ function canonicalGoTimeJSON(value) {
20
+ const match = goTimeJSONPattern.exec(value);
21
+ const [, year, month, day, hour, minute, second, fraction, zone, sign, zoneHour, zoneMinute] = match;
22
+ const clock = year + "-" + month + "-" + day + "T" + hour.padStart(2, "0") + ":" + minute + ":" + second;
23
+ const digits = (fraction ?? "").slice(0, 9).replace(/0+$/, "");
24
+ const offsetMinutes = zone === "Z" ? 0 : (Number(zoneHour) * 60 + Number(zoneMinute)) * (sign === "+" ? 1 : -1);
25
+ if (Math.abs(offsetMinutes) >= 1440) return value;
26
+ 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");
27
+ return clock + (digits ? "." + digits : "") + offset;
28
+ }
29
+ var GoTimeJSONSchema = z.string().refine(isGoTimeJSON, "invalid Go time.Time JSON timestamp").transform(canonicalGoTimeJSON);
7
30
  var ConfigSchema = z.object({
8
31
  "endpoint": z.string().optional(),
9
32
  "maxResponseBytes": z.number().int().optional(),
@@ -11,6 +34,82 @@ var ConfigSchema = z.object({
11
34
  "pollIntervalMs": z.number().int().optional(),
12
35
  "pollPageSize": z.number().int().optional()
13
36
  });
37
+ function decodeCredentials(value) {
38
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("credential fields are invalid");
39
+ const fields = value;
40
+ const allowed = /* @__PURE__ */ new Set(["auth_method", "access_token", "delegated_user", "oauth_client_id", "oauth_client_secret", "primary_email", "refresh_token", "service_account_key"]);
41
+ if (Object.keys(fields).some((key) => !allowed.has(key))) throw new TypeError("stored credential does not match the connector credential fields");
42
+ if (fields["access_token"] != null && !(typeof fields["access_token"] === "string")) throw new TypeError("credential access_token has an invalid type");
43
+ if (fields["delegated_user"] != null && !(typeof fields["delegated_user"] === "string")) throw new TypeError("credential delegated_user has an invalid type");
44
+ if (fields["oauth_client_id"] != null && !(typeof fields["oauth_client_id"] === "string")) throw new TypeError("credential oauth_client_id has an invalid type");
45
+ if (fields["oauth_client_secret"] != null && !(typeof fields["oauth_client_secret"] === "string")) throw new TypeError("credential oauth_client_secret has an invalid type");
46
+ if (fields["primary_email"] != null && !(typeof fields["primary_email"] === "string")) throw new TypeError("credential primary_email has an invalid type");
47
+ if (fields["refresh_token"] != null && !(typeof fields["refresh_token"] === "string")) throw new TypeError("credential refresh_token has an invalid type");
48
+ if (fields["service_account_key"] != null && !(typeof fields["service_account_key"] === "string")) throw new TypeError("credential service_account_key has an invalid type");
49
+ const selectedMethod = fields["auth_method"] ?? "";
50
+ if (typeof selectedMethod !== "string") throw new TypeError("credential auth_method is invalid");
51
+ const method = selectedMethod || "google-oauth";
52
+ const credentials = { authMethodId: method };
53
+ if (method === "google-oauth") {
54
+ if (!fields["oauth_client_id"]) throw new TypeError("credential oauth_client_id is required");
55
+ if (fields["oauth_client_id"]) credentials.oauthClientId = fields["oauth_client_id"];
56
+ if (!fields["oauth_client_secret"]) throw new TypeError("credential oauth_client_secret is required");
57
+ if (fields["oauth_client_secret"]) credentials.oauthClientSecret = new SecretString(fields["oauth_client_secret"]);
58
+ if (!fields["access_token"]) throw new TypeError("credential access_token is required");
59
+ if (fields["access_token"]) credentials.accessToken = new SecretString(fields["access_token"]);
60
+ if (!fields["refresh_token"]) throw new TypeError("credential refresh_token is required");
61
+ if (fields["refresh_token"]) credentials.refreshToken = new SecretString(fields["refresh_token"]);
62
+ if (!fields["primary_email"]) throw new TypeError("credential primary_email is required");
63
+ if (fields["primary_email"]) credentials.primaryEmail = fields["primary_email"];
64
+ } else if (method === "workspace-domain-delegation") {
65
+ if (!fields["service_account_key"]) throw new TypeError("credential service_account_key is required");
66
+ if (fields["service_account_key"]) credentials.serviceAccountKey = new SecretString(fields["service_account_key"]);
67
+ if (!fields["delegated_user"]) throw new TypeError("credential delegated_user is required");
68
+ if (fields["delegated_user"]) credentials.delegatedUser = fields["delegated_user"];
69
+ credentials.accessToken = new SecretString(fields["access_token"] ?? "");
70
+ credentials.primaryEmail = fields["primary_email"] ?? "";
71
+ } else {
72
+ throw new TypeError("credential auth_method is invalid");
73
+ }
74
+ return credentials;
75
+ }
76
+ function decodeSharedCredentials(value) {
77
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("credential fields are invalid");
78
+ const fields = value;
79
+ const allowed = /* @__PURE__ */ new Set(["auth_method", "access_token", "delegated_user", "oauth_client_id", "oauth_client_secret", "primary_email", "refresh_token", "service_account_key"]);
80
+ if (Object.keys(fields).some((key) => !allowed.has(key))) throw new TypeError("stored credential does not match the connector credential fields");
81
+ if (fields["access_token"] != null && !(typeof fields["access_token"] === "string")) throw new TypeError("credential access_token has an invalid type");
82
+ if (fields["delegated_user"] != null && !(typeof fields["delegated_user"] === "string")) throw new TypeError("credential delegated_user has an invalid type");
83
+ if (fields["oauth_client_id"] != null && !(typeof fields["oauth_client_id"] === "string")) throw new TypeError("credential oauth_client_id has an invalid type");
84
+ if (fields["oauth_client_secret"] != null && !(typeof fields["oauth_client_secret"] === "string")) throw new TypeError("credential oauth_client_secret has an invalid type");
85
+ if (fields["primary_email"] != null && !(typeof fields["primary_email"] === "string")) throw new TypeError("credential primary_email has an invalid type");
86
+ if (fields["refresh_token"] != null && !(typeof fields["refresh_token"] === "string")) throw new TypeError("credential refresh_token has an invalid type");
87
+ if (fields["service_account_key"] != null && !(typeof fields["service_account_key"] === "string")) throw new TypeError("credential service_account_key has an invalid type");
88
+ const selectedMethod = fields["auth_method"] ?? "";
89
+ if (typeof selectedMethod !== "string") throw new TypeError("credential auth_method is invalid");
90
+ const method = selectedMethod || "google-oauth";
91
+ const credentials = { authMethodId: method };
92
+ if (method === "google-oauth") {
93
+ if (!fields["oauth_client_id"]) throw new TypeError("credential oauth_client_id is required");
94
+ if (fields["oauth_client_id"]) credentials.oauthClientId = fields["oauth_client_id"];
95
+ if (fields["oauth_client_secret"]) credentials.oauthClientSecret = new SecretString(fields["oauth_client_secret"]);
96
+ if (!fields["access_token"]) throw new TypeError("credential access_token is required");
97
+ if (fields["access_token"]) credentials.accessToken = new SecretString(fields["access_token"]);
98
+ if (fields["refresh_token"]) credentials.refreshToken = new SecretString(fields["refresh_token"]);
99
+ if (!fields["primary_email"]) throw new TypeError("credential primary_email is required");
100
+ if (fields["primary_email"]) credentials.primaryEmail = fields["primary_email"];
101
+ } else if (method === "workspace-domain-delegation") {
102
+ if (fields["service_account_key"]) credentials.serviceAccountKey = new SecretString(fields["service_account_key"]);
103
+ if (!fields["delegated_user"]) throw new TypeError("credential delegated_user is required");
104
+ if (fields["delegated_user"]) credentials.delegatedUser = fields["delegated_user"];
105
+ if (!fields["access_token"]) throw new TypeError("credential access_token is required");
106
+ credentials.accessToken = new SecretString(fields["access_token"] ?? "");
107
+ credentials.primaryEmail = fields["primary_email"] ?? "";
108
+ } else {
109
+ throw new TypeError("credential auth_method is invalid");
110
+ }
111
+ return credentials;
112
+ }
14
113
  var GetMessageInputSchema = z.strictObject({
15
114
  "messageId": z.string()
16
115
  });
@@ -27,7 +126,7 @@ var MessageSchema = z.strictObject({
27
126
  "textBody": z.string().optional(),
28
127
  "htmlBody": z.string().optional(),
29
128
  "snippet": z.string().optional(),
30
- "receivedAt": z.iso.datetime({ offset: true }),
129
+ "receivedAt": GoTimeJSONSchema,
31
130
  "labelIds": z.array(z.string()).optional()
32
131
  });
33
132
  var SendMessageInputSchema = z.strictObject({
@@ -491,81 +590,209 @@ function parseSentResponse(response) {
491
590
 
492
591
  // src/refresh.ts
493
592
  import { ReauthorizationRequiredError } from "@superdurable/connectors-sdk";
494
- import {
495
- hasAllScopes,
496
- isRefreshRequired,
497
- parseRSAPrivateKeyPEM,
498
- signJWTBearerAssertion,
499
- TokenEndpoint
500
- } from "@superdurable/connectors-sdk/oauthtoken";
501
- import { z as z5 } from "zod";
502
- var GoogleOAuthTokenEndpoint = "https://oauth2.googleapis.com/token";
503
- var RequiredGmailScopes = ["https://www.googleapis.com/auth/gmail.readonly", "https://www.googleapis.com/auth/gmail.send"];
504
- var TerminalErrorCodes = ["invalid_grant", "invalid_client", "unauthorized_client"];
505
- var ServiceAccountKeySchema = z5.object({ client_email: z5.string().min(1), private_key: z5.string().min(1), token_uri: z5.url() });
593
+ import { isRefreshRequired, ManifestCredentialRefreshDriver } from "@superdurable/connectors-sdk/oauthtoken";
594
+
595
+ // src/generated/refresh.ts
596
+ var Authorization = {
597
+ "defaultMethod": "google-oauth",
598
+ "methods": [
599
+ {
600
+ "fields": [
601
+ {
602
+ "name": "oauth_client_id",
603
+ "required": true,
604
+ "type": "string"
605
+ },
606
+ {
607
+ "name": "oauth_client_secret",
608
+ "required": true,
609
+ "type": "secretString"
610
+ },
611
+ {
612
+ "name": "access_token",
613
+ "required": true,
614
+ "type": "secretString"
615
+ },
616
+ {
617
+ "name": "refresh_token",
618
+ "required": true,
619
+ "type": "secretString"
620
+ },
621
+ {
622
+ "name": "primary_email",
623
+ "required": true,
624
+ "type": "string"
625
+ }
626
+ ],
627
+ "id": "google-oauth",
628
+ "oauth2": {
629
+ "clientIDCredential": "oauth_client_id",
630
+ "clientSecretCredential": "oauth_client_secret",
631
+ "credentialMappings": [
632
+ {
633
+ "credential": "access_token",
634
+ "source": "access_token"
635
+ },
636
+ {
637
+ "credential": "refresh_token",
638
+ "source": "refresh_token"
639
+ }
640
+ ],
641
+ "refresh": {
642
+ "missingExpiry": "reject",
643
+ "requiredScopes": [
644
+ "https://www.googleapis.com/auth/gmail.readonly",
645
+ "https://www.googleapis.com/auth/gmail.send"
646
+ ],
647
+ "scopeSeparators": "whitespace",
648
+ "storedMissingExpiry": "refresh",
649
+ "terminalErrorCodes": [
650
+ "invalid_grant",
651
+ "invalid_client",
652
+ "unauthorized_client"
653
+ ],
654
+ "tokenExchangeTimeout": "25s"
655
+ },
656
+ "scopes": [
657
+ "openid",
658
+ "https://www.googleapis.com/auth/userinfo.email",
659
+ "https://www.googleapis.com/auth/gmail.readonly",
660
+ "https://www.googleapis.com/auth/gmail.send"
661
+ ],
662
+ "tokenEndpoint": "https://oauth2.googleapis.com/token"
663
+ },
664
+ "type": "oauth2"
665
+ },
666
+ {
667
+ "fields": [
668
+ {
669
+ "name": "service_account_key",
670
+ "required": true,
671
+ "type": "secretString"
672
+ },
673
+ {
674
+ "name": "delegated_user",
675
+ "required": true,
676
+ "type": "string"
677
+ },
678
+ {
679
+ "name": "access_token",
680
+ "required": false,
681
+ "type": "secretString"
682
+ },
683
+ {
684
+ "name": "primary_email",
685
+ "required": false,
686
+ "type": "string"
687
+ }
688
+ ],
689
+ "id": "workspace-domain-delegation",
690
+ "serviceAccount": {
691
+ "jwtBearer": {
692
+ "audience": {
693
+ "fromKey": "token_uri"
694
+ },
695
+ "credentialCopies": [
696
+ {
697
+ "credential": "primary_email",
698
+ "fromCredential": "delegated_user"
699
+ }
700
+ ],
701
+ "credentialMappings": [
702
+ {
703
+ "credential": "access_token",
704
+ "source": "access_token"
705
+ }
706
+ ],
707
+ "issuer": {
708
+ "fromKey": "client_email"
709
+ },
710
+ "keyCredential": "service_account_key",
711
+ "lifetime": "1h",
712
+ "missingExpiry": "reject",
713
+ "privateKey": {
714
+ "fromKey": "private_key"
715
+ },
716
+ "scopes": [
717
+ "https://www.googleapis.com/auth/gmail.readonly",
718
+ "https://www.googleapis.com/auth/gmail.send"
719
+ ],
720
+ "storedMissingExpiry": "refresh",
721
+ "subject": {
722
+ "fromCredential": "delegated_user"
723
+ },
724
+ "terminalErrorCodes": [
725
+ "invalid_grant",
726
+ "invalid_client",
727
+ "unauthorized_client"
728
+ ],
729
+ "tokenEndpoint": {
730
+ "fromKey": "token_uri"
731
+ }
732
+ }
733
+ },
734
+ "type": "serviceAccount"
735
+ }
736
+ ],
737
+ "refreshable": true
738
+ };
739
+ var CredentialFields = {
740
+ "access_token": "accessToken",
741
+ "delegated_user": "delegatedUser",
742
+ "oauth_client_id": "oauthClientId",
743
+ "oauth_client_secret": "oauthClientSecret",
744
+ "primary_email": "primaryEmail",
745
+ "refresh_token": "refreshToken",
746
+ "service_account_key": "serviceAccountKey"
747
+ };
748
+
749
+ // src/refresh.ts
506
750
  var GmailCredentialRefreshDriver = class {
507
- #fetch;
508
- #now;
509
- /** Inject the token request transport and clock for deterministic verification. */
751
+ #manifestDriver;
752
+ /** Inject the token transport and clock without transferring ownership. */
510
753
  constructor(fetchImplementation = fetch, now = () => /* @__PURE__ */ new Date()) {
511
754
  if (!fetchImplementation || !now) throw new TypeError("Gmail token transport and clock are required");
512
- this.#fetch = fetchImplementation;
513
- this.#now = now;
755
+ this.#manifestDriver = new ManifestCredentialRefreshDriver({
756
+ providerName: "Google",
757
+ auth: Authorization,
758
+ credentialFields: CredentialFields,
759
+ fetch: fetchImplementation,
760
+ now
761
+ });
514
762
  }
515
- /** Refresh absent credentials or tokens whose expiry is within five minutes. */
763
+ /** Refresh absent credentials and tokens approaching expiry, including missing expiry. */
516
764
  refreshRequired(state) {
517
765
  return isRefreshRequired(Boolean(state.credentials.accessToken.reveal()), state.expiresAt, state.now, "refresh");
518
766
  }
519
- /** Make one Google token exchange after the host admits and serializes refresh. */
767
+ /** Apply Gmail's method and delegated mailbox checks before the declared token exchange. */
520
768
  async refresh(state, signal) {
521
769
  const credentials = state.credentials;
522
- if (!credentials.authMethodId || credentials.authMethodId === GoogleOAuthAuthMethodID) {
523
- if (!credentials.oauthClientId || !credentials.oauthClientSecret || !credentials.refreshToken) throw new ReauthorizationRequiredError();
524
- const token2 = await this.#tokenEndpoint(GoogleOAuthTokenEndpoint).exchangeRefreshToken({
525
- id: credentials.oauthClientId,
526
- secret: credentials.oauthClientSecret,
527
- authenticationMethod: "client_secret_post"
528
- }, credentials.refreshToken, signal);
529
- this.#verifyScopes(token2.scope);
530
- return {
531
- credentials: { ...credentials, accessToken: token2.accessToken, refreshToken: token2.nextRefreshToken(credentials.refreshToken) },
532
- expiresAt: new Date(this.#now().getTime() + token2.expiresInMs)
533
- };
534
- }
535
- if (credentials.authMethodId !== WorkspaceDomainDelegationAuthMethodID) throw new ReauthorizationRequiredError();
770
+ const method = credentials.authMethodId || GoogleOAuthAuthMethodID;
771
+ if (method !== GoogleOAuthAuthMethodID && method !== WorkspaceDomainDelegationAuthMethodID)
772
+ throw new TypeError("Gmail authorization method is not supported");
773
+ if (method !== WorkspaceDomainDelegationAuthMethodID) return this.#manifestDriver.refresh(state, signal);
774
+ this.#validateServiceAccountKey(credentials.serviceAccountKey?.reveal() ?? "");
775
+ const delegatedUser = (credentials.delegatedUser ?? "").trim();
776
+ if (!delegatedUser || !delegatedUser.includes("@")) throw new ReauthorizationRequiredError();
777
+ const result = await this.#manifestDriver.refresh({ ...state, credentials: { ...credentials, delegatedUser } }, signal);
778
+ return { ...result, credentials: { ...result.credentials, delegatedUser: credentials.delegatedUser } };
779
+ }
780
+ #validateServiceAccountKey(raw) {
536
781
  let key;
537
782
  try {
538
- key = ServiceAccountKeySchema.parse(JSON.parse(credentials.serviceAccountKey?.reveal() ?? ""));
783
+ const parsed = JSON.parse(raw);
784
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new TypeError();
785
+ key = parsed;
539
786
  } catch {
540
787
  throw new ReauthorizationRequiredError();
541
788
  }
542
- const delegatedUser = credentials.delegatedUser;
543
- if (new URL(key.token_uri).protocol !== "https:" || !delegatedUser || !parseMailbox(delegatedUser)) throw new ReauthorizationRequiredError();
544
- let assertion;
789
+ 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 ReauthorizationRequiredError();
545
790
  try {
546
- assertion = signJWTBearerAssertion({
547
- issuer: key.client_email,
548
- subject: delegatedUser,
549
- audience: key.token_uri,
550
- scope: RequiredGmailScopes.join(" "),
551
- issuedAt: this.#now(),
552
- lifetimeMs: 36e5
553
- }, parseRSAPrivateKeyPEM(key.private_key));
791
+ const endpoint = new URL(key.token_uri);
792
+ if (endpoint.protocol !== "https:" || !endpoint.hostname) throw new TypeError();
554
793
  } catch {
555
794
  throw new ReauthorizationRequiredError();
556
795
  }
557
- const token = await this.#tokenEndpoint(key.token_uri).exchangeJWTBearerAssertion(assertion, signal);
558
- this.#verifyScopes(token.scope);
559
- return {
560
- credentials: { ...credentials, accessToken: token.accessToken, primaryEmail: credentials.delegatedUser ?? "" },
561
- expiresAt: new Date(this.#now().getTime() + token.expiresInMs)
562
- };
563
- }
564
- #tokenEndpoint(url) {
565
- return new TokenEndpoint({ providerName: "Google", url, terminalErrorCodes: TerminalErrorCodes, fetch: this.#fetch });
566
- }
567
- #verifyScopes(scope) {
568
- if (scope && !hasAllScopes(scope, RequiredGmailScopes)) throw new ReauthorizationRequiredError();
569
796
  }
570
797
  };
571
798
 
@@ -823,7 +1050,7 @@ var GmailSender = class {
823
1050
  return newMutationRetry(failure(operation.operationId, "TRANSPORT", `Gmail ${operation.requestName} request was not dispatched`));
824
1051
  }
825
1052
  if (error instanceof BodyTooLargeError2 && error.status) return this.#classifySendStatus(call, fence, budget, credentials, operation, message, error.status, error.headers ?? {}, void 0);
826
- return this.#confirmPossiblySent(call, budget, credentials, operation, message, "TRANSPORT", `Gmail ${operation.requestName} outcome is unknown`, this.#receipt(call));
1053
+ return this.#confirmPossiblySent(call, fence, budget, credentials, operation, message, "TRANSPORT", `Gmail ${operation.requestName} outcome is unknown`, this.#receipt(call));
827
1054
  }
828
1055
  const receipt = this.#receipt(call, gmailRequestID(response.response.headers));
829
1056
  const isAccepted = response.response.status >= 200 && response.response.status < 300;
@@ -838,11 +1065,10 @@ var GmailSender = class {
838
1065
  }
839
1066
  if (status === 503) {
840
1067
  const lookup = await this.#pollSentMessage(call, budget, credentials);
841
- if (lookup.sent) return this.#sentMessage(call, budget, credentials, operation, message, lookup.sent, receipt);
842
- await recordSafeResend(fence);
1068
+ if (lookup.sent) return this.#sentAfterDispatch(call, fence, budget, credentials, operation, message, lookup.sent, receipt);
843
1069
  return retryAfterRefusal(operation.operationId, "AVAILABILITY", `Gmail ${operation.requestName} is temporarily unavailable`, headers);
844
1070
  }
845
- if (status >= 500) return this.#confirmPossiblySent(call, budget, credentials, operation, message, "AVAILABILITY", `Gmail ${operation.requestName} outcome is unknown`, receipt);
1071
+ if (status >= 500) return this.#confirmPossiblySent(call, fence, budget, credentials, operation, message, "AVAILABILITY", `Gmail ${operation.requestName} outcome is unknown`, receipt);
846
1072
  if (status < 200 || status >= 300) {
847
1073
  if (call.context.attempt > 1) {
848
1074
  try {
@@ -855,16 +1081,21 @@ var GmailSender = class {
855
1081
  }
856
1082
  if (!sentResponse) {
857
1083
  const lookup = await this.#pollSentMessage(call, budget, credentials);
858
- return this.#sentMessage(call, budget, credentials, operation, message, lookup.sent ?? { id: "", threadId: message.requestedThreadId }, receipt);
1084
+ if (lookup.sent) return this.#sentAfterDispatch(call, fence, budget, credentials, operation, message, lookup.sent, receipt);
1085
+ return this.#sentMessage(call, budget, credentials, operation, message, { id: "", threadId: message.requestedThreadId }, receipt);
859
1086
  }
860
1087
  return this.#sentMessage(call, budget, credentials, operation, message, sentResponse, receipt);
861
1088
  }
862
- async #confirmPossiblySent(call, budget, credentials, operation, message, kind, reason, receipt) {
1089
+ async #confirmPossiblySent(call, fence, budget, credentials, operation, message, kind, reason, receipt) {
863
1090
  const lookup = await this.#pollSentMessage(call, budget, credentials);
864
- if (lookup.sent) return this.#sentMessage(call, budget, credentials, operation, message, lookup.sent, receipt);
1091
+ if (lookup.sent) return this.#sentAfterDispatch(call, fence, budget, credentials, operation, message, lookup.sent, receipt);
865
1092
  const suffix = lookup.hadError ? "the sent-mail search did not answer" : "the sent-mail search found no message";
866
1093
  return newMutationRetry(failure(operation.operationId, kind, `${reason}; ${suffix}`));
867
1094
  }
1095
+ async #sentAfterDispatch(call, fence, budget, credentials, operation, message, sent, receipt) {
1096
+ if (sent.id) await recordProviderIdentity(fence, sent.id);
1097
+ return this.#sentMessage(call, budget, credentials, operation, message, sent, receipt);
1098
+ }
868
1099
  async #sentMessage(call, budget, credentials, operation, message, sent, receipt) {
869
1100
  let threadId = sent.threadId;
870
1101
  if (!threadId && sent.id) {
@@ -1069,6 +1300,7 @@ import { ConnectionRefSchema as ConnectionRefSchema2 } from "@superdurable/conne
1069
1300
 
1070
1301
  // src/generated/connection.ts
1071
1302
  import { ConnectionRefSchema } from "@superdurable/connectors-sdk";
1303
+ import { newRefreshingCredentialProvider } from "@superdurable/connectors-sdk/projectconfig";
1072
1304
  var Connection = class {
1073
1305
  /** Stable provider and connection name. */
1074
1306
  reference;
@@ -1082,6 +1314,9 @@ var Connection = class {
1082
1314
  this.operations = operations;
1083
1315
  }
1084
1316
  };
1317
+ function newProjectCredentialProvider(project, connectionName, decode, encode, decodeShared) {
1318
+ return newRefreshingCredentialProvider(project.connections, { connectorId: ConnectorID2, connectionName }, decode, encode, decodeShared);
1319
+ }
1085
1320
 
1086
1321
  // src/connection.ts
1087
1322
  var GmailConnection = class extends Connection {
@@ -1096,27 +1331,15 @@ var GmailConnection = class extends Connection {
1096
1331
 
1097
1332
  // src/project.ts
1098
1333
  import { ConnectionRefSchema as ConnectionRefSchema3 } from "@superdurable/connectors-sdk";
1099
- import { newRefreshingCredentialProvider } from "@superdurable/connectors-sdk/projectconfig";
1100
- import { z as z7 } from "zod";
1334
+ import { z as z5 } from "zod";
1101
1335
 
1102
1336
  // src/credential_codec.ts
1103
1337
  import { SecretString as SecretString2 } from "@superdurable/connectors-sdk";
1104
- import { z as z6 } from "zod";
1105
- var StoredCredentialsSchema = z6.object({
1106
- auth_method: z6.string().optional(),
1107
- oauth_client_id: z6.string().optional(),
1108
- oauth_client_secret: z6.string().optional(),
1109
- access_token: z6.string().optional(),
1110
- refresh_token: z6.string().optional(),
1111
- primary_email: z6.string().optional(),
1112
- service_account_key: z6.string().optional(),
1113
- delegated_user: z6.string().optional()
1114
- });
1115
1338
  function decodeGmailCredentials(value) {
1116
- return decodeCredentialFields(value, false);
1339
+ return completeCredentials(decodeGmailFields(value, false));
1117
1340
  }
1118
1341
  function decodeGmailSharedCredentials(value) {
1119
- return decodeCredentialFields(value, true);
1342
+ return completeCredentials(decodeGmailFields(value, true));
1120
1343
  }
1121
1344
  function encodeGmailCredentials(credentials) {
1122
1345
  const fields = { auth_method: credentials.authMethodId ?? GoogleOAuthAuthMethodID };
@@ -1131,39 +1354,39 @@ function encodeGmailCredentials(credentials) {
1131
1354
  ]) if (value) fields[name] = value;
1132
1355
  return fields;
1133
1356
  }
1134
- function decodeCredentialFields(value, isShared) {
1135
- const fields = StoredCredentialsSchema.safeParse(value);
1136
- if (!fields.success) throw new TypeError("Gmail credential fields are invalid");
1137
- const stored = fields.data;
1138
- const credentials = {
1139
- authMethodId: stored.auth_method || GoogleOAuthAuthMethodID,
1140
- oauthClientId: stored.oauth_client_id ?? "",
1141
- oauthClientSecret: new SecretString2(stored.oauth_client_secret ?? ""),
1142
- accessToken: new SecretString2(stored.access_token ?? ""),
1143
- refreshToken: new SecretString2(stored.refresh_token ?? ""),
1144
- primaryEmail: stored.primary_email ?? "",
1145
- serviceAccountKey: new SecretString2(stored.service_account_key ?? ""),
1146
- delegatedUser: stored.delegated_user ?? ""
1357
+ function completeCredentials(decoded) {
1358
+ return {
1359
+ authMethodId: decoded.authMethodId ?? GoogleOAuthAuthMethodID,
1360
+ oauthClientId: decoded.oauthClientId ?? "",
1361
+ oauthClientSecret: decoded.oauthClientSecret ?? new SecretString2(""),
1362
+ accessToken: decoded.accessToken ?? new SecretString2(""),
1363
+ refreshToken: decoded.refreshToken ?? new SecretString2(""),
1364
+ primaryEmail: decoded.primaryEmail ?? "",
1365
+ serviceAccountKey: decoded.serviceAccountKey ?? new SecretString2(""),
1366
+ delegatedUser: decoded.delegatedUser ?? ""
1147
1367
  };
1148
- if (credentials.authMethodId === GoogleOAuthAuthMethodID) {
1149
- if (!credentials.oauthClientId || !credentials.primaryEmail || !isShared && (!credentials.oauthClientSecret?.reveal() || !credentials.refreshToken?.reveal()) || !credentials.accessToken.reveal()) {
1150
- throw new TypeError("Gmail OAuth connection credentials are incomplete");
1151
- }
1152
- } else if (credentials.authMethodId === WorkspaceDomainDelegationAuthMethodID) {
1153
- if (!credentials.delegatedUser || (isShared ? !credentials.accessToken.reveal() : !credentials.serviceAccountKey?.reveal())) {
1154
- throw new TypeError("Gmail Workspace connection credentials are incomplete");
1368
+ }
1369
+ function decodeGmailFields(value, isShared) {
1370
+ try {
1371
+ return isShared ? decodeSharedCredentials(value) : decodeCredentials(value);
1372
+ } catch (error) {
1373
+ const message = error instanceof Error ? error.message : "";
1374
+ if (message.includes("is required")) {
1375
+ const method = value && typeof value === "object" && "auth_method" in value ? value.auth_method : "";
1376
+ throw new TypeError(method === "workspace-domain-delegation" ? "Gmail Workspace connection credentials are incomplete" : "Gmail OAuth connection credentials are incomplete");
1155
1377
  }
1156
- } else throw new TypeError("Gmail authorization method is invalid");
1157
- return credentials;
1378
+ if (message.includes("auth_method is invalid")) throw new TypeError("Gmail authorization method is invalid");
1379
+ throw new TypeError("Gmail credential fields are invalid");
1380
+ }
1158
1381
  }
1159
1382
 
1160
1383
  // src/project.ts
1161
- var ProjectGmailConfigurationSchema = z7.object({
1162
- endpoint: z7.string().optional(),
1163
- maxResponseBytes: z7.number().int().safe().optional(),
1164
- maxMessageBytes: z7.number().int().safe().optional(),
1165
- pollInterval: z7.number().int().safe().optional(),
1166
- pollPageSize: z7.number().int().safe().optional()
1384
+ var ProjectGmailConfigurationSchema = z5.object({
1385
+ endpoint: z5.string().optional(),
1386
+ maxResponseBytes: z5.number().int().safe().optional(),
1387
+ maxMessageBytes: z5.number().int().safe().optional(),
1388
+ pollInterval: z5.number().int().safe().optional(),
1389
+ pollPageSize: z5.number().int().safe().optional()
1167
1390
  });
1168
1391
  function newProjectConnection(project, connectionName, options = {}) {
1169
1392
  return new GmailConnection(newProjectGmailClient(project, connectionName, options), { provider: ProviderID, name: connectionName });
@@ -1182,7 +1405,7 @@ function newProjectGmailClient(project, connectionName, options = {}) {
1182
1405
  ...fields.pollInterval ? { pollIntervalMs: Math.ceil(fields.pollInterval / 1e6) } : {},
1183
1406
  ...fields.pollPageSize ? { pollPageSize: fields.pollPageSize } : {}
1184
1407
  };
1185
- const provider = newRefreshingCredentialProvider(project.connections, { connectorId: ConnectorID, connectionName }, decodeGmailCredentials, encodeGmailCredentials, decodeGmailSharedCredentials);
1408
+ const provider = newProjectCredentialProvider(project, connectionName, decodeGmailCredentials, encodeGmailCredentials, decodeGmailSharedCredentials);
1186
1409
  return new GmailClient(config, provider, options);
1187
1410
  }
1188
1411
 
@@ -87,7 +87,7 @@ declare const MessageSchema: z.ZodObject<{
87
87
  textBody: z.ZodOptional<z.ZodString>;
88
88
  htmlBody: z.ZodOptional<z.ZodString>;
89
89
  snippet: z.ZodOptional<z.ZodString>;
90
- receivedAt: z.ZodISODateTime;
90
+ receivedAt: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
91
91
  labelIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
92
92
  }, z.core.$strict>;
93
93
  /** Runtime validator for ReplyToMessageInput. */
@@ -87,7 +87,7 @@ declare const MessageSchema: z.ZodObject<{
87
87
  textBody: z.ZodOptional<z.ZodString>;
88
88
  htmlBody: z.ZodOptional<z.ZodString>;
89
89
  snippet: z.ZodOptional<z.ZodString>;
90
- receivedAt: z.ZodISODateTime;
90
+ receivedAt: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
91
91
  labelIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
92
92
  }, z.core.$strict>;
93
93
  /** Runtime validator for ReplyToMessageInput. */