@superdurable/connector-google-docs 0.1.0 → 0.1.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.
package/README.md CHANGED
@@ -6,7 +6,9 @@ The manifest supplies generated models, factories, mocks, and refresh wiring
6
6
  for Google OAuth and Workspace domain delegation. The provider client bounds
7
7
  responses and text, reads only the first tab, and uses revision guards for
8
8
  writes. `createDocument` uses a single-dispatch fence and Drive app-property
9
- lookup to recover an earlier create without repeating an uncertain write.
9
+ lookup to recover an earlier create before every resend; an unknown outcome is
10
+ resent only up to the send cap (`maxSends`, default 3), and `uncertain` is
11
+ selected only at the cap.
10
12
 
11
13
  The runnable [policy documents example](examples/policy-documents/README.md)
12
14
  uses the static `policy-docs` connection and exercises every operation through
@@ -1,16 +1,18 @@
1
1
  {
2
2
  "connectorId": "google-docs",
3
- "releaseTag": "connectors/google/docs/go/v0.24.0",
3
+ "releaseTag": "connectors/google/docs/go/v0.24.1",
4
4
  "package": {
5
5
  "ecosystem": "npm",
6
6
  "name": "@superdurable/connector-google-docs",
7
- "version": "0.1.0"
7
+ "version": "0.1.1"
8
8
  },
9
9
  "factories": [
10
10
  {
11
11
  "name": "newGetDocumentTextStep",
12
12
  "kind": "query",
13
13
  "operationId": "getDocumentText",
14
+ "inputType": "GetDocumentTextInput",
15
+ "description": "Read the first tab of one document, without pending suggestions, as bounded Markdown or plain text with its title and revision ID.",
14
16
  "fields": {
15
17
  "stepType": "stepType",
16
18
  "annotations": "annotations",
@@ -48,12 +50,36 @@
48
50
  "field": "defect",
49
51
  "optional": true
50
52
  }
51
- ]
53
+ ],
54
+ "inputSchema": {
55
+ "additionalProperties": false,
56
+ "description": "GetDocumentTextInput identifies the document whose first tab is read.",
57
+ "properties": {
58
+ "documentId": {
59
+ "description": "DocumentID is the Google Docs document ID, the part of a docs.google.com/document/d/{documentId}/edit link after /d/.",
60
+ "type": "string"
61
+ },
62
+ "format": {
63
+ "description": "Format is markdown or plainText; blank renders Markdown.",
64
+ "enum": [
65
+ "markdown",
66
+ "plainText"
67
+ ],
68
+ "type": "string"
69
+ }
70
+ },
71
+ "required": [
72
+ "documentId"
73
+ ],
74
+ "type": "object"
75
+ }
52
76
  },
53
77
  {
54
78
  "name": "newCreateDocumentStep",
55
79
  "kind": "mutation",
56
80
  "operationId": "createDocument",
81
+ "inputType": "CreateDocumentInput",
82
+ "description": "Create one Google Doc from a title and optional plain-text or Markdown text in an optional Drive folder. Google offers no idempotency key, so the single-dispatch fence requires sync durability to persist its heartbeat across attempts; a private Drive app property supports read-back before every resend, and an unconfirmed create is resent only up to the send cap.",
57
83
  "fields": {
58
84
  "stepType": "stepType",
59
85
  "annotations": "annotations",
@@ -86,12 +112,44 @@
86
112
  "field": "defect",
87
113
  "optional": true
88
114
  }
89
- ]
115
+ ],
116
+ "inputSchema": {
117
+ "additionalProperties": false,
118
+ "description": "CreateDocumentInput describes one new Google Doc.",
119
+ "properties": {
120
+ "initialText": {
121
+ "description": "InitialText is the document's first content; blank creates an empty document.",
122
+ "type": "string"
123
+ },
124
+ "initialTextFormat": {
125
+ "description": "InitialTextFormat is plainText or markdown; blank imports plain text. Markdown asks Drive's Markdown import to create headings, lists, and tables.",
126
+ "enum": [
127
+ "markdown",
128
+ "plainText"
129
+ ],
130
+ "type": "string"
131
+ },
132
+ "parentFolderId": {
133
+ "description": "ParentFolderID is the destination Drive folder ID; blank creates the document in the My Drive root of the connection's account.",
134
+ "type": "string"
135
+ },
136
+ "title": {
137
+ "description": "Title is the new document's title; it must not be blank or contain line breaks.",
138
+ "type": "string"
139
+ }
140
+ },
141
+ "required": [
142
+ "title"
143
+ ],
144
+ "type": "object"
145
+ }
90
146
  },
91
147
  {
92
148
  "name": "newReplaceDocumentTextStep",
93
149
  "kind": "mutation",
94
150
  "operationId": "replaceDocumentText",
151
+ "inputType": "ReplaceDocumentTextInput",
152
+ "description": "Replace the whole body text or named text placeholders in the first tab of one document in one batch that Google applies only at the required revision, so a repeated dispatch cannot apply it twice.",
95
153
  "fields": {
96
154
  "stepType": "stepType",
97
155
  "annotations": "annotations",
@@ -134,12 +192,74 @@
134
192
  "field": "defect",
135
193
  "optional": true
136
194
  }
137
- ]
195
+ ],
196
+ "inputSchema": {
197
+ "$defs": {
198
+ "PlaceholderReplacement": {
199
+ "additionalProperties": false,
200
+ "description": "PlaceholderReplacement is one named text placeholder and its replacement.",
201
+ "properties": {
202
+ "placeholder": {
203
+ "description": "Placeholder is the exact, case-sensitive text to replace, such as {{effectiveDate}}. It is 1 to 256 bytes on one line.",
204
+ "type": "string"
205
+ },
206
+ "text": {
207
+ "description": "Text replaces every occurrence; blank removes the placeholder. It cannot contain any requested placeholder.",
208
+ "type": "string"
209
+ }
210
+ },
211
+ "required": [
212
+ "placeholder",
213
+ "text"
214
+ ],
215
+ "type": "object"
216
+ }
217
+ },
218
+ "additionalProperties": false,
219
+ "description": "ReplaceDocumentTextInput describes one guarded replacement in a document's first tab.",
220
+ "properties": {
221
+ "documentId": {
222
+ "description": "DocumentID is the Google Docs document ID.",
223
+ "type": "string"
224
+ },
225
+ "placeholders": {
226
+ "description": "Placeholders lists the placeholders to replace for placeholders, such as {{effectiveDate}}; every one must occur in the body at RequiredRevisionID.",
227
+ "items": {
228
+ "$ref": "#/$defs/PlaceholderReplacement"
229
+ },
230
+ "type": "array"
231
+ },
232
+ "requiredRevisionId": {
233
+ "description": "RequiredRevisionID is the revision the replacement applies to, normally the RevisionID of a getDocumentText Step. Google applies the change only while the document is still at this revision.",
234
+ "type": "string"
235
+ },
236
+ "target": {
237
+ "description": "Target is wholeBody or placeholders.",
238
+ "enum": [
239
+ "placeholders",
240
+ "wholeBody"
241
+ ],
242
+ "type": "string"
243
+ },
244
+ "text": {
245
+ "description": "Text is the new body text for wholeBody; blank empties the body. It is inserted literally, so Markdown markup is not interpreted.",
246
+ "type": "string"
247
+ }
248
+ },
249
+ "required": [
250
+ "documentId",
251
+ "requiredRevisionId",
252
+ "target"
253
+ ],
254
+ "type": "object"
255
+ }
138
256
  },
139
257
  {
140
258
  "name": "newAppendTextStep",
141
259
  "kind": "mutation",
142
260
  "operationId": "appendText",
261
+ "inputType": "AppendTextInput",
262
+ "description": "Append plain-text paragraphs to the end of the first tab's body of one document in one batch that Google applies only at the required revision, so a repeated dispatch cannot append twice.",
143
263
  "fields": {
144
264
  "stepType": "stepType",
145
265
  "annotations": "annotations",
@@ -177,7 +297,31 @@
177
297
  "field": "defect",
178
298
  "optional": true
179
299
  }
180
- ]
300
+ ],
301
+ "inputSchema": {
302
+ "additionalProperties": false,
303
+ "description": "AppendTextInput describes text appended to the end of a document's first tab.",
304
+ "properties": {
305
+ "documentId": {
306
+ "description": "DocumentID is the Google Docs document ID.",
307
+ "type": "string"
308
+ },
309
+ "requiredRevisionId": {
310
+ "description": "RequiredRevisionID is the revision the text is appended to, normally the RevisionID of a getDocumentText or replaceDocumentText Step. Google appends only while the document is still at this revision.",
311
+ "type": "string"
312
+ },
313
+ "text": {
314
+ "description": "Text is appended as one or more plain normal-style paragraphs, one per line, after the body's last paragraph. It must not be blank.",
315
+ "type": "string"
316
+ }
317
+ },
318
+ "required": [
319
+ "documentId",
320
+ "requiredRevisionId",
321
+ "text"
322
+ ],
323
+ "type": "object"
324
+ }
181
325
  }
