@superdurable/connector-box 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +6 -2
- package/dex-connector.json +129 -0
- package/dist/chunk-C3MMWLYU.js +315 -0
- package/dist/connection-DfqaRnkX.d.ts +124 -0
- package/dist/index.d.ts +179 -0
- package/dist/index.js +552 -0
- package/dist/mock.d.ts +58 -0
- package/dist/mock.js +48 -0
- package/package.json +62 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ConfigSchema,
|
|
3
|
+
Connection,
|
|
4
|
+
ConnectorID,
|
|
5
|
+
CredentialMaterialError,
|
|
6
|
+
DownloadFileBranch,
|
|
7
|
+
DownloadFileBranchDefect,
|
|
8
|
+
DownloadFileBranchDownloaded,
|
|
9
|
+
DownloadFileBranchInvalidResponse,
|
|
10
|
+
DownloadFileBranchNotFound,
|
|
11
|
+
DownloadFileBranchProviderRejected,
|
|
12
|
+
DownloadFileBranchTooLarge,
|
|
13
|
+
DownloadFileDefinition,
|
|
14
|
+
DownloadFileInputSchema,
|
|
15
|
+
DownloadFileMetadata,
|
|
16
|
+
DownloadedFileSchema,
|
|
17
|
+
ProviderID,
|
|
18
|
+
UploadFileBranch,
|
|
19
|
+
UploadFileBranchDefect,
|
|
20
|
+
UploadFileBranchInvalidResponse,
|
|
21
|
+
UploadFileBranchNotFound,
|
|
22
|
+
UploadFileBranchProviderRejected,
|
|
23
|
+
UploadFileBranchUploaded,
|
|
24
|
+
UploadFileDefinition,
|
|
25
|
+
UploadFileInputSchema,
|
|
26
|
+
UploadFileMetadata,
|
|
27
|
+
UploadedFileSchema,
|
|
28
|
+
decodeCredentials,
|
|
29
|
+
decodeSharedCredentials,
|
|
30
|
+
emptyDownloadedFile,
|
|
31
|
+
emptyUploadedFile,
|
|
32
|
+
isCredentialMaterialError,
|
|
33
|
+
newConnection,
|
|
34
|
+
newConnectionWithOperations,
|
|
35
|
+
newProjectCredentialProvider
|
|
36
|
+
} from "./chunk-C3MMWLYU.js";
|
|
37
|
+
|
|
38
|
+
// src/client.ts
|
|
39
|
+
import { randomBytes } from "crypto";
|
|
40
|
+
import {
|
|
41
|
+
ReauthorizationRequiredError,
|
|
42
|
+
SecretString,
|
|
43
|
+
resolveCredential
|
|
44
|
+
} from "@superdurable/connectors-sdk";
|
|
45
|
+
import { ManifestCredentialRefreshDriver } from "@superdurable/connectors-sdk/oauthtoken";
|
|
46
|
+
import { ConnectionNotSelectedError, CredentialBrokerRejectedError, ObjectNotFoundError } from "@superdurable/connectors-sdk/projectconfig";
|
|
47
|
+
import {
|
|
48
|
+
BodyTooLargeError,
|
|
49
|
+
ProviderTransportError,
|
|
50
|
+
isHeaderSafeCredential,
|
|
51
|
+
parseRetryAfter,
|
|
52
|
+
sendProviderRequest,
|
|
53
|
+
validateBaseURL
|
|
54
|
+
} from "@superdurable/connectors-sdk/providerhttp";
|
|
55
|
+
|
|
56
|
+
// src/generated/refresh.ts
|
|
57
|
+
var Authorization = {
|
|
58
|
+
"fields": [
|
|
59
|
+
{
|
|
60
|
+
"name": "oauth_client_id",
|
|
61
|
+
"required": true,
|
|
62
|
+
"type": "string"
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
"name": "oauth_client_secret",
|
|
66
|
+
"required": true,
|
|
67
|
+
"type": "secretString"
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
"name": "access_token",
|
|
71
|
+
"required": true,
|
|
72
|
+
"type": "secretString"
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
"name": "refresh_token",
|
|
76
|
+
"required": true,
|
|
77
|
+
"type": "secretString"
|
|
78
|
+
}
|
|
79
|
+
],
|
|
80
|
+
"oauth2": {
|
|
81
|
+
"clientIDCredential": "oauth_client_id",
|
|
82
|
+
"clientSecretCredential": "oauth_client_secret",
|
|
83
|
+
"credentialMappings": [
|
|
84
|
+
{
|
|
85
|
+
"credential": "access_token",
|
|
86
|
+
"source": "access_token"
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
"credential": "refresh_token",
|
|
90
|
+
"source": "refresh_token"
|
|
91
|
+
}
|
|
92
|
+
],
|
|
93
|
+
"refresh": {
|
|
94
|
+
"missingExpiry": "reject",
|
|
95
|
+
"requiredScopes": [
|
|
96
|
+
"root_readwrite"
|
|
97
|
+
],
|
|
98
|
+
"scopeSeparators": "whitespaceAndComma",
|
|
99
|
+
"storedMissingExpiry": "refresh",
|
|
100
|
+
"terminalErrorCodes": [
|
|
101
|
+
"invalid_grant",
|
|
102
|
+
"invalid_client",
|
|
103
|
+
"unauthorized_client"
|
|
104
|
+
],
|
|
105
|
+
"tokenExchangeTimeout": "15s"
|
|
106
|
+
},
|
|
107
|
+
"scopes": [
|
|
108
|
+
"root_readwrite"
|
|
109
|
+
],
|
|
110
|
+
"tokenEndpoint": "https://api.box.com/oauth2/token",
|
|
111
|
+
"tokenEndpointAuthMethod": "client_secret_post"
|
|
112
|
+
},
|
|
113
|
+
"refreshable": true,
|
|
114
|
+
"type": "oauth2"
|
|
115
|
+
};
|
|
116
|
+
var CredentialFields = {
|
|
117
|
+
"access_token": "accessToken",
|
|
118
|
+
"oauth_client_id": "oauthClientId",
|
|
119
|
+
"oauth_client_secret": "oauthClientSecret",
|
|
120
|
+
"refresh_token": "refreshToken"
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
// src/operations.ts
|
|
124
|
+
import { createHash } from "crypto";
|
|
125
|
+
import {
|
|
126
|
+
newMutationBranch,
|
|
127
|
+
newMutationRetry,
|
|
128
|
+
newQueryBranch,
|
|
129
|
+
newQueryRetry
|
|
130
|
+
} from "@superdurable/connectors-sdk";
|
|
131
|
+
function failure(operation, kind, message) {
|
|
132
|
+
return { kind, provider: "box", operation, message };
|
|
133
|
+
}
|
|
134
|
+
function downloadBranch(branch, kind, message) {
|
|
135
|
+
return newQueryBranch(branch, emptyDownloadedFile, {}, failure("downloadFile", kind, message));
|
|
136
|
+
}
|
|
137
|
+
function downloadRetry(kind, message, delay = 0) {
|
|
138
|
+
return newQueryRetry(failure("downloadFile", kind, message), delay);
|
|
139
|
+
}
|
|
140
|
+
function uploadBranch(branch, kind, message) {
|
|
141
|
+
return newMutationBranch(branch, emptyUploadedFile, {}, failure("uploadFile", kind, message));
|
|
142
|
+
}
|
|
143
|
+
function uploadRetry(kind, message, delay = 0) {
|
|
144
|
+
return newMutationRetry(failure("uploadFile", kind, message), delay);
|
|
145
|
+
}
|
|
146
|
+
function validFileID(value) {
|
|
147
|
+
return /^[0-9]{1,40}$/.test(value);
|
|
148
|
+
}
|
|
149
|
+
function decodeMetadata(body, fileID) {
|
|
150
|
+
const value = JSON.parse(Buffer.from(body).toString("utf8"));
|
|
151
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Box file metadata is not an object");
|
|
152
|
+
const record = value;
|
|
153
|
+
const { id, type, name, sha1, size } = record;
|
|
154
|
+
if (id !== fileID || type !== "file" || typeof name !== "string" || !name || typeof sha1 !== "string" || !/^[0-9a-fA-F]{40}$/.test(sha1) || typeof size !== "number" || !Number.isSafeInteger(size) || size < 0)
|
|
155
|
+
throw new TypeError("Box file metadata is incomplete");
|
|
156
|
+
return { fileID, kind: type, name, sha1, size };
|
|
157
|
+
}
|
|
158
|
+
function matches(metadata, fileID, digest, size) {
|
|
159
|
+
return metadata.fileID === fileID && metadata.kind === "file" && !!metadata.name && metadata.sha1.toUpperCase() === digest && metadata.size === size;
|
|
160
|
+
}
|
|
161
|
+
function uploaded(metadata) {
|
|
162
|
+
return newMutationBranch("uploaded", { fileId: metadata.fileID, name: metadata.name, sha1: metadata.sha1.toUpperCase() });
|
|
163
|
+
}
|
|
164
|
+
var DownloadFileOperation = class {
|
|
165
|
+
/** Bind the provider client. */
|
|
166
|
+
constructor(client) {
|
|
167
|
+
this.client = client;
|
|
168
|
+
if (!client) throw new TypeError("Box client is required");
|
|
169
|
+
}
|
|
170
|
+
client;
|
|
171
|
+
/** Return stable manifest metadata. */
|
|
172
|
+
definition() {
|
|
173
|
+
return DownloadFileDefinition;
|
|
174
|
+
}
|
|
175
|
+
/** Download bytes, classify provider responses, and encode bounded content. */
|
|
176
|
+
async invoke(call, input) {
|
|
177
|
+
input = DownloadFileInputSchema.parse(input);
|
|
178
|
+
if (!validFileID(input.fileId)) return downloadBranch("defect", "VALIDATION", "Box file ID must contain only decimal digits");
|
|
179
|
+
const exchange = await this.client.download(call, input.fileId);
|
|
180
|
+
if (exchange.error === "credential") return downloadBranch("defect", "AUTHENTICATION", "Box credentials are unavailable or invalid");
|
|
181
|
+
if (exchange.error === "refresh") return downloadRetry("AVAILABILITY", "Box credentials could not be refreshed");
|
|
182
|
+
if (exchange.error === "request") return downloadRetry("TRANSPORT", "Box download request failed");
|
|
183
|
+
if (exchange.status === 429) return downloadRetry("RATE_LIMIT", "Box rate limited the download", exchange.retryAfterMs);
|
|
184
|
+
if (exchange.status === 408 || exchange.status >= 500) return downloadRetry("AVAILABILITY", "Box download is temporarily unavailable", exchange.retryAfterMs);
|
|
185
|
+
if (exchange.status === 202) return downloadRetry("AVAILABILITY", "Box file is not ready for download", exchange.retryAfterMs);
|
|
186
|
+
if (exchange.error === "invalidRedirect") return downloadBranch("invalidResponse", "PROTOCOL", "Box returned an unsafe download redirect");
|
|
187
|
+
if (exchange.status !== 200 && exchange.error === "tooLarge")
|
|
188
|
+
return downloadBranch("invalidResponse", "RESPONSE_TOO_LARGE", "Box error response exceeds the configured limit");
|
|
189
|
+
if (exchange.status === 404) return downloadBranch("notFound", "NOT_FOUND", "Box did not find the file");
|
|
190
|
+
if (exchange.status !== 200) return downloadBranch("providerRejected", "PROVIDER_REJECTION", `Box rejected HTTP ${exchange.status}`);
|
|
191
|
+
if (exchange.error === "tooLarge") return downloadBranch("tooLarge", "RESPONSE_TOO_LARGE", "Box file exceeds the configured download limit");
|
|
192
|
+
if (exchange.error) return downloadRetry("TRANSPORT", "Box download response was interrupted");
|
|
193
|
+
return newQueryBranch("downloaded", { fileId: input.fileId, contentBase64: Buffer.from(exchange.body).toString("base64"), contentBytes: exchange.body.length });
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
var UploadFileOperation = class {
|
|
197
|
+
/** Bind the provider client. */
|
|
198
|
+
constructor(client) {
|
|
199
|
+
this.client = client;
|
|
200
|
+
if (!client) throw new TypeError("Box client is required");
|
|
201
|
+
}
|
|
202
|
+
client;
|
|
203
|
+
/** Return stable manifest metadata. */
|
|
204
|
+
definition() {
|
|
205
|
+
return UploadFileDefinition;
|
|
206
|
+
}
|
|
207
|
+
/** Record stable call identity; Box receives no request key. */
|
|
208
|
+
idempotencyKey(callID, _input) {
|
|
209
|
+
void _input;
|
|
210
|
+
return callID;
|
|
211
|
+
}
|
|
212
|
+
/** Compare current content, replace once, and read back ambiguous outcomes. */
|
|
213
|
+
async invoke(call, input) {
|
|
214
|
+
input = UploadFileInputSchema.parse(input);
|
|
215
|
+
if (!validFileID(input.fileId)) return uploadBranch("defect", "VALIDATION", "Box file ID must contain only decimal digits");
|
|
216
|
+
if (Math.ceil(input.contentBase64.length / 4) * 3 > this.client.maxUploadBytes)
|
|
217
|
+
return uploadBranch("defect", "VALIDATION", "Box upload exceeds the configured byte limit");
|
|
218
|
+
const content = Buffer.from(input.contentBase64, "base64");
|
|
219
|
+
if (content.toString("base64") !== input.contentBase64 || content.length > this.client.maxUploadBytes)
|
|
220
|
+
return uploadBranch("defect", "VALIDATION", "Box upload content must be bounded Base64");
|
|
221
|
+
const digest = createHash("sha1").update(content).digest("hex").toUpperCase();
|
|
222
|
+
const isLaterAttempt = (call.context?.attempt ?? 1) > 1;
|
|
223
|
+
const first = await this.client.getFileMetadata(call, input.fileId);
|
|
224
|
+
const initial = initialMetadata(first, input.fileId, isLaterAttempt);
|
|
225
|
+
if ("decision" in initial) return initial.decision;
|
|
226
|
+
const metadata = initial.metadata;
|
|
227
|
+
if (matches(metadata, input.fileId, digest, content.length)) return uploaded(metadata);
|
|
228
|
+
const exchange = await this.client.upload(call, input.fileId, metadata.name, content);
|
|
229
|
+
if (exchange.error === "credential" && !exchange.requestSent) return credentialFailure(isLaterAttempt);
|
|
230
|
+
if (exchange.error === "refresh") return uploadRetry("AVAILABILITY", "Box credentials could not be refreshed");
|
|
231
|
+
if (exchange.error === "request" && !exchange.requestSent)
|
|
232
|
+
return uploadRetry("TRANSPORT", "Box upload did not leave the process");
|
|
233
|
+
if (exchange.status === 429) return uploadRetry("RATE_LIMIT", "Box rate limited the upload", exchange.retryAfterMs);
|
|
234
|
+
if (exchange.status === 408 || exchange.status >= 500)
|
|
235
|
+
return uploadRetry("AVAILABILITY", "Box upload is temporarily unavailable", exchange.retryAfterMs);
|
|
236
|
+
if (isDefiniteRefusal(exchange)) return refusal(exchange.status);
|
|
237
|
+
const isAccepted = exchange.status === 200 || exchange.status === 201;
|
|
238
|
+
if (isAccepted && !exchange.error) {
|
|
239
|
+
try {
|
|
240
|
+
const wire = JSON.parse(Buffer.from(exchange.body).toString("utf8"));
|
|
241
|
+
if (wire && typeof wire === "object" && "entries" in wire && Array.isArray(wire.entries) && wire.entries.length === 1) {
|
|
242
|
+
const returned = decodeMetadata(Buffer.from(JSON.stringify(wire.entries[0])), input.fileId);
|
|
243
|
+
if (matches(returned, input.fileId, digest, content.length)) return uploaded(returned);
|
|
244
|
+
}
|
|
245
|
+
} catch {
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
const readback = await this.client.getFileMetadata(call, input.fileId);
|
|
249
|
+
if (readback.status === 200 && !readback.error) {
|
|
250
|
+
try {
|
|
251
|
+
const confirmed = decodeMetadata(readback.body, input.fileId);
|
|
252
|
+
if (matches(confirmed, input.fileId, digest, content.length)) return uploaded(confirmed);
|
|
253
|
+
} catch {
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return uploadRetry("TRANSPORT", "Box replacement could not be confirmed by read-back", readback.retryAfterMs);
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
function initialMetadata(exchange, fileID, isLaterAttempt) {
|
|
260
|
+
if (exchange.error === "credential" && exchange.status === 0) return { decision: credentialFailure(isLaterAttempt) };
|
|
261
|
+
if (exchange.error === "credential") return { decision: uploadRetry("PROTOCOL", "Box metadata echoed the access token", exchange.retryAfterMs) };
|
|
262
|
+
if (exchange.error === "refresh") return { decision: uploadRetry("AVAILABILITY", "Box credentials could not be refreshed") };
|
|
263
|
+
if (exchange.error === "request") return { decision: uploadRetry("TRANSPORT", "Box metadata request failed") };
|
|
264
|
+
if (exchange.status === 429) return { decision: uploadRetry("RATE_LIMIT", "Box rate limited metadata lookup", exchange.retryAfterMs) };
|
|
265
|
+
if (exchange.status === 408 || exchange.status >= 500)
|
|
266
|
+
return { decision: uploadRetry("AVAILABILITY", "Box metadata is temporarily unavailable", exchange.retryAfterMs) };
|
|
267
|
+
if (isDefiniteRefusal(exchange)) return { decision: refusal(exchange.status) };
|
|
268
|
+
if (exchange.status !== 200)
|
|
269
|
+
return { decision: uploadRetry("PROTOCOL", `Box answered metadata lookup with unexpected HTTP ${exchange.status}`, exchange.retryAfterMs) };
|
|
270
|
+
if (exchange.error === "tooLarge") return { decision: uploadRetry("RESPONSE_TOO_LARGE", "Box metadata exceeds the configured limit") };
|
|
271
|
+
if (exchange.error) return { decision: uploadRetry("TRANSPORT", "Box metadata response was interrupted") };
|
|
272
|
+
try {
|
|
273
|
+
return { metadata: decodeMetadata(exchange.body, fileID) };
|
|
274
|
+
} catch {
|
|
275
|
+
return { decision: uploadRetry("PROTOCOL", "Box returned invalid file metadata") };
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
function credentialFailure(isLaterAttempt) {
|
|
279
|
+
if (isLaterAttempt) return uploadRetry("AUTHENTICATION", "Box credentials are unavailable or invalid after a possible earlier upload");
|
|
280
|
+
return uploadBranch("defect", "AUTHENTICATION", "Box credentials are unavailable or invalid");
|
|
281
|
+
}
|
|
282
|
+
var definiteRefusalStatuses = /* @__PURE__ */ new Set([400, 401, 403, 404, 411, 413, 414, 415, 422]);
|
|
283
|
+
function isDefiniteRefusal(exchange) {
|
|
284
|
+
if (exchange.error || !definiteRefusalStatuses.has(exchange.status)) return false;
|
|
285
|
+
let wire;
|
|
286
|
+
try {
|
|
287
|
+
wire = JSON.parse(Buffer.from(exchange.body).toString("utf8"));
|
|
288
|
+
} catch {
|
|
289
|
+
return true;
|
|
290
|
+
}
|
|
291
|
+
if (!wire || typeof wire !== "object" || Array.isArray(wire)) return true;
|
|
292
|
+
const fields = wire;
|
|
293
|
+
return fields.type !== "file" && (fields.entries === void 0 || fields.entries === null);
|
|
294
|
+
}
|
|
295
|
+
function refusal(status) {
|
|
296
|
+
if (status === 404) return uploadBranch("notFound", "NOT_FOUND", "Box did not find the file");
|
|
297
|
+
return uploadBranch("providerRejected", "PROVIDER_REJECTION", `Box rejected HTTP ${status}`);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// src/client.ts
|
|
301
|
+
var BoxClient = class {
|
|
302
|
+
/** Validated API endpoint. */
|
|
303
|
+
baseURL;
|
|
304
|
+
/** Validated upload endpoint. */
|
|
305
|
+
uploadBaseURL;
|
|
306
|
+
/** Timeout for one request. */
|
|
307
|
+
timeoutMs;
|
|
308
|
+
/** Error and metadata response limit. */
|
|
309
|
+
maxResponseBytes;
|
|
310
|
+
/** Download content limit. */
|
|
311
|
+
maxDownloadBytes;
|
|
312
|
+
/** Replacement content limit. */
|
|
313
|
+
maxUploadBytes;
|
|
314
|
+
credentials;
|
|
315
|
+
refreshDriver;
|
|
316
|
+
send;
|
|
317
|
+
now;
|
|
318
|
+
/** Validate configuration and inject dependencies without network access. */
|
|
319
|
+
constructor(config, credentials, options = {}) {
|
|
320
|
+
if (!config || !credentials) throw new TypeError("Box configuration and credentials are required");
|
|
321
|
+
this.baseURL = validateBaseURL(config.baseUrl || "https://api.box.com");
|
|
322
|
+
this.uploadBaseURL = validateBaseURL(config.uploadBaseUrl || "https://upload.box.com/api");
|
|
323
|
+
this.timeoutMs = config.timeoutMs || 15e3;
|
|
324
|
+
this.maxResponseBytes = config.maxResponseBytes || 2097152;
|
|
325
|
+
this.maxDownloadBytes = config.maxDownloadBytes || 1048576;
|
|
326
|
+
this.maxUploadBytes = config.maxUploadBytes || 1048576;
|
|
327
|
+
if (![this.timeoutMs, this.maxResponseBytes, this.maxDownloadBytes, this.maxUploadBytes].every((value) => Number.isSafeInteger(value) && value > 0)) throw new TypeError("Box request limits must be positive integers");
|
|
328
|
+
if (this.maxUploadBytes > 50 * 1024 * 1024) throw new TypeError("Box direct upload limit exceeds 50 MiB");
|
|
329
|
+
this.credentials = credentials;
|
|
330
|
+
this.refreshDriver = options.refreshDriver ?? new ManifestCredentialRefreshDriver({
|
|
331
|
+
providerName: "Box",
|
|
332
|
+
auth: Authorization,
|
|
333
|
+
credentialFields: CredentialFields
|
|
334
|
+
});
|
|
335
|
+
this.send = options.send ?? sendProviderRequest;
|
|
336
|
+
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
337
|
+
}
|
|
338
|
+
/** Bind the bounded download Query. */
|
|
339
|
+
downloadFile() {
|
|
340
|
+
return new DownloadFileOperation(this);
|
|
341
|
+
}
|
|
342
|
+
/** Bind the bounded replacement Mutation. */
|
|
343
|
+
uploadFile() {
|
|
344
|
+
return new UploadFileOperation(this);
|
|
345
|
+
}
|
|
346
|
+
/** Download one file, following only Box's signed HTTPS content URL. */
|
|
347
|
+
async download(call, fileID) {
|
|
348
|
+
const token = await this.resolveToken(call);
|
|
349
|
+
if (typeof token !== "string") return token;
|
|
350
|
+
const first = await this.request(
|
|
351
|
+
call,
|
|
352
|
+
"GET",
|
|
353
|
+
this.baseURL + `/2.0/files/${fileID}/content`,
|
|
354
|
+
{ Authorization: "Bearer " + token },
|
|
355
|
+
this.maxDownloadBytes,
|
|
356
|
+
token
|
|
357
|
+
);
|
|
358
|
+
if (first.status !== 302 || first.error) return first;
|
|
359
|
+
const location = first.location ?? "";
|
|
360
|
+
if (!isBoxDownloadURL(location)) return { ...first, body: new Uint8Array(), error: "invalidRedirect" };
|
|
361
|
+
const second = await this.request(call, "GET", location, {}, this.maxDownloadBytes, token);
|
|
362
|
+
if (second.status === 302 && !second.error) return { ...second, body: new Uint8Array(), error: "invalidRedirect" };
|
|
363
|
+
return second;
|
|
364
|
+
}
|
|
365
|
+
/** Read one file's current identity and digest. */
|
|
366
|
+
async getFileMetadata(call, fileID) {
|
|
367
|
+
const token = await this.resolveToken(call);
|
|
368
|
+
if (typeof token !== "string") return token;
|
|
369
|
+
return this.request(
|
|
370
|
+
call,
|
|
371
|
+
"GET",
|
|
372
|
+
this.baseURL + `/2.0/files/${fileID}?fields=id,type,name,sha1,size`,
|
|
373
|
+
{ Authorization: "Bearer " + token, Accept: "application/json" },
|
|
374
|
+
this.maxResponseBytes,
|
|
375
|
+
token
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
/** Replace current content with Box's attributes-first multipart request. */
|
|
379
|
+
async upload(call, fileID, name, content) {
|
|
380
|
+
const token = await this.resolveToken(call);
|
|
381
|
+
if (typeof token !== "string") return token;
|
|
382
|
+
const boundary = "dexbox" + randomBytes(12).toString("hex");
|
|
383
|
+
const escapedName = name.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/[\r\n]/g, "_");
|
|
384
|
+
const body = Buffer.concat([
|
|
385
|
+
Buffer.from(`--${boundary}\r
|
|
386
|
+
Content-Disposition: form-data; name="attributes"\r
|
|
387
|
+
\r
|
|
388
|
+
${JSON.stringify({ name })}\r
|
|
389
|
+
`),
|
|
390
|
+
Buffer.from(`--${boundary}\r
|
|
391
|
+
Content-Disposition: form-data; name="file"; filename="${escapedName}"\r
|
|
392
|
+
Content-Type: application/octet-stream\r
|
|
393
|
+
\r
|
|
394
|
+
`),
|
|
395
|
+
Buffer.from(content),
|
|
396
|
+
Buffer.from(`\r
|
|
397
|
+
--${boundary}--\r
|
|
398
|
+
`)
|
|
399
|
+
]);
|
|
400
|
+
return this.request(call, "POST", this.uploadBaseURL + `/2.0/files/${fileID}/content`, {
|
|
401
|
+
Authorization: "Bearer " + token,
|
|
402
|
+
Accept: "application/json",
|
|
403
|
+
"Content-Type": `multipart/form-data; boundary=${boundary}`
|
|
404
|
+
}, this.maxResponseBytes, token, body);
|
|
405
|
+
}
|
|
406
|
+
async resolveToken(call) {
|
|
407
|
+
let credentials;
|
|
408
|
+
try {
|
|
409
|
+
credentials = await resolveCredential(this.credentials, call, this.refreshDriver, call.context.cancellationSignal);
|
|
410
|
+
} catch (error) {
|
|
411
|
+
const isTerminal = error instanceof ReauthorizationRequiredError || error instanceof ObjectNotFoundError || error instanceof ConnectionNotSelectedError || error instanceof CredentialBrokerRejectedError || isCredentialMaterialError(error);
|
|
412
|
+
return emptyExchange(isTerminal ? "credential" : "refresh");
|
|
413
|
+
}
|
|
414
|
+
const token = credentials.accessToken instanceof SecretString ? credentials.accessToken.reveal() : "";
|
|
415
|
+
return token && isHeaderSafeCredential(token) ? token : emptyExchange("credential");
|
|
416
|
+
}
|
|
417
|
+
async request(call, method, url, headers, successLimit, token, body) {
|
|
418
|
+
const request = {
|
|
419
|
+
url,
|
|
420
|
+
method,
|
|
421
|
+
headers: { ...headers, "User-Agent": "Dex Connector (https://superdurable.io)" },
|
|
422
|
+
maxResponseBytes: Math.max(successLimit, this.maxResponseBytes),
|
|
423
|
+
addressPolicy: new URL(url).protocol === "http:" ? "privateNetworkHTTP" : "publicHTTPS",
|
|
424
|
+
timeoutMs: this.timeoutMs,
|
|
425
|
+
signal: call.context.cancellationSignal,
|
|
426
|
+
...body === void 0 ? {} : { body }
|
|
427
|
+
};
|
|
428
|
+
let response;
|
|
429
|
+
try {
|
|
430
|
+
response = await this.send(request);
|
|
431
|
+
} catch (error) {
|
|
432
|
+
if (error instanceof BodyTooLargeError) return {
|
|
433
|
+
...emptyExchange("tooLarge"),
|
|
434
|
+
status: error.status ?? 0,
|
|
435
|
+
requestSent: true,
|
|
436
|
+
retryAfterMs: parseRetryAfter(header(error.headers ?? {}, "retry-after"), this.now())
|
|
437
|
+
};
|
|
438
|
+
if (error instanceof ProviderTransportError) return {
|
|
439
|
+
...emptyExchange("request"),
|
|
440
|
+
requestSent: !error.isProvablyNotSent
|
|
441
|
+
};
|
|
442
|
+
return emptyExchange("request");
|
|
443
|
+
}
|
|
444
|
+
const retryAfterMs = parseRetryAfter(header(response.headers, "retry-after"), this.now());
|
|
445
|
+
const location = response.status === 302 ? header(response.headers, "location") : "";
|
|
446
|
+
if (location.includes(token) || Buffer.from(response.body).includes(token))
|
|
447
|
+
return { status: response.status, body: new Uint8Array(), retryAfterMs, requestSent: true, error: "credential" };
|
|
448
|
+
const limit = response.status === 200 ? successLimit : this.maxResponseBytes;
|
|
449
|
+
if (response.body.length > limit) return { status: response.status, body: new Uint8Array(), retryAfterMs, requestSent: true, error: "tooLarge" };
|
|
450
|
+
return { status: response.status, body: response.body, retryAfterMs, requestSent: true, ...location ? { location } : {} };
|
|
451
|
+
}
|
|
452
|
+
};
|
|
453
|
+
function emptyExchange(error) {
|
|
454
|
+
return { status: 0, body: new Uint8Array(), retryAfterMs: 0, requestSent: false, error };
|
|
455
|
+
}
|
|
456
|
+
function isBoxDownloadURL(value) {
|
|
457
|
+
if (!value || value.length > 8192) return false;
|
|
458
|
+
try {
|
|
459
|
+
const url = new URL(value);
|
|
460
|
+
return url.protocol === "https:" && url.hostname.endsWith(".boxcloud.com") && !url.username && !url.password && !url.port && !url.hash && !!url.pathname;
|
|
461
|
+
} catch {
|
|
462
|
+
return false;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
function header(headers, name) {
|
|
466
|
+
const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
|
|
467
|
+
return Array.isArray(entry) ? entry[0] ?? "" : entry ?? "";
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
// src/project.ts
|
|
471
|
+
function encodeCredentials(credentials) {
|
|
472
|
+
return {
|
|
473
|
+
oauth_client_id: credentials.oauthClientId,
|
|
474
|
+
oauth_client_secret: credentials.oauthClientSecret.reveal(),
|
|
475
|
+
access_token: credentials.accessToken.reveal(),
|
|
476
|
+
refresh_token: credentials.refreshToken.reveal()
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
function newProjectConnection(project, connectionName, options = {}) {
|
|
480
|
+
if (!project) throw new TypeError("Box project is required");
|
|
481
|
+
const selected = project.configuration.connections.find((entry) => entry.connectorId === "box" && entry.connectionName === connectionName);
|
|
482
|
+
if (!selected || selected.provider !== "box") throw new TypeError("Box project connection is not configured");
|
|
483
|
+
const config = ConfigSchema.parse(selected.configuration);
|
|
484
|
+
const provider = newProjectCredentialProvider(project, connectionName, decodeCredentials, encodeCredentials, decodeSharedCredentials);
|
|
485
|
+
return newConnection(new BoxClient(config, provider, options), { provider: "box", name: connectionName });
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// src/generated/steps.ts
|
|
489
|
+
import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
|
|
490
|
+
function newDownloadFileStep(configuration) {
|
|
491
|
+
const { connection, connectionName, downloaded, notFound, tooLarge, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
|
|
492
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
493
|
+
return newQueryStep({ ...stepConfiguration, operation: connection.operations.downloadFile(), connection: connection.reference, branches: [
|
|
494
|
+
goToBranch("downloaded", downloaded),
|
|
495
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
496
|
+
...tooLarge ? [goToBranch("tooLarge", tooLarge)] : [],
|
|
497
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
498
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
499
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
500
|
+
] });
|
|
501
|
+
}
|
|
502
|
+
function newUploadFileStep(configuration) {
|
|
503
|
+
const { connection, connectionName, uploaded: uploaded2, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
|
|
504
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
505
|
+
return newMutationStep({ ...stepConfiguration, operation: connection.operations.uploadFile(), connection: connection.reference, branches: [
|
|
506
|
+
goToBranch("uploaded", uploaded2),
|
|
507
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
508
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
509
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
510
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
511
|
+
] });
|
|
512
|
+
}
|
|
513
|
+
export {
|
|
514
|
+
BoxClient,
|
|
515
|
+
ConfigSchema,
|
|
516
|
+
Connection,
|
|
517
|
+
ConnectorID,
|
|
518
|
+
CredentialMaterialError,
|
|
519
|
+
DownloadFileBranch,
|
|
520
|
+
DownloadFileBranchDefect,
|
|
521
|
+
DownloadFileBranchDownloaded,
|
|
522
|
+
DownloadFileBranchInvalidResponse,
|
|
523
|
+
DownloadFileBranchNotFound,
|
|
524
|
+
DownloadFileBranchProviderRejected,
|
|
525
|
+
DownloadFileBranchTooLarge,
|
|
526
|
+
DownloadFileDefinition,
|
|
527
|
+
DownloadFileInputSchema,
|
|
528
|
+
DownloadFileMetadata,
|
|
529
|
+
DownloadFileOperation,
|
|
530
|
+
DownloadedFileSchema,
|
|
531
|
+
ProviderID,
|
|
532
|
+
UploadFileBranch,
|
|
533
|
+
UploadFileBranchDefect,
|
|
534
|
+
UploadFileBranchInvalidResponse,
|
|
535
|
+
UploadFileBranchNotFound,
|
|
536
|
+
UploadFileBranchProviderRejected,
|
|
537
|
+
UploadFileBranchUploaded,
|
|
538
|
+
UploadFileDefinition,
|
|
539
|
+
UploadFileInputSchema,
|
|
540
|
+
UploadFileMetadata,
|
|
541
|
+
UploadFileOperation,
|
|
542
|
+
UploadedFileSchema,
|
|
543
|
+
decodeCredentials,
|
|
544
|
+
decodeSharedCredentials,
|
|
545
|
+
header,
|
|
546
|
+
isCredentialMaterialError,
|
|
547
|
+
newConnection,
|
|
548
|
+
newConnectionWithOperations,
|
|
549
|
+
newDownloadFileStep,
|
|
550
|
+
newProjectConnection,
|
|
551
|
+
newUploadFileStep
|
|
552
|
+
};
|
package/dist/mock.d.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { MockQuery, MockMutation, Case } from '@superdurable/connectors-sdk/connectormock';
|
|
2
|
+
import { Failure } from '@superdurable/connectors-sdk';
|
|
3
|
+
import { O as Operations, d as Connection, D as DownloadFileInput, a as DownloadedFile, U as UploadFileInput, b as UploadedFile } from './connection-DfqaRnkX.js';
|
|
4
|
+
import 'zod';
|
|
5
|
+
|
|
6
|
+
/** Go zero value for DownloadFileInput in scripted cases. */
|
|
7
|
+
declare const emptyDownloadFileInput: DownloadFileInput;
|
|
8
|
+
/** Go zero value for DownloadedFile in scripted cases. */
|
|
9
|
+
declare const emptyDownloadedFile: DownloadedFile;
|
|
10
|
+
/** Go zero value for UploadFileInput in scripted cases. */
|
|
11
|
+
declare const emptyUploadFileInput: UploadFileInput;
|
|
12
|
+
/** Go zero value for UploadedFile in scripted cases. */
|
|
13
|
+
declare const emptyUploadedFile: UploadedFile;
|
|
14
|
+
/** Script the downloaded branch. */
|
|
15
|
+
declare function downloadFileDownloaded(value: DownloadedFile, failure?: Failure): Case<DownloadedFile>;
|
|
16
|
+
/** Script the notFound branch. */
|
|
17
|
+
declare function downloadFileNotFound(value: DownloadedFile, failure?: Failure): Case<DownloadedFile>;
|
|
18
|
+
/** Script the tooLarge branch. */
|
|
19
|
+
declare function downloadFileTooLarge(value: DownloadedFile, failure?: Failure): Case<DownloadedFile>;
|
|
20
|
+
/** Script the providerRejected branch. */
|
|
21
|
+
declare function downloadFileProviderRejected(value: DownloadedFile, failure?: Failure): Case<DownloadedFile>;
|
|
22
|
+
/** Script the invalidResponse branch. */
|
|
23
|
+
declare function downloadFileInvalidResponse(value: DownloadedFile, failure?: Failure): Case<DownloadedFile>;
|
|
24
|
+
/** Script the defect branch. */
|
|
25
|
+
declare function downloadFileDefect(value: DownloadedFile, failure?: Failure): Case<DownloadedFile>;
|
|
26
|
+
/** Script a safe retry of downloadFile. */
|
|
27
|
+
declare function downloadFileRetry(failure: Failure, retryAfterMs?: number): Case<DownloadedFile>;
|
|
28
|
+
/** Manifest scenario downloadedDefault for downloadFile. */
|
|
29
|
+
declare function downloadFileDownloadedDefault(): Case<DownloadedFile>;
|
|
30
|
+
/** Default downloadFile scenario. */
|
|
31
|
+
declare function downloadFileDefault(): Case<DownloadedFile>;
|
|
32
|
+
/** Script the uploaded branch. */
|
|
33
|
+
declare function uploadFileUploaded(value: UploadedFile, failure?: Failure): Case<UploadedFile>;
|
|
34
|
+
/** Script the notFound branch. */
|
|
35
|
+
declare function uploadFileNotFound(value: UploadedFile, failure?: Failure): Case<UploadedFile>;
|
|
36
|
+
/** Script the providerRejected branch. */
|
|
37
|
+
declare function uploadFileProviderRejected(value: UploadedFile, failure?: Failure): Case<UploadedFile>;
|
|
38
|
+
/** Script the invalidResponse branch. */
|
|
39
|
+
declare function uploadFileInvalidResponse(value: UploadedFile, failure?: Failure): Case<UploadedFile>;
|
|
40
|
+
/** Script the defect branch. */
|
|
41
|
+
declare function uploadFileDefect(value: UploadedFile, failure?: Failure): Case<UploadedFile>;
|
|
42
|
+
/** Script a safe retry of uploadFile. */
|
|
43
|
+
declare function uploadFileRetry(failure: Failure, retryAfterMs?: number): Case<UploadedFile>;
|
|
44
|
+
/** Manifest scenario uploadedDefault for uploadFile. */
|
|
45
|
+
declare function uploadFileUploadedDefault(): Case<UploadedFile>;
|
|
46
|
+
/** Default uploadFile scenario. */
|
|
47
|
+
declare function uploadFileDefault(): Case<UploadedFile>;
|
|
48
|
+
/** Scripted operations and manifest defaults for this connector. */
|
|
49
|
+
declare class GeneratedMock implements Operations {
|
|
50
|
+
#private;
|
|
51
|
+
constructor(connectionName: string);
|
|
52
|
+
connection(): Connection;
|
|
53
|
+
downloadFile(): MockQuery<DownloadFileInput, DownloadedFile>;
|
|
54
|
+
uploadFile(): MockMutation<UploadFileInput, UploadedFile>;
|
|
55
|
+
assertNoFailures(): void;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export { GeneratedMock, downloadFileDefault, downloadFileDefect, downloadFileDownloaded, downloadFileDownloadedDefault, downloadFileInvalidResponse, downloadFileNotFound, downloadFileProviderRejected, downloadFileRetry, downloadFileTooLarge, emptyDownloadFileInput, emptyDownloadedFile, emptyUploadFileInput, emptyUploadedFile, uploadFileDefault, uploadFileDefect, uploadFileInvalidResponse, uploadFileNotFound, uploadFileProviderRejected, uploadFileRetry, uploadFileUploaded, uploadFileUploadedDefault };
|
package/dist/mock.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import {
|
|
2
|
+
GeneratedMock,
|
|
3
|
+
downloadFileDefault,
|
|
4
|
+
downloadFileDefect,
|
|
5
|
+
downloadFileDownloaded,
|
|
6
|
+
downloadFileDownloadedDefault,
|
|
7
|
+
downloadFileInvalidResponse,
|
|
8
|
+
downloadFileNotFound,
|
|
9
|
+
downloadFileProviderRejected,
|
|
10
|
+
downloadFileRetry,
|
|
11
|
+
downloadFileTooLarge,
|
|
12
|
+
emptyDownloadFileInput,
|
|
13
|
+
emptyDownloadedFile,
|
|
14
|
+
emptyUploadFileInput,
|
|
15
|
+
emptyUploadedFile,
|
|
16
|
+
uploadFileDefault,
|
|
17
|
+
uploadFileDefect,
|
|
18
|
+
uploadFileInvalidResponse,
|
|
19
|
+
uploadFileNotFound,
|
|
20
|
+
uploadFileProviderRejected,
|
|
21
|
+
uploadFileRetry,
|
|
22
|
+
uploadFileUploaded,
|
|
23
|
+
uploadFileUploadedDefault
|
|
24
|
+
} from "./chunk-C3MMWLYU.js";
|
|
25
|
+
export {
|
|
26
|
+
GeneratedMock,
|
|
27
|
+
downloadFileDefault,
|
|
28
|
+
downloadFileDefect,
|
|
29
|
+
downloadFileDownloaded,
|
|
30
|
+
downloadFileDownloadedDefault,
|
|
31
|
+
downloadFileInvalidResponse,
|
|
32
|
+
downloadFileNotFound,
|
|
33
|
+
downloadFileProviderRejected,
|
|
34
|
+
downloadFileRetry,
|
|
35
|
+
downloadFileTooLarge,
|
|
36
|
+
emptyDownloadFileInput,
|
|
37
|
+
emptyDownloadedFile,
|
|
38
|
+
emptyUploadFileInput,
|
|
39
|
+
emptyUploadedFile,
|
|
40
|
+
uploadFileDefault,
|
|
41
|
+
uploadFileDefect,
|
|
42
|
+
uploadFileInvalidResponse,
|
|
43
|
+
uploadFileNotFound,
|
|
44
|
+
uploadFileProviderRejected,
|
|
45
|
+
uploadFileRetry,
|
|
46
|
+
uploadFileUploaded,
|
|
47
|
+
uploadFileUploadedDefault
|
|
48
|
+
};
|