182
326
  ]
183
327
  }
@@ -30,71 +30,85 @@ var ConfigSchema = z.object({
30
30
  "maxResponseBytes": z.number().int().optional(),
31
31
  "maxTextBytes": z.number().int().optional()
32
32
  });
33
+ var CredentialMaterialError = class extends TypeError {
34
+ constructor(message) {
35
+ super(message);
36
+ this.name = "CredentialMaterialError";
37
+ }
38
+ };
39
+ var sdkCredentialDecodingFailureMessages = /* @__PURE__ */ new Set([
40
+ "project credential decoding failed",
41
+ "shared project credential decoding failed",
42
+ "project credential decoding failed: this connector version does not support shared credentials"
43
+ ]);
44
+ function isCredentialMaterialError(error) {
45
+ return error instanceof CredentialMaterialError || error instanceof TypeError && sdkCredentialDecodingFailureMessages.has(error.message);
46
+ }
33
47
  function decodeCredentials(value) {
34
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("credential fields are invalid");
48
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new CredentialMaterialError("credential fields are invalid");
35
49
  const fields = value;
36
50
  const allowed = /* @__PURE__ */ new Set(["auth_method", "access_token", "delegated_user", "oauth_client_id", "oauth_client_secret", "refresh_token", "service_account_key"]);
37
- if (Object.keys(fields).some((key) => !allowed.has(key))) throw new TypeError("stored credential does not match the connector credential fields");
38
- if (fields["access_token"] != null && !(typeof fields["access_token"] === "string")) throw new TypeError("credential access_token has an invalid type");
39
- if (fields["delegated_user"] != null && !(typeof fields["delegated_user"] === "string")) throw new TypeError("credential delegated_user has an invalid type");
40
- if (fields["oauth_client_id"] != null && !(typeof fields["oauth_client_id"] === "string")) throw new TypeError("credential oauth_client_id has an invalid type");
41
- if (fields["oauth_client_secret"] != null && !(typeof fields["oauth_client_secret"] === "string")) throw new TypeError("credential oauth_client_secret has an invalid type");
42
- if (fields["refresh_token"] != null && !(typeof fields["refresh_token"] === "string")) throw new TypeError("credential refresh_token has an invalid type");
43
- if (fields["service_account_key"] != null && !(typeof fields["service_account_key"] === "string")) throw new TypeError("credential service_account_key has an invalid type");
51
+ if (Object.keys(fields).some((key) => !allowed.has(key))) throw new CredentialMaterialError("stored credential does not match the connector credential fields");
52
+ if (fields["access_token"] != null && !(typeof fields["access_token"] === "string")) throw new CredentialMaterialError("credential access_token has an invalid type");
53
+ if (fields["delegated_user"] != null && !(typeof fields["delegated_user"] === "string")) throw new CredentialMaterialError("credential delegated_user has an invalid type");
54
+ if (fields["oauth_client_id"] != null && !(typeof fields["oauth_client_id"] === "string")) throw new CredentialMaterialError("credential oauth_client_id has an invalid type");
55
+ if (fields["oauth_client_secret"] != null && !(typeof fields["oauth_client_secret"] === "string")) throw new CredentialMaterialError("credential oauth_client_secret has an invalid type");
56
+ if (fields["refresh_token"] != null && !(typeof fields["refresh_token"] === "string")) throw new CredentialMaterialError("credential refresh_token has an invalid type");
57
+ if (fields["service_account_key"] != null && !(typeof fields["service_account_key"] === "string")) throw new CredentialMaterialError("credential service_account_key has an invalid type");
44
58
  const selectedMethod = fields["auth_method"] ?? "";
45
- if (typeof selectedMethod !== "string") throw new TypeError("credential auth_method is invalid");
59
+ if (typeof selectedMethod !== "string") throw new CredentialMaterialError("credential auth_method is invalid");
46
60
  const method = selectedMethod || "google-oauth";
47
61
  const credentials = { authMethodId: method };
48
62
  if (method === "google-oauth") {
49
- if (!fields["oauth_client_id"]) throw new TypeError("credential oauth_client_id is required");
63
+ if (!fields["oauth_client_id"]) throw new CredentialMaterialError("credential oauth_client_id is required");
50
64
  if (fields["oauth_client_id"]) credentials.oauthClientId = fields["oauth_client_id"];
51
- if (!fields["oauth_client_secret"]) throw new TypeError("credential oauth_client_secret is required");
65
+ if (!fields["oauth_client_secret"]) throw new CredentialMaterialError("credential oauth_client_secret is required");
52
66
  if (fields["oauth_client_secret"]) credentials.oauthClientSecret = new SecretString(fields["oauth_client_secret"]);
53
- if (!fields["access_token"]) throw new TypeError("credential access_token is required");
67
+ if (!fields["access_token"]) throw new CredentialMaterialError("credential access_token is required");
54
68
  if (fields["access_token"]) credentials.accessToken = new SecretString(fields["access_token"]);
55
- if (!fields["refresh_token"]) throw new TypeError("credential refresh_token is required");
69
+ if (!fields["refresh_token"]) throw new CredentialMaterialError("credential refresh_token is required");
56
70
  if (fields["refresh_token"]) credentials.refreshToken = new SecretString(fields["refresh_token"]);
57
71
  } else if (method === "workspace-domain-delegation") {
58
- if (!fields["service_account_key"]) throw new TypeError("credential service_account_key is required");
72
+ if (!fields["service_account_key"]) throw new CredentialMaterialError("credential service_account_key is required");
59
73
  if (fields["service_account_key"]) credentials.serviceAccountKey = new SecretString(fields["service_account_key"]);
60
- if (!fields["delegated_user"]) throw new TypeError("credential delegated_user is required");
74
+ if (!fields["delegated_user"]) throw new CredentialMaterialError("credential delegated_user is required");
61
75
  if (fields["delegated_user"]) credentials.delegatedUser = fields["delegated_user"];
62
76
  credentials.accessToken = new SecretString(fields["access_token"] ?? "");
63
77
  } else {
64
- throw new TypeError("credential auth_method is invalid");
78
+ throw new CredentialMaterialError("credential auth_method is invalid");
65
79
  }
66
80
  return credentials;
67
81
  }
68
82
  function decodeSharedCredentials(value) {
69
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("credential fields are invalid");
83
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new CredentialMaterialError("credential fields are invalid");
70
84
  const fields = value;
71
85
  const allowed = /* @__PURE__ */ new Set(["auth_method", "access_token", "delegated_user", "oauth_client_id", "oauth_client_secret", "refresh_token", "service_account_key"]);
72
- if (Object.keys(fields).some((key) => !allowed.has(key))) throw new TypeError("stored credential does not match the connector credential fields");
73
- if (fields["access_token"] != null && !(typeof fields["access_token"] === "string")) throw new TypeError("credential access_token has an invalid type");
74
- if (fields["delegated_user"] != null && !(typeof fields["delegated_user"] === "string")) throw new TypeError("credential delegated_user has an invalid type");
75
- if (fields["oauth_client_id"] != null && !(typeof fields["oauth_client_id"] === "string")) throw new TypeError("credential oauth_client_id has an invalid type");
76
- if (fields["oauth_client_secret"] != null && !(typeof fields["oauth_client_secret"] === "string")) throw new TypeError("credential oauth_client_secret has an invalid type");
77
- if (fields["refresh_token"] != null && !(typeof fields["refresh_token"] === "string")) throw new TypeError("credential refresh_token has an invalid type");
78
- if (fields["service_account_key"] != null && !(typeof fields["service_account_key"] === "string")) throw new TypeError("credential service_account_key has an invalid type");
86
+ if (Object.keys(fields).some((key) => !allowed.has(key))) throw new CredentialMaterialError("stored credential does not match the connector credential fields");
87
+ if (fields["access_token"] != null && !(typeof fields["access_token"] === "string")) throw new CredentialMaterialError("credential access_token has an invalid type");
88
+ if (fields["delegated_user"] != null && !(typeof fields["delegated_user"] === "string")) throw new CredentialMaterialError("credential delegated_user has an invalid type");
89
+ if (fields["oauth_client_id"] != null && !(typeof fields["oauth_client_id"] === "string")) throw new CredentialMaterialError("credential oauth_client_id has an invalid type");
90
+ if (fields["oauth_client_secret"] != null && !(typeof fields["oauth_client_secret"] === "string")) throw new CredentialMaterialError("credential oauth_client_secret has an invalid type");
91
+ if (fields["refresh_token"] != null && !(typeof fields["refresh_token"] === "string")) throw new CredentialMaterialError("credential refresh_token has an invalid type");
92
+ if (fields["service_account_key"] != null && !(typeof fields["service_account_key"] === "string")) throw new CredentialMaterialError("credential service_account_key has an invalid type");
79
93
  const selectedMethod = fields["auth_method"] ?? "";
80
- if (typeof selectedMethod !== "string") throw new TypeError("credential auth_method is invalid");
94
+ if (typeof selectedMethod !== "string") throw new CredentialMaterialError("credential auth_method is invalid");
81
95
  const method = selectedMethod || "google-oauth";
82
96
  const credentials = { authMethodId: method };
83
97
  if (method === "google-oauth") {
84
- if (!fields["oauth_client_id"]) throw new TypeError("credential oauth_client_id is required");
98
+ if (!fields["oauth_client_id"]) throw new CredentialMaterialError("credential oauth_client_id is required");
85
99
  if (fields["oauth_client_id"]) credentials.oauthClientId = fields["oauth_client_id"];
86
100
  if (fields["oauth_client_secret"]) credentials.oauthClientSecret = new SecretString(fields["oauth_client_secret"]);
87
- if (!fields["access_token"]) throw new TypeError("credential access_token is required");
101
+ if (!fields["access_token"]) throw new CredentialMaterialError("credential access_token is required");
88
102
  if (fields["access_token"]) credentials.accessToken = new SecretString(fields["access_token"]);
89
103
  if (fields["refresh_token"]) credentials.refreshToken = new SecretString(fields["refresh_token"]);
90
104
  } else if (method === "workspace-domain-delegation") {
91
105
  if (fields["service_account_key"]) credentials.serviceAccountKey = new SecretString(fields["service_account_key"]);
92
- if (!fields["delegated_user"]) throw new TypeError("credential delegated_user is required");
106
+ if (!fields["delegated_user"]) throw new CredentialMaterialError("credential delegated_user is required");
93
107
  if (fields["delegated_user"]) credentials.delegatedUser = fields["delegated_user"];
94
- if (!fields["access_token"]) throw new TypeError("credential access_token is required");
108
+ if (!fields["access_token"]) throw new CredentialMaterialError("credential access_token is required");
95
109
  credentials.accessToken = new SecretString(fields["access_token"] ?? "");
96
110
  } else {
97
- throw new TypeError("credential auth_method is invalid");
111
+ throw new CredentialMaterialError("credential auth_method is invalid");
98
112
  }
99
113
  return credentials;
100
114
  }
@@ -210,10 +224,12 @@ var CreateDocumentDefinition = {
210
224
  { id: "created", description: "Google created the document or returned the one an earlier attempt of the same Step execution created." },
211
225
  { id: "providerRejected", description: "Google conclusively rejected the creation or the duplicate lookup, such as a missing parent folder; no document was created.", optional: true },
212
226
  { id: "invalidResponse", description: "Google returned an invalid or oversized duplicate-lookup response before the creation was sent.", optional: true },
213
- { id: "uncertain", description: "A creation may have been sent but its outcome cannot be confirmed, so the document may exist; the connector sends nothing after selecting this branch.", optional: true },
227
+ { id: "uncertain", description: "A creation may have been sent and cannot be confirmed: the duplicate lookup found nothing when the send cap was reached, including after Google accepted it with an unusable response that carries no file ID, Google refused a resend, or the connection needed reauthorization after a possible send; the document may exist, and the connector sends nothing after selecting this branch.", optional: true },
214
228
  { id: "defect", description: "Local input, connection configuration, or connector definition is invalid.", optional: true }
215
229
  ],
216
- stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 6e4, maximumAttempts: 5, totalDurationMs: 3e5 } }
230
+ stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 6e4, maximumAttempts: 5, totalDurationMs: 3e5 } },
231
+ repeatOnUnknown: "limited",
232
+ maxSends: 3
217
233
  };
218
234
  var CreateDocumentMetadata = { kind: "mutation", idempotency: "required", authorization: "required" };
219
235
  var ReplaceDocumentTextBranch = {
@@ -243,7 +259,8 @@ var ReplaceDocumentTextDefinition = {
243
259
  { id: "invalidResponse", description: "Google returned an invalid or oversized document response.", optional: true },
244
260
  { id: "defect", description: "Local input, connection configuration, or connector definition is invalid.", optional: true }
245
261
  ],
246
- stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "async" }
262
+ stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "async" },
263
+ repeatOnUnknown: "safe"
247
264
  };
248
265
  var ReplaceDocumentTextMetadata = { kind: "mutation", idempotency: "required", authorization: "required" };
249
266
  var AppendTextBranch = {
@@ -270,7 +287,8 @@ var AppendTextDefinition = {
270
287
  { id: "invalidResponse", description: "Google returned an invalid or oversized document response.", optional: true },
271
288
  { id: "defect", description: "Local input, connection configuration, or connector definition is invalid.", optional: true }
272
289
  ],
273
- stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "async" }
290
+ stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "async" },
291
+ repeatOnUnknown: "safe"
274
292
  };
275
293
  var AppendTextMetadata = { kind: "mutation", idempotency: "required", authorization: "required" };
276
294
 
@@ -303,6 +321,8 @@ function newProjectCredentialProvider(project, connectionName, decode, encode, d
303
321
 
304
322
  export {
305
323
  ConfigSchema,
324
+ CredentialMaterialError,
325
+ isCredentialMaterialError,
306
326
  decodeCredentials,
307
327
  decodeSharedCredentials,
308
328
  GetDocumentTextInputSchema,
@@ -36,6 +36,12 @@ interface Credentials {
36
36
  /** Secret service-account JSON key downloaded from https://console.cloud.google.com/iam-admin/serviceaccounts after selecting the account > Keys > Add key > Create new key > JSON; blank means delegated token minting cannot start. */
37
37
  serviceAccountKey?: SecretString;
38
38
  }
39
+ /** Stored credential material that fails the connector credential checks, so no retry can succeed. */
40
+ declare class CredentialMaterialError extends TypeError {
41
+ constructor(message: string);
42
+ }
43
+ /** Report malformed stored credential material, also behind the SDK provider's decoding TypeError. */
44
+ declare function isCredentialMaterialError(error: unknown): boolean;
39
45
  /** Decode private credential fields for the selected authorization method. */
40
46
  declare function decodeCredentials(value: unknown): Credentials;
41
47
  /** Decode shared credential fields for the selected authorization method. */
@@ -298,4 +304,4 @@ declare function newConnection(client: Operations, reference: ConnectionRef): Co
298
304
  /** Bind scripted operations to a named connection. */
299
305
  declare function newConnectionWithOperations(operations: Operations, reference: ConnectionRef): Connection;
300
306
 
301
- export { type AppendTextInput as A, Connection as C, type GetDocumentTextInput as G, type Operations as O, type PlaceholderReplacement as P, type ReplaceDocumentTextInput as R, type AppendTextOutput as a, type CreateDocumentInput as b, type CreateDocumentOutput as c, type GetDocumentTextOutput as d, type ReplaceDocumentTextOutput as e, type Config as f, type CredentialSource as g, type Credentials as h, AppendTextInputSchema as i, AppendTextOutputSchema as j, ConfigSchema as k, CreateDocumentInputSchema as l, CreateDocumentOutputSchema as m, type CreatedDocument as n, CreatedDocumentSchema as o, GetDocumentTextInputSchema as p, GetDocumentTextOutputSchema as q, type PlaceholderReplacementResult as r, PlaceholderReplacementResultSchema as s, PlaceholderReplacementSchema as t, ReplaceDocumentTextInputSchema as u, ReplaceDocumentTextOutputSchema as v, decodeCredentials as w, decodeSharedCredentials as x, newConnection as y, newConnectionWithOperations as z };
307
+ export { type AppendTextInput as A, newConnection as B, Connection as C, newConnectionWithOperations as D, type GetDocumentTextInput as G, type Operations as O, type PlaceholderReplacement as P, type ReplaceDocumentTextInput as R, type AppendTextOutput as a, type CreateDocumentInput as b, type CreateDocumentOutput as c, type GetDocumentTextOutput as d, type ReplaceDocumentTextOutput as e, type Config as f, type CredentialSource as g, type Credentials as h, AppendTextInputSchema as i, AppendTextOutputSchema as j, ConfigSchema as k, CreateDocumentInputSchema as l, CreateDocumentOutputSchema as m, type CreatedDocument as n, CreatedDocumentSchema as o, CredentialMaterialError as p, GetDocumentTextInputSchema as q, GetDocumentTextOutputSchema as r, type PlaceholderReplacementResult as s, PlaceholderReplacementResultSchema as t, PlaceholderReplacementSchema as u, ReplaceDocumentTextInputSchema as v, ReplaceDocumentTextOutputSchema as w, decodeCredentials as x, decodeSharedCredentials as y, isCredentialMaterialError as z };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as AppendTextInput, a as AppendTextOutput, C as Connection, b as CreateDocumentInput, c as CreateDocumentOutput, G as GetDocumentTextInput, d as GetDocumentTextOutput, R as ReplaceDocumentTextInput, e as ReplaceDocumentTextOutput, f as Config, g as CredentialSource, h as Credentials, O as Operations } from './connection-BTFf7Ob2.js';
2
- export { i as AppendTextInputSchema, j as AppendTextOutputSchema, k as ConfigSchema, l as CreateDocumentInputSchema, m as CreateDocumentOutputSchema, n as CreatedDocument, o as CreatedDocumentSchema, p as GetDocumentTextInputSchema, q as GetDocumentTextOutputSchema, P as PlaceholderReplacement, r as PlaceholderReplacementResult, s as PlaceholderReplacementResultSchema, t as PlaceholderReplacementSchema, u as ReplaceDocumentTextInputSchema, v as ReplaceDocumentTextOutputSchema, w as decodeCredentials, x as decodeSharedCredentials, y as newConnection, z as newConnectionWithOperations } from './connection-BTFf7Ob2.js';
1
+ import { A as AppendTextInput, a as AppendTextOutput, C as Connection, b as CreateDocumentInput, c as CreateDocumentOutput, G as GetDocumentTextInput, d as GetDocumentTextOutput, R as ReplaceDocumentTextInput, e as ReplaceDocumentTextOutput, f as Config, g as CredentialSource, h as Credentials, O as Operations } from './connection-CAHPwRm8.js';
2
+ export { i as AppendTextInputSchema, j as AppendTextOutputSchema, k as ConfigSchema, l as CreateDocumentInputSchema, m as CreateDocumentOutputSchema, n as CreatedDocument, o as CreatedDocumentSchema, p as CredentialMaterialError, q as GetDocumentTextInputSchema, r as GetDocumentTextOutputSchema, P as PlaceholderReplacement, s as PlaceholderReplacementResult, t as PlaceholderReplacementResultSchema, u as PlaceholderReplacementSchema, v as ReplaceDocumentTextInputSchema, w as ReplaceDocumentTextOutputSchema, x as decodeCredentials, y as decodeSharedCredentials, z as isCredentialMaterialError, B as newConnection, D as newConnectionWithOperations } from './connection-CAHPwRm8.js';
3
3
  import * as _superdurable_connectors_sdk from '@superdurable/connectors-sdk';
4
4
  import { MutationDefinition, QueryDefinition, MutationStepConfig, Mutation, MutationResult, QueryStepConfig, Query, QueryResult, MutationStep, QueryStep, Call, QueryAttempt, MutationAttempt, CredentialRefreshDriver, ReceiptDraft } from '@superdurable/connectors-sdk';
5
5
  import { StepTarget } from '@superdurable/dex';
@@ -54,7 +54,7 @@ declare const CreateDocumentBranchCreated: "created";
54
54
  declare const CreateDocumentBranchProviderRejected: "providerRejected";
55
55
  /** Google returned an invalid or oversized duplicate-lookup response before the creation was sent. */
56
56
  declare const CreateDocumentBranchInvalidResponse: "invalidResponse";
57
- /** A creation may have been sent but its outcome cannot be confirmed, so the document may exist; the connector sends nothing after selecting this branch. */
57
+ /** A creation may have been sent and cannot be confirmed: the duplicate lookup found nothing when the send cap was reached, including after Google accepted it with an unusable response that carries no file ID, Google refused a resend, or the connection needed reauthorization after a possible send; the document may exist, and the connector sends nothing after selecting this branch. */
58
58
  declare const CreateDocumentBranchUncertain: "uncertain";
59
59
  /** Local input, connection configuration, or connector definition is invalid. */
60
60
  declare const CreateDocumentBranchDefect: "defect";
@@ -165,7 +165,7 @@ interface CreateDocumentStepConfig<StepInput, OperationInput = CreateDocumentInp
165
165
  providerRejected?: StepTarget<MutationResult<OperationOutput>>;
166
166
  /** Google returned an invalid or oversized duplicate-lookup response before the creation was sent. */
167
167
  invalidResponse?: StepTarget<MutationResult<OperationOutput>>;
168
- /** A creation may have been sent but its outcome cannot be confirmed, so the document may exist; the connector sends nothing after selecting this branch. */
168
+ /** A creation may have been sent and cannot be confirmed: the duplicate lookup found nothing when the send cap was reached, including after Google accepted it with an unusable response that carries no file ID, Google refused a resend, or the connection needed reauthorization after a possible send; the document may exist, and the connector sends nothing after selecting this branch. */
169
169
  uncertain?: StepTarget<MutationResult<OperationOutput>>;
170
170
  /** Local input, connection configuration, or connector definition is invalid. */
171
171
  defect?: StepTarget<MutationResult<OperationOutput>>;
@@ -194,6 +194,8 @@ interface ReplaceDocumentTextStepConfig<StepInput, OperationInput = ReplaceDocum
194
194
  invalidResponse?: StepTarget<MutationResult<OperationOutput>>;
195
195
  /** Local input, connection configuration, or connector definition is invalid. */
196
196
  defect?: StepTarget<MutationResult<OperationOutput>>;
197
+ /** Accepted for compatibility; ignored because the operation is safe to repeat. */
198
+ maxSends?: number;
197
199
  }
198
200
  /** Build the replaceDocumentText Step from a named connection. */
199
201
  declare function newReplaceDocumentTextStep<StepInput, OperationInput = ReplaceDocumentTextInput, OperationOutput = ReplaceDocumentTextOutput>(configuration: ReplaceDocumentTextStepConfig<StepInput, OperationInput, OperationOutput>): MutationStep<StepInput, OperationInput, OperationOutput>;
@@ -217,6 +219,8 @@ interface AppendTextStepConfig<StepInput, OperationInput = AppendTextInput, Oper
217
219
  invalidResponse?: StepTarget<MutationResult<OperationOutput>>;
218
220
  /** Local input, connection configuration, or connector definition is invalid. */
219
221
  defect?: StepTarget<MutationResult<OperationOutput>>;
222
+ /** Accepted for compatibility; ignored because the operation is safe to repeat. */
223
+ maxSends?: number;
220
224
  }
221
225
  /** Build the appendText Step from a named connection. */
222
226
  declare function newAppendTextStep<StepInput, OperationInput = AppendTextInput, OperationOutput = AppendTextOutput>(configuration: AppendTextStepConfig<StepInput, OperationInput, OperationOutput>): MutationStep<StepInput, OperationInput, OperationOutput>;
@@ -235,7 +239,7 @@ declare class ReplaceDocumentTextOperation implements Mutation<ReplaceDocumentTe
235
239
  private readonly client;
236
240
  /** Bind a validated Docs client. */
237
241
  constructor(client: DocsClient);
238
- /** Return the immutable operation definition. */ definition(): _superdurable_connectors_sdk.QueryDefinition;
242
+ /** Return the immutable operation definition. */ definition(): _superdurable_connectors_sdk.MutationDefinition;
239
243
  /** Use the stable Dex Call ID; the revision guards the write. */ idempotencyKey(callId: string): string;
240
244
  /** Validate and run one revision-guarded replacement. */
241
245
  invoke(call: Call, input: ReplaceDocumentTextInput): Promise<MutationAttempt<ReplaceDocumentTextOutput>>;
@@ -245,7 +249,7 @@ declare class AppendTextOperation implements Mutation<AppendTextInput, AppendTex
245
249
  private readonly client;
246
250
  /** Bind a validated Docs client. */
247
251
  constructor(client: DocsClient);
248
- /** Return the immutable operation definition. */ definition(): _superdurable_connectors_sdk.QueryDefinition;
252
+ /** Return the immutable operation definition. */ definition(): _superdurable_connectors_sdk.MutationDefinition;
249
253
  /** Use the stable Dex Call ID; the revision guards the write. */ idempotencyKey(callId: string): string;
250
254
  /** Validate and run one revision-guarded append. */
251
255
  invoke(call: Call, input: AppendTextInput): Promise<MutationAttempt<AppendTextOutput>>;
@@ -255,7 +259,7 @@ declare class CreateDocumentOperation implements Mutation<CreateDocumentInput, C
255
259
  private readonly client;
256
260
  /** Bind a validated Docs client. */
257
261
  constructor(client: DocsClient);
258
- /** Return the immutable operation definition. */ definition(): _superdurable_connectors_sdk.QueryDefinition;
262
+ /** Return the immutable operation definition. */ definition(): _superdurable_connectors_sdk.MutationDefinition;
259
263
  /** Use the stable Dex Call ID as Drive's private app-property value. */ idempotencyKey(callId: string): string;
260
264
  /** Validate, reconcile, and create no more than once per Dex Call. */
261
265
  invoke(call: Call, input: CreateDocumentInput): Promise<MutationAttempt<CreateDocumentOutput>>;
@@ -263,6 +267,10 @@ declare class CreateDocumentOperation implements Mutation<CreateDocumentInput, C
263
267
 
264
268
  /** Replaceable bounded transport for an in-process provider stand-in. */
265
269
  type DocsTransport = (request: ProviderRequest) => Promise<ProviderResponse>;
270
+ /** A bounded Google response, marking a non-2xx body dropped for its size. */
271
+ interface DocsResponse extends ProviderResponse {
272
+ /** The non-2xx body exceeded the error limit, so it could hide a created object. */ isErrorBodyTooLarge?: boolean;
273
+ }
266
274
  /** Constructor-injected transport, clock, and manifest refresh driver. */
267
275
  interface DocsClientOptions {
268
276
  /** Provider transport; defaults to the SDK's policy-checked HTTP sender. */
@@ -287,11 +295,16 @@ declare class DocsClient {
287
295
  /** Bind the replaceDocumentText operation. */ replaceDocumentText(): ReplaceDocumentTextOperation;
288
296
  /** Bind the appendText operation. */ appendText(): AppendTextOperation;
289
297
  /** Resolve the current access token, including a host-coordinated refresh. */
298
+ /**
299
+ * Resolve one call's credentials. Throws ReauthorizationRequiredError when the connection must be
300
+ * reconnected or holds an unusable credential, and a TypeError for an outage a later attempt may clear.
301
+ */
290
302
  resolveCredentials(call: Call): Promise<Credentials>;
291
303
  /** Ask the host to refresh after one rejected access token. */
304
+ /** Throws ReauthorizationRequiredError for a terminal or unusable refresh, and a TypeError for a transient one. */
292
305
  refreshCredentialsAfterRejection(call: Call): Promise<Credentials>;
293
306
  /** Send one request; an idempotent request may refresh once after a 401. */
294
- request(call: Call, credentials: Credentials, method: string, url: string, body?: Uint8Array, contentType?: string, singleDispatch?: boolean, signal?: AbortSignal): Promise<ProviderResponse>;
307
+ request(call: Call, credentials: Credentials, method: string, url: string, body?: Uint8Array, contentType?: string, singleDispatch?: boolean, signal?: AbortSignal): Promise<DocsResponse>;
295
308
  /** Return a receipt with only provider-safe identifiers. */
296
309
  receipt(call: Call, response: ProviderResponse | undefined, objectID?: string): ReceiptDraft;
297
310
  /** Return the observation clock for Retry-After dates. */ now(): Date;
package/dist/index.js CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  CreateDocumentMetadata,
25
25
  CreateDocumentOutputSchema,
26
26
  CreatedDocumentSchema,
27
+ CredentialMaterialError,
27
28
  GetDocumentTextBranch,
28
29
  GetDocumentTextBranchDefect,
29
30
  GetDocumentTextBranchInvalidResponse,
@@ -52,10 +53,11 @@ import {
52
53
  ReplaceDocumentTextOutputSchema,
53
54
  decodeCredentials,
54
55
  decodeSharedCredentials,
56
+ isCredentialMaterialError,
55
57
  newConnection,
56
58
  newConnectionWithOperations,
57
59
  newProjectCredentialProvider
58
- } from "./chunk-FHV3PBWN.js";
60
+ } from "./chunk-2AMHZOKT.js";
59
61
 
60
62
  // src/generated/steps.ts
61
63
  import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
@@ -83,7 +85,7 @@ function newCreateDocumentStep(configuration) {
83
85
  ] });
84
86
  }
85
87
  function newReplaceDocumentTextStep(configuration) {
86
- const { connection, connectionName, replaced, placeholderNotFound, revisionChanged, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
88
+ const { connection, connectionName, replaced, placeholderNotFound, revisionChanged, notFound, providerRejected, invalidResponse, defect, maxSends, ...stepConfiguration } = configuration;
87
89
  if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
88
90
  return newMutationStep({ ...stepConfiguration, operation: connection.operations.replaceDocumentText(), connection: connection.reference, branches: [
89
91
  goToBranch("replaced", replaced),
@@ -96,7 +98,7 @@ function newReplaceDocumentTextStep(configuration) {
96
98
  ] });
97
99
  }
98
100
  function newAppendTextStep(configuration) {
99
- const { connection, connectionName, appended, revisionChanged, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
101
+ const { connection, connectionName, appended, revisionChanged, notFound, providerRejected, invalidResponse, defect, maxSends, ...stepConfiguration } = configuration;
100
102
  if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
101
103
  return newMutationStep({ ...stepConfiguration, operation: connection.operations.appendText(), connection: connection.reference, branches: [
102
104
  goToBranch("appended", appended),
@@ -112,9 +114,10 @@ function newAppendTextStep(configuration) {
112
114
  import { ConnectionRefSchema } from "@superdurable/connectors-sdk";
113
115
 
114
116
  // src/client.ts
115
- import { resolveCredential, resolveCredentialAfterRejection } from "@superdurable/connectors-sdk";
116
- import { BodyTooLargeError, isHeaderSafeCredential, parseRetryAfter, readErrorTokens, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
117
+ import { ReauthorizationRequiredError as ReauthorizationRequiredError2, resolveCredential, resolveCredentialAfterRejection } from "@superdurable/connectors-sdk";
118
+ import { BodyTooLargeError, ProviderStalledError, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, readErrorTokens, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
117
119
  import { ManifestCredentialRefreshDriver } from "@superdurable/connectors-sdk/oauthtoken";
120
+ import { ConnectionNotSelectedError, CredentialBrokerRejectedError, ObjectNotFoundError } from "@superdurable/connectors-sdk/projectconfig";
118
121
 
119
122
  // src/generated/refresh.ts
120
123
  var Authorization = {
@@ -165,7 +168,8 @@ var Authorization = {
165
168
  "invalid_grant",
166
169
  "invalid_client",
167
170
  "unauthorized_client"
168
- ]
171
+ ],
172
+ "tokenExchangeTimeout": "25s"
169
173
  },
170
174
  "scopes": [
171
175
  "https://www.googleapis.com/auth/documents",
@@ -251,7 +255,7 @@ var CredentialFields = {
251
255
  };
252
256
 
253
257
  // src/operations.ts
254
- import { newMutationBranch, newMutationRetry, newMutationUncertain, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
258
+ import { ReauthorizationRequiredError, definitionMaxSends, newMutationBranch, newMutationRetry, newMutationUncertain, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
255
259
  import { newFence } from "@superdurable/connectors-sdk/singledispatch";
256
260
  import { randomBytes } from "crypto";
257
261
 
@@ -567,7 +571,8 @@ var GetDocumentTextOperation = class {
567
571
  let credentials;
568
572
  try {
569
573
  credentials = await this.client.resolveCredentials(call);
570
- } catch {
574
+ } catch (error) {
575
+ if (!(error instanceof ReauthorizationRequiredError)) return newQueryRetry(docsFailure("getDocumentText", "AUTHENTICATION", "connection credentials are temporarily unavailable"));
571
576
  return newQueryBranch("defect", zeroRead, {}, docsFailure("getDocumentText", "AUTHENTICATION", "connection credentials are unavailable"));
572
577
  }
573
578
  const url = documentURL(this.client, input.documentId, "PREVIEW_WITHOUT_SUGGESTIONS", readFields);
@@ -692,8 +697,10 @@ async function runGuardedWrite(client, call, documentId, requiredRevisionId, ope
692
697
  let credentials;
693
698
  try {
694
699
  credentials = await client.resolveCredentials(call);
695
- } catch {
696
- return newMutationBranch("defect", zero, {}, docsFailure(operation, "AUTHENTICATION", "connection credentials are unavailable"));
700
+ } catch (error) {
701
+ const failure = docsFailure(operation, "AUTHENTICATION", "connection credentials are unavailable");
702
+ if (!(error instanceof ReauthorizationRequiredError) || call.context.attempt > 1) return newMutationRetry(failure);
703
+ return newMutationBranch("defect", zero, {}, failure);
697
704
  }
698
705
  const read = async () => {
699
706
  const result = await sendRead(client, call, credentials, operation, documentURL(client, documentId, "SUGGESTIONS_INLINE", writeFields), "invalidResponse", "notFound", zero);
@@ -753,8 +760,10 @@ async function runGuardedWrite(client, call, documentId, requiredRevisionId, ope
753
760
  return changed(reread);
754
761
  }
755
762
  if (response.status === 404) return newMutationBranch("notFound", zero, receipt, docsFailure(operation, "NOT_FOUND", "document was not found or is not visible to the connection"));
756
- return newMutationBranch("providerRejected", zero, receipt, docsFailure(operation, statusFailureKind(response.status, tokens), "provider rejected the update"));
763
+ if (definiteRefusalStatuses.has(response.status)) return newMutationBranch("providerRejected", zero, receipt, docsFailure(operation, statusFailureKind(response.status, tokens), "provider rejected the update"));
764
+ return newMutationRetry(docsFailure(operation, statusFailureKind(response.status, tokens), "provider update outcome is unknown; the next attempt reads the revision"));
757
765
  }
766
+ var definiteRefusalStatuses = /* @__PURE__ */ new Set([400, 401, 403, 404, 411, 413, 414, 415, 422]);
758
767
  function buildReplacement(document, bodyText, input) {
759
768
  if (input.target === "wholeBody") {
760
769
  const start = document.bodyStartIndex;
@@ -848,30 +857,58 @@ async function createDocument(client, call, input) {
848
857
  }
849
858
  const key = call.idempotencyKey ?? "";
850
859
  if (!key || Buffer.byteLength(key) > 100) return newMutationBranch("defect", zeroCreate, {}, docsFailure("createDocument", "LOCAL_DEFECT", "idempotency key is missing or too long"));
860
+ const operationMaxSends = definitionMaxSends(CreateDocumentDefinition);
851
861
  let fence;
852
862
  try {
853
- fence = newFence(call, 3e4);
863
+ fence = newFence(call, 3e4, { maxSends: operationMaxSends });
854
864
  } catch {
855
865
  return newMutationBranch("defect", zeroCreate, {}, docsFailure("createDocument", "LOCAL_DEFECT", "single-dispatch fence could not be constructed"));
856
866
  }
857
867
  const decision = fence.decide();
858
- if (decision.kind === "failClosed") return newMutationBranch("defect", zeroCreate, {}, docsFailure("createDocument", "LOCAL_DEFECT", "single-dispatch checkpoint is invalid"));
868
+ const priorSendUpperBound = decision.priorSendUpperBound ?? 0;
869
+ const canResendUnknownOutcome = priorSendUpperBound + 1 < (operationMaxSends >= 2 ? call.maxSendsOverride ?? operationMaxSends : 1);
870
+ const hasPossibleEarlierSend = priorSendUpperBound > 0;
859
871
  let credentials;
860
872
  try {
861
873
  credentials = await client.resolveCredentials(call);
862
- } catch {
863
- if (decision.kind === "sendAllowed") {
874
+ } catch (error) {
875
+ const isRetryable2 = !(error instanceof ReauthorizationRequiredError);
876
+ const isFirstAttemptSend = decision.kind === "sendAllowed" && !hasPossibleEarlierSend;
877
+ if (isRetryable2 && isFirstAttemptSend) {
864
878
  try {
865
879
  await fence.recordNotSent();
866
880
  } catch {
867
881
  return newMutationRetry(docsFailure("createDocument", "AVAILABILITY", "Dex could not record a pre-send retry"));
868
882
  }
869
- return newMutationRetry(docsFailure("createDocument", "AUTHENTICATION", "connection credentials are unavailable"));
883
+ return newMutationRetry(docsFailure("createDocument", "AUTHENTICATION", "connection credentials are temporarily unavailable"));
870
884
  }
871
- return newMutationRetry(docsFailure("createDocument", "AUTHENTICATION", "connection credentials are unavailable for duplicate lookup"));
885
+ if (isRetryable2 || decision.kind === "failClosed") return newMutationRetry(docsFailure("createDocument", "AUTHENTICATION", "connection credentials are unavailable for duplicate lookup"));
886
+ const failure = docsFailure("createDocument", "AUTHENTICATION", "connection credentials are unavailable; reconnect the connection");
887
+ if (!isFirstAttemptSend) return newMutationUncertain(zeroCreate, { ...failure, message: `${failure.message} after an earlier unconfirmed send` }, {});
888
+ return newMutationBranch("defect", zeroCreate, {}, failure);
872
889
  }
873
890
  const lookupQuery = { q: `appProperties has { key='dexIdempotencyKey' and value='${key.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}' }`, fields: `incompleteSearch,files(${fileFields})`, pageSize: "10", spaces: "drive" };
874
- if (decision.kind === "readBackRequired" && decision.marker?.providerId && isDriveID(decision.marker.providerId)) {
891
+ const lookupURL = filesListURL(client, lookupQuery);
892
+ const lookup = async () => {
893
+ const result = await sendRead(client, call, credentials, "createDocument", lookupURL, "invalidResponse", "providerRejected", zeroCreate, createLookupSignal(call));
894
+ if ("attempt" in result) return result;
895
+ try {
896
+ return { ...decodeEarlierDocument(result.response.body), response: result.response };
897
+ } catch {
898
+ return { attempt: newQueryBranch("invalidResponse", zeroCreate, client.receipt(call, result.response), docsFailure("createDocument", "PROTOCOL", "provider returned an invalid duplicate-lookup response")), isInvalidLookup: true };
899
+ }
900
+ };
901
+ if (decision.kind === "failClosed") {
902
+ const found = await lookup();
903
+ if ("response" in found && !found.incomplete && found.document) return newMutationBranch("created", { document: found.document, isFromEarlierAttempt: true }, client.receipt(call, void 0, found.document.documentId));
904
+ return newMutationRetry(docsFailure("createDocument", "AVAILABILITY", "dispatch checkpoint is unreadable; no document was created in this attempt"));
905
+ }
906
+ const hasSavedDocumentId = !!decision.marker?.providerId;
907
+ const isAtSendCap = decision.kind === "readBackRequired";
908
+ const isFirstSend = decision.kind === "sendAllowed" && !hasPossibleEarlierSend && !hasSavedDocumentId;
909
+ const hasPossibleCreate = hasPossibleEarlierSend || hasSavedDocumentId;
910
+ const retryLookupOrSelectUncertain = (kind, message, receiptDraft) => isAtSendCap ? newMutationUncertain(zeroCreate, docsFailure("createDocument", kind, message), receiptDraft) : newMutationRetry(docsFailure("createDocument", kind, `${message}; the next attempt looks it up again`));
911
+ if (hasSavedDocumentId && decision.marker?.providerId && isDriveID(decision.marker.providerId)) {
875
912
  const url = `${client.driveBaseURL}/files/${goPathEscape(decision.marker.providerId)}?${goQuery({ fields: fileFields, supportsAllDrives: "true" })}`;
876
913
  const found = await sendRead(client, call, credentials, "createDocument", url, "invalidResponse", "providerRejected", zeroCreate, createLookupSignal(call));
877
914
  if ("response" in found) {
@@ -882,32 +919,36 @@ async function createDocument(client, call, input) {
882
919
  }
883
920
  } else if (found.attempt.kind === "retry") return newMutationRetry(found.attempt.failure, found.attempt.retryAfterMs);
884
921
  }
885
- const lookupURL = filesListURL(client, lookupQuery);
886
- const lookup = async () => {
887
- const result = await sendRead(client, call, credentials, "createDocument", lookupURL, "invalidResponse", "providerRejected", zeroCreate, createLookupSignal(call));
888
- if ("attempt" in result) return result;
889
- try {
890
- return { ...decodeEarlierDocument(result.response.body), response: result.response };
891
- } catch {
892
- return { attempt: newQueryBranch("invalidResponse", zeroCreate, client.receipt(call, result.response), docsFailure("createDocument", "PROTOCOL", "provider returned an invalid duplicate-lookup response")) };
893
- }
894
- };
895
922
  const firstLookup = await lookup();
896
923
  if ("attempt" in firstLookup) {
897
924
  const attempt = firstLookup.attempt;
898
- if (decision.kind === "sendAllowed" && attempt.kind === "retry") return retryBeforeSend(fence, "AVAILABILITY", "duplicate lookup is unavailable");
899
- if (decision.kind !== "sendAllowed" && attempt.kind === "branch") return newMutationUncertain(zeroCreate, docsFailure("createDocument", attempt.failure?.kind ?? "PROTOCOL", "a prior create cannot be confirmed because duplicate lookup was rejected"), attempt.receipt);
925
+ if (firstLookup.isInvalidLookup) {
926
+ if (hasPossibleCreate) return retryLookupOrSelectUncertain("PROTOCOL", "a prior create cannot be confirmed because duplicate lookup was invalid", attempt.kind === "branch" ? attempt.receipt : {});
927
+ return attempt;
928
+ }
929
+ if (isFirstSend && attempt.kind === "retry") return retryBeforeSend(fence, "AVAILABILITY", "duplicate lookup is unavailable");
930
+ if (hasPossibleCreate && attempt.kind === "branch") return retryLookupOrSelectUncertain(attempt.failure?.kind ?? "PROTOCOL", "a prior create cannot be confirmed because duplicate lookup was rejected", attempt.receipt);
900
931
  return attempt;
901
932
  }
902
933
  const lookupReceipt = client.receipt(call, firstLookup.response);
903
934
  if (firstLookup.document) return newMutationBranch("created", { document: firstLookup.document, isFromEarlierAttempt: true }, client.receipt(call, firstLookup.response, firstLookup.document.documentId));
904
- if (firstLookup.incomplete) return decision.kind === "sendAllowed" ? retryBeforeSend(fence, "AVAILABILITY", "provider did not complete the duplicate lookup") : newMutationRetry(docsFailure("createDocument", "AVAILABILITY", "provider did not complete the duplicate lookup"));
905
- if (decision.kind !== "sendAllowed") return newMutationUncertain(zeroCreate, docsFailure("createDocument", "TRANSPORT", "an earlier attempt of this Step may have created the document, and the duplicate lookup does not show it yet"), lookupReceipt);
935
+ if (firstLookup.incomplete) return isFirstSend ? retryBeforeSend(fence, "AVAILABILITY", "provider did not complete the duplicate lookup") : newMutationRetry(docsFailure("createDocument", "AVAILABILITY", "provider did not complete the duplicate lookup"));
936
+ if (isAtSendCap || hasSavedDocumentId) return retryLookupOrSelectUncertain("TRANSPORT", "an earlier attempt of this Step may have created the document, the duplicate lookup does not show it, and no further send is allowed", lookupReceipt);
937
+ const rejectOrSelectUncertain = async (branch, kind, message, receiptDraft) => {
938
+ if (hasPossibleEarlierSend) return newMutationUncertain(zeroCreate, docsFailure("createDocument", kind, `${message} after an earlier unconfirmed send`), receiptDraft);
939
+ if (branch === "providerRejected") {
940
+ try {
941
+ await fence.recordCanResend();
942
+ } catch {
943
+ }
944
+ }
945
+ return newMutationBranch(branch, zeroCreate, receiptDraft, docsFailure("createDocument", kind, message));
946
+ };
906
947
  let request;
907
948
  try {
908
949
  request = buildCreateRequest(client, input, format, key);
909
950
  } catch {
910
- return newMutationBranch("defect", zeroCreate, {}, docsFailure("createDocument", "LOCAL_DEFECT", "create request could not be encoded"));
951
+ return rejectOrSelectUncertain("defect", "LOCAL_DEFECT", "create request could not be encoded", {});
911
952
  }
912
953
  let response;
913
954
  let sendError;
@@ -928,7 +969,30 @@ async function createDocument(client, call, input) {
928
969
  }
929
970
  return newMutationBranch("created", { document: found.document }, { ...receipt, providerObjectId: found.document.documentId });
930
971
  }
931
- return newMutationUncertain(zeroCreate, docsFailure("createDocument", kind, message), receipt);
972
+ if (canResendUnknownOutcome) return newMutationRetry(docsFailure("createDocument", kind, message));
973
+ return newMutationUncertain(zeroCreate, docsFailure("createDocument", kind, `${message}; the send cap is reached`), receipt);
974
+ };
975
+ const reconcileAccepted = async (kind, body) => {
976
+ const documentId = createdDocumentID(body);
977
+ let isAcceptanceSaved = true;
978
+ try {
979
+ await fence.recordProviderId(documentId || acceptedCreateWithoutDocumentID);
980
+ } catch {
981
+ isAcceptanceSaved = false;
982
+ }
983
+ const found = await lookup();
984
+ if ("response" in found && !found.incomplete && found.document) {
985
+ try {
986
+ await fence.recordProviderId(found.document.documentId);
987
+ } catch {
988
+ }
989
+ return newMutationBranch("created", { document: found.document }, { ...receipt, providerObjectId: found.document.documentId });
990
+ }
991
+ if (isAcceptanceSaved && documentId)
992
+ return newMutationRetry(docsFailure("createDocument", kind, "provider accepted the create with an unusable response; the next attempt reads the document back"));
993
+ if (isAcceptanceSaved)
994
+ return newMutationRetry(docsFailure("createDocument", kind, "provider accepted the create with an unusable response, and the duplicate lookup does not show it yet; the next attempt looks it up again"));
995
+ return newMutationUncertain(zeroCreate, docsFailure("createDocument", kind, "provider accepted the create with an unusable response, the duplicate lookup does not show it, and its acceptance checkpoint failed, so it is not sent again"), receipt);
932
996
  };
933
997
  if (response && response.status >= 200 && response.status < 300) {
934
998
  try {
@@ -939,10 +1003,15 @@ async function createDocument(client, call, input) {
939
1003
  }
940
1004
  return newMutationBranch("created", { document }, { ...receipt, providerObjectId: document.documentId });
941
1005
  } catch {
942
- return confirmAfterSend("PROTOCOL", "provider returned an unusable accepted create response");
1006
+ return reconcileAccepted("PROTOCOL", response.body);
943
1007
  }
944
1008
  }
945
- if (response && (isRateLimit(response.status, tokens) || response.status === 503)) {
1009
+ if (sendError instanceof DocsRequestError && sendError.status >= 200 && sendError.status < 300)
1010
+ return reconcileAccepted(sendError.tooLarge ? "RESPONSE_TOO_LARGE" : "TRANSPORT", void 0);
1011
+ if (response && createdDocumentID(response.body)) return reconcileAccepted("PROTOCOL", response.body);
1012
+ const isBrokenThrottleBody = sendError instanceof DocsRequestError && (sendError.status === 429 || sendError.status === 503);
1013
+ if (response && (isRateLimit(response.status, tokens) || response.status === 503) || isBrokenThrottleBody) {
1014
+ const throttled = response ?? { status: sendError.status, headers: sendError.headers, body: new Uint8Array() };
946
1015
  const found = await lookup();
947
1016
  if ("response" in found && !found.incomplete && found.document) {
948
1017
  try {
@@ -956,13 +1025,18 @@ async function createDocument(client, call, input) {
956
1025
  } catch {
957
1026
  return newMutationRetry(docsFailure("createDocument", "AVAILABILITY", "Dex could not record safe resend after provider rejection"));
958
1027
  }
959
- return newMutationRetry(docsFailure("createDocument", statusFailureKind(response.status, tokens), "provider temporarily rejected the create"), retryAfterMs(response, client.now()));
1028
+ return newMutationRetry(docsFailure("createDocument", statusFailureKind(throttled.status, tokens), "provider temporarily rejected the create"), retryAfterMs(throttled, client.now()));
960
1029
  }
961
- if (response?.status === 401) {
1030
+ if (response?.status === 401 && !response.isErrorBodyTooLarge) {
962
1031
  try {
963
1032
  await client.refreshCredentialsAfterRejection(call);
964
- } catch {
965
- return newMutationBranch("providerRejected", zeroCreate, receipt, docsFailure("createDocument", "AUTHENTICATION", "provider rejected the create credential"));
1033
+ } catch (error) {
1034
+ if (error instanceof ReauthorizationRequiredError) return rejectOrSelectUncertain("providerRejected", "AUTHENTICATION", "provider rejected the create credential", receipt);
1035
+ try {
1036
+ await fence.recordCanResend();
1037
+ } catch {
1038
+ }
1039
+ return newMutationRetry(docsFailure("createDocument", "AUTHENTICATION", "provider rejected the create credential, and its refresh is temporarily unavailable"));
966
1040
  }
967
1041
  try {
968
1042
  await fence.recordCanResend();
@@ -972,9 +1046,6 @@ async function createDocument(client, call, input) {
972
1046
  return newMutationRetry(docsFailure("createDocument", "AUTHENTICATION", "provider rejected the create credential; refreshed for the next attempt"));
973
1047
  }
974
1048
  if (sendError) {
975
- if (sendError instanceof DocsRequestError && sendError.tooLarge && sendError.status >= 200 && sendError.status < 300) {
976
- return confirmAfterSend("PROTOCOL", "provider returned an unusable accepted create response");
977
- }
978
1049
  if (sendError instanceof DocsRequestError && sendError.beforeSend) {
979
1050
  try {
980
1051
  await fence.recordCanResend();
@@ -985,8 +1056,19 @@ async function createDocument(client, call, input) {
985
1056
  }
986
1057
  return confirmAfterSend("TRANSPORT", "provider create outcome is unknown");
987
1058
  }
988
- if (response && (response.status >= 500 || response.status === 408 || response.status === 409)) return confirmAfterSend("AVAILABILITY", "provider create outcome is unknown");
989
- return newMutationBranch("providerRejected", zeroCreate, receipt, docsFailure("createDocument", statusFailureKind(response?.status ?? 0, tokens), "provider rejected the create"));
1059
+ const status = response?.status ?? 0;
1060
+ if (definiteRefusalStatuses.has(status) && !response?.isErrorBodyTooLarge) return rejectOrSelectUncertain("providerRejected", statusFailureKind(status, tokens), "provider rejected the create", receipt);
1061
+ return confirmAfterSend(statusFailureKind(status, tokens), `provider create outcome is unknown after HTTP ${status}`);
1062
+ }
1063
+ var acceptedCreateWithoutDocumentID = "dex:acceptedWithoutDocumentId";
1064
+ function createdDocumentID(body) {
1065
+ if (!body) return "";
1066
+ try {
1067
+ const id = parseObject(body).id;
1068
+ return typeof id === "string" && isDriveID(id) ? id : "";
1069
+ } catch {
1070
+ return "";
1071
+ }
990
1072
  }
991
1073
  async function retryBeforeSend(fence, kind, reason) {
992
1074
  try {
@@ -1128,19 +1210,32 @@ var DocsClient2 = class {
1128
1210
  return new AppendTextOperation(this);
1129
1211
  }
1130
1212
  /** Resolve the current access token, including a host-coordinated refresh. */
1213
+ /**
1214
+ * Resolve one call's credentials. Throws ReauthorizationRequiredError when the connection must be
1215
+ * reconnected or holds an unusable credential, and a TypeError for an outage a later attempt may clear.
1216
+ */
1131
1217
  async resolveCredentials(call) {
1218
+ let credentials;
1132
1219
  try {
1133
- const credentials = await resolveCredential(this.#credentials, call, this.#refreshDriver, call.context.cancellationSignal);
1134
- if (!isHeaderSafeCredential(credentials.accessToken?.reveal() ?? "") || !["google-oauth", "workspace-domain-delegation", ""].includes(credentials.authMethodId ?? "")) throw new TypeError("invalid credential");
1135
- return credentials;
1136
- } catch {
1220
+ credentials = await resolveCredential(this.#credentials, call, this.#refreshDriver, call.context.cancellationSignal);
1221
+ } catch (error) {
1222
+ if (isTerminalCredentialError(error)) throw new ReauthorizationRequiredError2();
1137
1223
  throw new TypeError("connection credentials are unavailable");
1138
1224
  }
1225
+ if (!isHeaderSafeCredential(credentials.accessToken?.reveal() ?? "") || !["google-oauth", "workspace-domain-delegation", ""].includes(credentials.authMethodId ?? "")) throw new ReauthorizationRequiredError2();
1226
+ return credentials;
1139
1227
  }
1140
1228
  /** Ask the host to refresh after one rejected access token. */
1229
+ /** Throws ReauthorizationRequiredError for a terminal or unusable refresh, and a TypeError for a transient one. */
1141
1230
  async refreshCredentialsAfterRejection(call) {
1142
- const credentials = await resolveCredentialAfterRejection(this.#credentials, call, this.#refreshDriver, call.context.cancellationSignal);
1143
- if (!isHeaderSafeCredential(credentials.accessToken?.reveal() ?? "")) throw new TypeError("connection credentials are unavailable");
1231
+ let credentials;
1232
+ try {
1233
+ credentials = await resolveCredentialAfterRejection(this.#credentials, call, this.#refreshDriver, call.context.cancellationSignal);
1234
+ } catch (error) {
1235
+ if (isTerminalCredentialError(error)) throw new ReauthorizationRequiredError2();
1236
+ throw new TypeError("connection credentials are temporarily unavailable");
1237
+ }
1238
+ if (!isHeaderSafeCredential(credentials.accessToken?.reveal() ?? "")) throw new ReauthorizationRequiredError2();
1144
1239
  return credentials;
1145
1240
  }
1146
1241
  /** Send one request; an idempotent request may refresh once after a 401. */
@@ -1165,18 +1260,19 @@ var DocsClient2 = class {
1165
1260
  response = await this.#transport(request);
1166
1261
  } catch (error) {
1167
1262
  if (error instanceof BodyTooLargeError) {
1168
- if (error.status && (error.status < 200 || error.status >= 300)) response = { status: error.status, headers: error.headers ?? {}, body: new Uint8Array() };
1263
+ if (error.status && (error.status < 200 || error.status >= 300)) response = { status: error.status, headers: error.headers ?? {}, body: new Uint8Array(), isErrorBodyTooLarge: true };
1169
1264
  else throw new DocsRequestError(false, true, error.status ?? 0, error.headers ?? {});
1170
1265
  } else {
1171
1266
  const isBeforeSend = !!error && typeof error === "object" && ("beforeSend" in error && error.beforeSend === true || "isProvablyNotSent" in error && error.isProvablyNotSent === true);
1172
- throw new DocsRequestError(isBeforeSend);
1267
+ const isHeaderFailure = error instanceof ProviderTransportError || error instanceof ProviderStalledError;
1268
+ throw new DocsRequestError(isBeforeSend, false, isHeaderFailure ? error.status ?? 0 : 0, isHeaderFailure ? error.headers ?? {} : {});
1173
1269
  }
1174
1270
  }
1175
1271
  if (response.status >= 200 && response.status < 300 && response.body.byteLength > this.maxResponseBytes) {
1176
1272
  throw new DocsRequestError(false, true, response.status, response.headers);
1177
1273
  }
1178
1274
  if ((response.status < 200 || response.status >= 300) && response.body.byteLength > Math.max(this.maxResponseBytes, 65536)) {
1179
- response = { ...response, body: new Uint8Array() };
1275
+ response = { ...response, body: new Uint8Array(), isErrorBodyTooLarge: true };
1180
1276
  }
1181
1277
  if (response.status !== 401 || attempt !== 0 || singleDispatch || !("resolveAfterRejection" in this.#credentials)) return response;
1182
1278
  try {
@@ -1197,6 +1293,9 @@ var DocsClient2 = class {
1197
1293
  return this.#now();
1198
1294
  }
1199
1295
  };
1296
+ function isTerminalCredentialError(error) {
1297
+ return error instanceof ReauthorizationRequiredError2 || error instanceof ObjectNotFoundError || error instanceof ConnectionNotSelectedError || error instanceof CredentialBrokerRejectedError || isCredentialMaterialError(error);
1298
+ }
1200
1299
  function header(headers, name) {
1201
1300
  const value = headers[name] ?? headers[name.toLowerCase()] ?? headers[name.toUpperCase()];
1202
1301
  return Array.isArray(value) ? value[0] ?? "" : value ?? "";
@@ -1290,6 +1389,7 @@ export {
1290
1389
  CreateDocumentOperation,
1291
1390
  CreateDocumentOutputSchema,
1292
1391
  CreatedDocumentSchema,
1392
+ CredentialMaterialError,
1293
1393
  DocsClient2 as DocsClient,
1294
1394
  GetDocumentTextBranch,
1295
1395
  GetDocumentTextBranchDefect,
@@ -1321,6 +1421,7 @@ export {
1321
1421
  ReplaceDocumentTextOutputSchema,
1322
1422
  decodeCredentials,
1323
1423
  decodeSharedCredentials,
1424
+ isCredentialMaterialError,
1324
1425
  newAppendTextStep,
1325
1426
  newConnection,
1326
1427
  newConnectionWithOperations,
package/dist/mock.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { MockQuery, MockMutation, Case } from '@superdurable/connectors-sdk/connectormock';
2
2
  import { Failure } from '@superdurable/connectors-sdk';
3
- import { O as Operations, C as Connection, G as GetDocumentTextInput, d as GetDocumentTextOutput, b as CreateDocumentInput, c as CreateDocumentOutput, R as ReplaceDocumentTextInput, e as ReplaceDocumentTextOutput, A as AppendTextInput, a as AppendTextOutput, n as CreatedDocument, P as PlaceholderReplacement, r as PlaceholderReplacementResult } from './connection-BTFf7Ob2.js';
3
+ import { O as Operations, C as Connection, G as GetDocumentTextInput, d as GetDocumentTextOutput, b as CreateDocumentInput, c as CreateDocumentOutput, R as ReplaceDocumentTextInput, e as ReplaceDocumentTextOutput, A as AppendTextInput, a as AppendTextOutput, n as CreatedDocument, P as PlaceholderReplacement, s as PlaceholderReplacementResult } from './connection-CAHPwRm8.js';
4
4
  import 'zod';
5
5
 
6
6
  /** Go zero value for GetDocumentTextInput in scripted cases. */
package/dist/mock.js CHANGED
@@ -17,7 +17,7 @@ import {
17
17
  ReplaceDocumentTextInputSchema,
18
18
  ReplaceDocumentTextOutputSchema,
19
19
  newConnectionWithOperations
20
- } from "./chunk-FHV3PBWN.js";
20
+ } from "./chunk-2AMHZOKT.js";
21
21
 
22
22
  // src/generated/mock.ts
23
23
  import { branchCase, retryCase, uncertainCase, newMutation, newQuery } from "@superdurable/connectors-sdk/connectormock";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@superdurable/connector-google-docs",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "license": "MIT",
5
5
  "description": "Dex Google Docs connector for TypeScript",
6
6
  "repository": {
@@ -22,7 +22,8 @@
22
22
  "./mock": {
23
23
  "types": "./dist/mock.d.ts",
24
24
  "import": "./dist/mock.js"
25
- }
25
+ },
26
+ "./dex-connector.json": "./dex-connector.json"
26
27
  },
27
28
  "files": [
28
29
  "dist",
@@ -41,7 +42,7 @@
41
42
  "check": "npm run typecheck && npm run lint && npm test"
42
43
  },
43
44
  "dependencies": {
44
- "@superdurable/connectors-sdk": "0.7.0",
45
+ "@superdurable/connectors-sdk": "0.12.0",
45
46
  "@superdurable/dex": ">=1.28.0",
46
47
  "zod": "^4.1.0"
47
48
  },