@superdurable/connector-amazon-s3 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,726 @@
1
+ import {
2
+ ConfigSchema,
3
+ Connection,
4
+ ConnectionNameProvider,
5
+ ConnectorID,
6
+ GetObjectTextBranch,
7
+ GetObjectTextBranchDefect,
8
+ GetObjectTextBranchInvalidResponse,
9
+ GetObjectTextBranchNotFound,
10
+ GetObjectTextBranchProviderRejected,
11
+ GetObjectTextBranchRead,
12
+ GetObjectTextBranchTooLarge,
13
+ GetObjectTextBranchUnsupportedContent,
14
+ GetObjectTextDefinition,
15
+ GetObjectTextInputSchema,
16
+ GetObjectTextMetadata,
17
+ HeadObjectBranch,
18
+ HeadObjectBranchDefect,
19
+ HeadObjectBranchFound,
20
+ HeadObjectBranchInvalidResponse,
21
+ HeadObjectBranchNotFound,
22
+ HeadObjectBranchProviderRejected,
23
+ HeadObjectDefinition,
24
+ HeadObjectInputSchema,
25
+ HeadObjectMetadata,
26
+ ListObjectsBranch,
27
+ ListObjectsBranchDefect,
28
+ ListObjectsBranchFound,
29
+ ListObjectsBranchInvalidResponse,
30
+ ListObjectsBranchNotFound,
31
+ ListObjectsBranchProviderRejected,
32
+ ListObjectsDefinition,
33
+ ListObjectsInputSchema,
34
+ ListObjectsMetadata,
35
+ ListObjectsOutputSchema,
36
+ ObjectMetadataSchema,
37
+ ObjectSummarySchema,
38
+ ObjectTextSchema,
39
+ ProviderID,
40
+ PutObjectBranch,
41
+ PutObjectBranchAlreadyExists,
42
+ PutObjectBranchDefect,
43
+ PutObjectBranchProviderRejected,
44
+ PutObjectBranchStored,
45
+ PutObjectDefinition,
46
+ PutObjectInputSchema,
47
+ PutObjectMetadata,
48
+ StoredObjectSchema,
49
+ newConnection,
50
+ newConnectionWithOperations
51
+ } from "./chunk-OCSVX3FX.js";
52
+
53
+ // src/client.ts
54
+ import { createHash as createHash2, createHmac } from "crypto";
55
+ import { BodyTooLargeError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
56
+
57
+ // src/operations.ts
58
+ import { createHash } from "crypto";
59
+ import { XMLParser, XMLValidator } from "fast-xml-parser";
60
+ import { newMutationBranch, newMutationRetry, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
61
+ var parser = new XMLParser({ ignoreAttributes: true, parseTagValue: false, processEntities: true });
62
+ var zeroList = { bucket: "", isTruncated: false };
63
+ var zeroMetadata = { bucket: "", key: "", sizeBytes: 0 };
64
+ var zeroText = { bucket: "", key: "", sizeBytes: 0 };
65
+ var zeroStored = { bucket: "", key: "", sizeBytes: 0 };
66
+ var ListObjectsOperation = class {
67
+ /** Bind one client. */
68
+ constructor(client) {
69
+ this.client = client;
70
+ }
71
+ client;
72
+ /** Return the manifest operation identity. */
73
+ definition() {
74
+ return ListObjectsDefinition;
75
+ }
76
+ /** Send and classify one bucket listing. */
77
+ async invoke(call, input) {
78
+ const operation = "listObjects";
79
+ if (!ListObjectsInputSchema.safeParse(input).success) return defectQuery(operation, zeroList, "invalid list input");
80
+ let bucket;
81
+ try {
82
+ bucket = this.client.bucket(input.bucket);
83
+ for (const field of ["prefix", "delimiter", "startAfter"]) validateKey(input[field] ?? "", field, true);
84
+ if (input.continuationToken && (Buffer.byteLength(input.continuationToken) > 4096 || !/^[!-~]+$/.test(input.continuationToken))) throw new TypeError("continuationToken must be printable");
85
+ } catch (error) {
86
+ return defectQuery(operation, zeroList, errorMessage(error));
87
+ }
88
+ const maxKeys = input.maxKeys || this.client.listPageSize;
89
+ if (!Number.isSafeInteger(maxKeys) || maxKeys < 1 || maxKeys > 1e3) return defectQuery(operation, zeroList, "maxKeys must be from 1 to 1000");
90
+ const session = await this.client.startSession(call);
91
+ if (!session) return credentialDefectQuery(operation, zeroList);
92
+ const query = { "list-type": "2", "encoding-type": "url", "max-keys": String(maxKeys) };
93
+ if (input.prefix) query.prefix = input.prefix;
94
+ if (input.delimiter) query.delimiter = input.delimiter;
95
+ if (input.startAfter) query["start-after"] = input.startAfter;
96
+ if (input.continuationToken) query["continuation-token"] = input.continuationToken;
97
+ let response;
98
+ try {
99
+ response = await this.client.exchange(call, session, { method: "GET", bucket, query });
100
+ } catch {
101
+ return newQueryRetry(failure(operation, "TRANSPORT", "S3 could not be reached or did not finish the list"));
102
+ }
103
+ const receipt = this.client.receipt(call, response, bucket);
104
+ if (response.status < 200 || response.status >= 300) return queryFailure(operation, "list", response, session, receipt, { bucket, isTruncated: false }, false, this.client.currentTime());
105
+ if (response.isTooLarge) return newQueryBranch("invalidResponse", { bucket, isTruncated: false }, receipt, failure(operation, "RESPONSE_TOO_LARGE", "S3 list page exceeds maxResponseBytes"));
106
+ const contents = Buffer.from(response.body).toString("utf8");
107
+ if (containsCredential(contents, session)) return newQueryBranch("invalidResponse", { bucket, isTruncated: false }, receipt, failure(operation, "PROTOCOL", "S3 list page contains credentials"));
108
+ let output;
109
+ try {
110
+ output = decodeListPage(contents, bucket, input.prefix, input.delimiter);
111
+ } catch {
112
+ return newQueryBranch("invalidResponse", { bucket, isTruncated: false }, receipt, failure(operation, "PROTOCOL", "S3 returned an invalid list page"));
113
+ }
114
+ if (!output.objects?.length && !output.commonPrefixes?.length && !output.isTruncated) return newQueryBranch("notFound", output, receipt, failure(operation, "NOT_FOUND", "no object matched the prefix"));
115
+ return newQueryBranch("found", output, receipt);
116
+ }
117
+ };
118
+ var HeadObjectOperation = class {
119
+ /** Bind one client. */
120
+ constructor(client) {
121
+ this.client = client;
122
+ }
123
+ client;
124
+ /** Return the manifest operation identity. */
125
+ definition() {
126
+ return HeadObjectDefinition;
127
+ }
128
+ /** Send and classify one HEAD request. */
129
+ async invoke(call, input) {
130
+ const operation = "headObject";
131
+ if (!HeadObjectInputSchema.safeParse(input).success) return defectQuery(operation, zeroMetadata, "invalid object input");
132
+ let bucket;
133
+ try {
134
+ bucket = this.client.bucket(input.bucket);
135
+ validateKey(input.key);
136
+ } catch (error) {
137
+ return defectQuery(operation, zeroMetadata, errorMessage(error));
138
+ }
139
+ const session = await this.client.startSession(call);
140
+ if (!session) return credentialDefectQuery(operation, zeroMetadata);
141
+ const identity = { bucket, key: input.key, sizeBytes: 0 };
142
+ let response;
143
+ try {
144
+ response = await this.client.exchange(call, session, { method: "HEAD", bucket, key: input.key, maxBytes: 65536 });
145
+ } catch {
146
+ return newQueryRetry(failure(operation, "TRANSPORT", "S3 could not be reached or did not finish the object metadata read"));
147
+ }
148
+ const receipt = this.client.receipt(call, response, bucket, input.key);
149
+ if (response.status < 200 || response.status >= 300) return queryFailure(operation, "object", response, session, receipt, identity, true, this.client.currentTime());
150
+ const metadata = decodeMetadata(response, session, bucket, input.key);
151
+ if (!metadata) return newQueryBranch("invalidResponse", identity, receipt, failure(operation, "PROTOCOL", "S3 returned object metadata without a valid size or modification time"));
152
+ return newQueryBranch("found", metadata, receipt);
153
+ }
154
+ };
155
+ var GetObjectTextOperation = class {
156
+ /** Bind one client. */
157
+ constructor(client) {
158
+ this.client = client;
159
+ }
160
+ client;
161
+ /** Return the manifest operation identity. */
162
+ definition() {
163
+ return GetObjectTextDefinition;
164
+ }
165
+ /** Send and classify one object GET. */
166
+ async invoke(call, input) {
167
+ const operation = "getObjectText";
168
+ if (!GetObjectTextInputSchema.safeParse(input).success) return defectQuery(operation, zeroText, "invalid object input");
169
+ let bucket;
170
+ try {
171
+ bucket = this.client.bucket(input.bucket);
172
+ validateKey(input.key);
173
+ } catch (error) {
174
+ return defectQuery(operation, zeroText, errorMessage(error));
175
+ }
176
+ const session = await this.client.startSession(call);
177
+ if (!session) return credentialDefectQuery(operation, zeroText);
178
+ const identity = { bucket, key: input.key, sizeBytes: 0 };
179
+ let response;
180
+ try {
181
+ response = await this.client.exchange(call, session, { method: "GET", bucket, key: input.key, maxBytes: Math.max(this.client.maxTextBytes, 65536) });
182
+ } catch {
183
+ return newQueryRetry(failure(operation, "TRANSPORT", "S3 could not be reached or did not finish the object read"));
184
+ }
185
+ const receipt = this.client.receipt(call, response, bucket, input.key);
186
+ if (response.status < 200 || response.status >= 300) return queryFailure(operation, "object", response, session, receipt, identity, true, this.client.currentTime());
187
+ const metadata = decodeMetadata(response, session, bucket, input.key);
188
+ const output = { bucket, key: input.key, sizeBytes: metadata?.sizeBytes ?? parseLength(header(response, "content-length")) ?? 0 };
189
+ const contentType = safeHeader(response, "content-type", session);
190
+ const etag = safeHeader(response, "etag", session);
191
+ if (contentType) output.contentType = contentType;
192
+ if (etag) output.eTag = etag;
193
+ if (metadata?.versionId) output.versionId = metadata.versionId;
194
+ if (metadata?.lastModified) output.lastModified = metadata.lastModified;
195
+ const encoding = header(response, "content-encoding").trim();
196
+ const mediaType = contentType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
197
+ const allowed = mediaType.startsWith("text/") || ["application/json", "application/ld+json", "application/xml", "application/yaml", "application/x-yaml", "application/x-ndjson", "application/javascript", "application/sql", "application/csv", "application/toml"].includes(mediaType) || ["+json", "+xml", "+yaml"].some((suffix) => mediaType.endsWith(suffix));
198
+ if (encoding && encoding.toLowerCase() !== "identity" || !allowed && mediaType !== "" && mediaType !== "application/octet-stream" && mediaType !== "binary/octet-stream") return newQueryBranch("unsupportedContent", output, receipt, failure(operation, "VALIDATION", "object content is not UTF-8 text"));
199
+ if (output.sizeBytes > this.client.maxTextBytes || response.isTooLarge) return newQueryBranch("tooLarge", output, receipt, failure(operation, "RESPONSE_TOO_LARGE", "object size exceeds maxTextBytes"));
200
+ if (metadata?.sizeBytes !== void 0 && metadata.sizeBytes !== response.body.length) return newQueryBranch("invalidResponse", output, receipt, failure(operation, "PROTOCOL", "S3 returned content whose length differs from Content-Length"));
201
+ let text;
202
+ try {
203
+ text = new TextDecoder("utf-8", { fatal: true }).decode(response.body);
204
+ } catch {
205
+ return newQueryBranch("unsupportedContent", { ...output, sizeBytes: response.body.length }, receipt, failure(operation, "VALIDATION", "object content is not valid UTF-8 text"));
206
+ }
207
+ output.sizeBytes = response.body.length;
208
+ if (text.includes("\0")) return newQueryBranch("unsupportedContent", output, receipt, failure(operation, "VALIDATION", "object content is not valid UTF-8 text"));
209
+ if (containsCredential(text, session)) return newQueryBranch("invalidResponse", output, receipt, failure(operation, "PROTOCOL", "object content contains credentials"));
210
+ output.text = text;
211
+ return newQueryBranch("read", output, receipt);
212
+ }
213
+ };
214
+ var PutObjectOperation = class {
215
+ /** Bind one client. */
216
+ constructor(client) {
217
+ this.client = client;
218
+ }
219
+ client;
220
+ /** Return the manifest operation identity. */
221
+ definition() {
222
+ return PutObjectDefinition;
223
+ }
224
+ /** Use the stable Dex Call ID as the object marker. */
225
+ idempotencyKey(callId) {
226
+ return callId;
227
+ }
228
+ /** Send a signed PUT and reconcile create-only precondition failures. */
229
+ async invoke(call, input) {
230
+ const operation = "putObject";
231
+ if (!PutObjectInputSchema.safeParse(input).success) return defectMutation(zeroStored, "invalid object input");
232
+ let bucket;
233
+ let content;
234
+ try {
235
+ bucket = this.client.bucket(input.bucket);
236
+ validateKey(input.key);
237
+ if (input.textContent && input.byteContent) throw new TypeError("set at most one of textContent and byteContent");
238
+ if (input.byteContent && !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(input.byteContent)) throw new TypeError("byteContent must be base64");
239
+ content = input.textContent ? Buffer.from(input.textContent, "utf8") : Buffer.from(input.byteContent ?? "", "base64");
240
+ if (content.length > this.client.maxUploadBytes) throw new TypeError("content exceeds maxUploadBytes");
241
+ validatePutHeaders(input);
242
+ if (!/^[!-~]+$/.test(call.id) || call.id.length > 128) throw new TypeError("idempotency key is missing or not header-safe");
243
+ } catch (error) {
244
+ return defectMutation(zeroStored, errorMessage(error));
245
+ }
246
+ const session = await this.client.startSession(call);
247
+ if (!session) return newMutationBranch("defect", zeroStored, {}, failure(operation, "AUTHENTICATION", "S3 connection credentials are unavailable"));
248
+ const requested = { bucket, key: input.key, sizeBytes: content.length, contentType: input.contentType };
249
+ const headers = { "content-type": input.contentType, "content-md5": createHash("md5").update(content).digest("base64"), "x-amz-meta-dex-idempotency-key": call.id };
250
+ for (const [name, value] of Object.entries(input.metadata ?? {})) headers[`x-amz-meta-${name}`] = value;
251
+ if (input.isCreateOnly) headers["if-none-match"] = "*";
252
+ let response;
253
+ try {
254
+ response = await this.client.exchange(call, session, { method: "PUT", bucket, key: input.key, headers, body: content, maxBytes: 65536 });
255
+ } catch {
256
+ return newMutationRetry(failure(operation, "TRANSPORT", "S3 could not be reached or did not finish the object write"));
257
+ }
258
+ const receipt = this.client.receipt(call, response, bucket, input.key);
259
+ if (response.status >= 200 && response.status < 300) {
260
+ const etag = safeHeader(response, "etag", session);
261
+ const versionId = safeHeader(response, "x-amz-version-id", session);
262
+ return newMutationBranch("stored", { ...requested, ...etag ? { eTag: etag } : {}, ...versionId ? { versionId } : {} }, receipt);
263
+ }
264
+ if (input.isCreateOnly && response.status === 412) return this.readExisting(call, session, requested);
265
+ const classified = classify(operation, "object write", response, session, false, this.client.currentTime());
266
+ if (classified.retry) return newMutationRetry(classified.failure, classified.retryAfterMs);
267
+ return newMutationBranch("providerRejected", requested, receipt, classified.failure);
268
+ }
269
+ async readExisting(call, session, requested) {
270
+ let response;
271
+ try {
272
+ response = await this.client.exchange(call, session, { method: "HEAD", bucket: requested.bucket, key: requested.key, maxBytes: 65536 });
273
+ } catch {
274
+ return newMutationRetry(failure("putObject", "TRANSPORT", "S3 could not be reached or did not finish the object metadata read"));
275
+ }
276
+ const receipt = this.client.receipt(call, response, requested.bucket, requested.key);
277
+ if (response.status === 404) return newMutationRetry(failure("putObject", "CONFLICT", "the object was removed before it could be read"));
278
+ if (response.status < 200 || response.status >= 300) {
279
+ const classified = classify("putObject", "object", response, session, true, this.client.currentTime());
280
+ if (classified.retry) return newMutationRetry(classified.failure, classified.retryAfterMs);
281
+ if (classified.failure.kind === "AUTHORIZATION") return newMutationBranch("providerRejected", requested, receipt, classified.failure);
282
+ return newMutationBranch("providerRejected", requested, receipt, classified.failure);
283
+ }
284
+ const metadata = decodeMetadata(response, session, requested.bucket, requested.key);
285
+ if (!metadata) return newMutationBranch("providerRejected", requested, receipt, failure("putObject", "PROTOCOL", "S3 returned invalid metadata for the existing object"));
286
+ const stored = { bucket: requested.bucket, key: requested.key, sizeBytes: metadata.sizeBytes, contentType: metadata.contentType ?? "" };
287
+ if (metadata.eTag) stored.eTag = metadata.eTag;
288
+ if (metadata.versionId) stored.versionId = metadata.versionId;
289
+ if (metadata.lastModified) stored.lastModified = metadata.lastModified;
290
+ if (metadata.metadata?.["dex-idempotency-key"] === call.id) return newMutationBranch("stored", { ...stored, isFromEarlierAttempt: true }, receipt);
291
+ return newMutationBranch("alreadyExists", stored, receipt, failure("putObject", "CONFLICT", "another object already exists"));
292
+ }
293
+ };
294
+ function failure(operation, kind, message) {
295
+ return { provider: "amazon-s3", operation, kind, message };
296
+ }
297
+ function errorMessage(error) {
298
+ return error instanceof Error ? error.message : "S3 input is invalid";
299
+ }
300
+ function defectQuery(operation, value, message) {
301
+ return newQueryBranch("defect", value, {}, failure(operation, "VALIDATION", message));
302
+ }
303
+ function credentialDefectQuery(operation, value) {
304
+ return newQueryBranch("defect", value, {}, failure(operation, "AUTHENTICATION", "S3 connection credentials are unavailable"));
305
+ }
306
+ function defectMutation(value, message) {
307
+ return newMutationBranch("defect", value, {}, failure("putObject", "VALIDATION", message));
308
+ }
309
+ function classify(operation, subject, response, session, isObject, now) {
310
+ const code = response.status === 404 && response.body.length === 0 ? "" : errorCode(response.body, session);
311
+ const status = response.status;
312
+ const delay = retryAfter(response, now);
313
+ let kind = "PROVIDER_REJECTION";
314
+ let retry = false;
315
+ let notFound = false;
316
+ if (status === 429 || code === "SlowDown") {
317
+ kind = "RATE_LIMIT";
318
+ retry = true;
319
+ } else if (status === 408 || code === "RequestTimeout") {
320
+ kind = "TRANSPORT";
321
+ retry = true;
322
+ } else if (code === "ConditionalRequestConflict" || code === "OperationAborted") {
323
+ kind = "CONFLICT";
324
+ retry = true;
325
+ } else if (status === 307 || status >= 500 && status !== 501) {
326
+ kind = "AVAILABILITY";
327
+ retry = true;
328
+ } else if (status === 404 && isObject && code !== "NoSuchBucket") {
329
+ kind = "NOT_FOUND";
330
+ notFound = true;
331
+ } else if (status === 404) kind = "NOT_FOUND";
332
+ else if (code === "RequestTimeTooSkewed" || ["InvalidAccessKeyId", "SignatureDoesNotMatch", "ExpiredToken", "InvalidToken", "TokenRefreshRequired", "InvalidSecurity"].includes(code) || status === 401) kind = "AUTHENTICATION";
333
+ else if (status === 403) kind = "AUTHORIZATION";
334
+ else if (status === 412 || status === 409) kind = "CONFLICT";
335
+ return { retry, notFound, failure: failure(operation, kind, `S3 rejected the ${subject} with HTTP ${status}${code ? ` ${code}` : ""}`), retryAfterMs: delay };
336
+ }
337
+ function queryFailure(operation, subject, response, session, receipt, value, isObject, now) {
338
+ const classified = classify(operation, subject, response, session, isObject, now);
339
+ if (classified.retry) return newQueryRetry(classified.failure, classified.retryAfterMs);
340
+ return newQueryBranch(classified.notFound ? "notFound" : "providerRejected", value, receipt, classified.failure);
341
+ }
342
+ function errorCode(body, session) {
343
+ const text = Buffer.from(body).toString("utf8");
344
+ if (text.length > 65536 || XMLValidator.validate(text) !== true) return "";
345
+ const parsed = parser.parse(text);
346
+ const code = parsed.Error?.Code;
347
+ return typeof code === "string" && /^[A-Za-z0-9.]{1,64}$/.test(code) && !containsCredential(code, session, true) ? code : "";
348
+ }
349
+ function parseLength(value) {
350
+ return /^\d+$/.test(value) && Number.isSafeInteger(Number(value)) ? Number(value) : void 0;
351
+ }
352
+ function parseDate(value) {
353
+ const date = new Date(value);
354
+ return value && !Number.isNaN(date.getTime()) ? date.toISOString().replace(".000Z", "Z") : void 0;
355
+ }
356
+ function decodeMetadata(response, session, bucket, key) {
357
+ const size = parseLength(header(response, "content-length"));
358
+ const lastModified = parseDate(header(response, "last-modified"));
359
+ if (size === void 0 || !lastModified) return void 0;
360
+ const output = { bucket, key, sizeBytes: size, lastModified };
361
+ for (const [field, name] of Object.entries({ eTag: "etag", contentType: "content-type", contentEncoding: "content-encoding", contentLanguage: "content-language", contentDisposition: "content-disposition", cacheControl: "cache-control", versionId: "x-amz-version-id", storageClass: "x-amz-storage-class", serverSideEncryption: "x-amz-server-side-encryption" })) {
362
+ const value = safeHeader(response, name, session);
363
+ if (value) output[field] = value;
364
+ }
365
+ const metadata = {};
366
+ for (const name of Object.keys(response.headers)) if (name.toLowerCase().startsWith("x-amz-meta-")) {
367
+ const value = safeHeader(response, name, session);
368
+ if (value) metadata[name.slice("x-amz-meta-".length).toLowerCase()] = value;
369
+ }
370
+ if (Object.keys(metadata).length) output.metadata = metadata;
371
+ const missing = parseLength(header(response, "x-amz-missing-meta"));
372
+ if (missing && missing > 0) output.missingMetadataCount = missing;
373
+ return output;
374
+ }
375
+ function decodeListPage(xml, bucket, prefix, delimiter) {
376
+ if (XMLValidator.validate(xml) !== true) throw new TypeError("invalid XML");
377
+ const document = parser.parse(xml);
378
+ const page = document.ListBucketResult;
379
+ if (!page) throw new TypeError("missing ListBucketResult");
380
+ const isTruncated = page.IsTruncated === "true";
381
+ const nextContinuationToken = typeof page.NextContinuationToken === "string" ? page.NextContinuationToken : "";
382
+ if (isTruncated && !nextContinuationToken) throw new TypeError("missing continuation token");
383
+ if (nextContinuationToken && (Buffer.byteLength(nextContinuationToken) > 4096 || !/^[!-~]+$/.test(nextContinuationToken))) throw new TypeError("invalid continuation token");
384
+ const isEncoded = page.EncodingType === "url";
385
+ const decodeKey = (value) => {
386
+ if (typeof value !== "string" || !value) throw new TypeError("missing key");
387
+ const decoded = isEncoded ? decodeURIComponent(value.replace(/\+/g, " ")) : value;
388
+ if (!decoded) throw new TypeError("missing key");
389
+ return decoded;
390
+ };
391
+ const objects = [];
392
+ for (const item of asArray(page.Contents)) {
393
+ const record = asRecord(item);
394
+ const size = parseLength(String(record.Size ?? ""));
395
+ if (size === void 0) throw new TypeError("invalid object size");
396
+ const summary = { key: decodeKey(record.Key), sizeBytes: size };
397
+ if (typeof record.ETag === "string" && record.ETag) summary.eTag = record.ETag;
398
+ if (typeof record.StorageClass === "string" && record.StorageClass) summary.storageClass = record.StorageClass;
399
+ if (typeof record.LastModified === "string" && record.LastModified) {
400
+ const date = parseDate(record.LastModified);
401
+ if (!date) throw new TypeError("invalid object date");
402
+ summary.lastModified = date;
403
+ }
404
+ objects.push(summary);
405
+ }
406
+ const commonPrefixes = asArray(page.CommonPrefixes).map((item) => decodeKey(asRecord(item).Prefix));
407
+ return { bucket, ...prefix ? { prefix } : {}, ...delimiter ? { delimiter } : {}, ...objects.length ? { objects } : {}, ...commonPrefixes.length ? { commonPrefixes } : {}, isTruncated, ...nextContinuationToken ? { nextContinuationToken } : {} };
408
+ }
409
+ function asArray(value) {
410
+ return value === void 0 ? [] : Array.isArray(value) ? value : [value];
411
+ }
412
+ function asRecord(value) {
413
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("invalid XML element");
414
+ return value;
415
+ }
416
+ function validatePutHeaders(input) {
417
+ if (!input.contentType || Buffer.byteLength(input.contentType) > 256 || /[^\x20-\x7E]/.test(input.contentType)) throw new TypeError("contentType must be a printable media type");
418
+ let metadataBytes = 0;
419
+ for (const [name, value] of Object.entries(input.metadata ?? {})) {
420
+ if (!/^[a-z0-9][a-z0-9._-]{0,127}$/.test(name) || name === "dex-idempotency-key" || /[^\x20-\x7E]/.test(value)) throw new TypeError("user metadata is invalid");
421
+ metadataBytes += Buffer.byteLength(name) + Buffer.byteLength(value);
422
+ }
423
+ if (metadataBytes > 2048) throw new TypeError("user metadata exceeds 2048 bytes");
424
+ }
425
+
426
+ // src/client.ts
427
+ var emptyHash = createHash2("sha256").update("").digest("hex");
428
+ var encoder = new TextEncoder();
429
+ var S3Client = class {
430
+ region;
431
+ defaultBucket;
432
+ listPageSize;
433
+ maxResponseBytes;
434
+ maxTextBytes;
435
+ maxUploadBytes;
436
+ endpoint;
437
+ addressingStyle;
438
+ isAmazonEndpoint;
439
+ credentials;
440
+ send;
441
+ now;
442
+ /** Validate public configuration and bind a private credential source. */
443
+ constructor(config, credentials, options = {}) {
444
+ if (!credentials) throw new TypeError("credential provider is required");
445
+ this.region = config.region || "us-east-1";
446
+ if (!/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/.test(this.region)) throw new TypeError("S3 region must be a Region code");
447
+ const suffix = /^(us|eu|ap|sa|ca|me|af|il|mx)-\w+-\d+$|^us-gov-\w+-\d+$/.test(this.region) ? "amazonaws.com" : /^cn-\w+-\d+$/.test(this.region) ? "amazonaws.com.cn" : /^eusc-de-\w+-\d+$/.test(this.region) ? "amazonaws.eu" : "";
448
+ this.isAmazonEndpoint = !config.endpoint;
449
+ if (this.isAmazonEndpoint && !suffix) throw new TypeError("S3 region is not an Amazon S3 Region; set endpoint");
450
+ this.endpoint = new URL(validateBaseURL(config.endpoint || `https://s3.${this.region}.${suffix}`));
451
+ if (!/^(\/[A-Za-z0-9._~-]+)*$/.test(this.endpoint.pathname.replace(/\/$/, "")) || this.endpoint.search || this.endpoint.hash) throw new TypeError("S3 endpoint path is invalid");
452
+ this.addressingStyle = config.addressingStyle || "auto";
453
+ if (!["auto", "path", "virtualHosted"].includes(this.addressingStyle)) throw new TypeError("S3 addressingStyle is invalid");
454
+ this.defaultBucket = config.defaultBucket || "";
455
+ if (this.defaultBucket) validateBucket(this.defaultBucket);
456
+ this.listPageSize = config.listPageSize || 100;
457
+ this.maxResponseBytes = config.maxResponseBytes || 4194304;
458
+ this.maxTextBytes = config.maxTextBytes || 1048576;
459
+ this.maxUploadBytes = config.maxUploadBytes || 1048576;
460
+ if (!Number.isSafeInteger(this.listPageSize) || this.listPageSize < 1 || this.listPageSize > 1e3) throw new TypeError("S3 listPageSize must be from 1 to 1000");
461
+ if (![this.maxResponseBytes, this.maxTextBytes].every((value) => Number.isSafeInteger(value) && value > 0)) throw new TypeError("S3 response limits must be positive");
462
+ if (!Number.isSafeInteger(this.maxUploadBytes) || this.maxUploadBytes < 1 || this.maxUploadBytes > 5242880) throw new TypeError("S3 maxUploadBytes must be from 1 to 5242880");
463
+ this.credentials = credentials;
464
+ this.send = options.send ?? sendProviderRequest;
465
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
466
+ }
467
+ /** Bind the bucket listing query. */
468
+ listObjects() {
469
+ return new ListObjectsOperation(this);
470
+ }
471
+ /** Bind the metadata query. */
472
+ headObject() {
473
+ return new HeadObjectOperation(this);
474
+ }
475
+ /** Bind the text query. */
476
+ getObjectText() {
477
+ return new GetObjectTextOperation(this);
478
+ }
479
+ /** Bind the object write mutation. */
480
+ putObject() {
481
+ return new PutObjectOperation(this);
482
+ }
483
+ /** Resolve current credentials once per Invoke without exposing secret-bearing errors. */
484
+ async startSession(call) {
485
+ try {
486
+ const credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
487
+ const accessKeyId = credentials.accessKeyId.reveal();
488
+ const secretAccessKey = credentials.secretAccessKey.reveal();
489
+ const sessionToken = credentials.sessionToken?.reveal() ?? "";
490
+ if (!isHeaderSafeCredential(accessKeyId) || accessKeyId.length > 128 || /[/,=]/.test(accessKeyId)) return void 0;
491
+ if (!secretAccessKey || Buffer.byteLength(secretAccessKey) > 256 || /\p{Cc}/u.test(secretAccessKey)) return void 0;
492
+ if (sessionToken && (!isHeaderSafeCredential(sessionToken) || sessionToken.length > 4096)) return void 0;
493
+ return { accessKeyId, secretAccessKey, sessionToken };
494
+ } catch {
495
+ return void 0;
496
+ }
497
+ }
498
+ /** Resolve and validate an input bucket. */
499
+ bucket(inputBucket) {
500
+ const bucket = inputBucket || this.defaultBucket;
501
+ if (!bucket) throw new TypeError("bucket is required because the connection has no defaultBucket");
502
+ validateBucket(bucket);
503
+ if (this.addressingStyle === "virtualHosted" && bucket.includes(".") && this.endpoint.protocol === "https:") throw new TypeError("a bucket name with a dot cannot use virtualHosted addressing over HTTPS");
504
+ return bucket;
505
+ }
506
+ /** Send a SigV4 request once; Dex owns operation retries. */
507
+ async exchange(call, session, request) {
508
+ const target = this.requestURL(request);
509
+ const now = this.now();
510
+ const amzDate = now.toISOString().replace(/[-:]|\.\d{3}/g, "");
511
+ const body = request.body;
512
+ const payloadHash = body ? createHash2("sha256").update(body).digest("hex") : emptyHash;
513
+ const headers = { ...request.headers, "x-amz-content-sha256": payloadHash, "x-amz-date": amzDate };
514
+ if (body) headers["content-length"] = String(body.length);
515
+ if (session.sessionToken) headers["x-amz-security-token"] = session.sessionToken;
516
+ const signed = { host: target.host.toLowerCase() };
517
+ for (const [name, value] of Object.entries(headers)) signed[name.toLowerCase()] = value.trim().replace(/\s+/g, " ");
518
+ const names = Object.keys(signed).sort();
519
+ const canonicalHeaders = names.map((name) => `${name}:${signed[name]}
520
+ `).join("");
521
+ const canonicalRequest = [request.method, target.pathname, target.search.slice(1), canonicalHeaders, names.join(";"), payloadHash].join("\n");
522
+ const date = amzDate.slice(0, 8);
523
+ const scope = `${date}/${this.region}/s3/aws4_request`;
524
+ const stringToSign = `AWS4-HMAC-SHA256
525
+ ${amzDate}
526
+ ${scope}
527
+ ${createHash2("sha256").update(canonicalRequest).digest("hex")}`;
528
+ const signingKey = hmac(hmac(hmac(hmac(`AWS4${session.secretAccessKey}`, date), this.region), "s3"), "aws4_request");
529
+ headers.authorization = `AWS4-HMAC-SHA256 Credential=${session.accessKeyId}/${scope}, SignedHeaders=${names.join(";")}, Signature=${createHmac("sha256", signingKey).update(stringToSign).digest("hex")}`;
530
+ headers["accept-encoding"] = "identity";
531
+ const remaining = call.context.deadline ? call.context.deadline.getTime() - Date.now() : 12e3;
532
+ const timeoutMs = Math.max(1, Math.min(12e3, remaining));
533
+ try {
534
+ const response = await this.send({ url: target.toString(), method: request.method, headers, ...body ? { body } : {}, maxResponseBytes: request.maxBytes ?? this.maxResponseBytes, addressPolicy: this.isAmazonEndpoint ? "publicHTTPS" : "privateNetworkHTTP", timeoutMs, signal: call.context.cancellationSignal });
535
+ return { ...response, isTooLarge: false };
536
+ } catch (error) {
537
+ if (error instanceof BodyTooLargeError && error.status !== void 0) return { status: error.status, headers: error.headers ?? {}, body: new Uint8Array(), isTooLarge: true };
538
+ throw error;
539
+ }
540
+ }
541
+ /** Make a safe receipt from provider correlation metadata. */
542
+ receipt(_call, response, bucket, key) {
543
+ const requestId = header(response, "x-amz-request-id");
544
+ return { providerObjectId: key === void 0 ? bucket : `${bucket}/${key}`, ...requestId && /^[A-Za-z0-9+/=._-]{1,128}$/.test(requestId) ? { providerRequestId: requestId } : {}, observedAt: this.now().toISOString() };
545
+ }
546
+ /** Return the clock used for retry headers. */
547
+ currentTime() {
548
+ return this.now();
549
+ }
550
+ requestURL(request) {
551
+ const target = new URL(this.endpoint);
552
+ const basePath = target.pathname.replace(/\/$/, "");
553
+ const usePath = this.addressingStyle === "path" || this.addressingStyle === "auto" && (!this.isAmazonEndpoint || request.bucket.includes("."));
554
+ if (usePath) target.pathname = escapeS3Path(`${basePath}/${request.bucket}${request.key === void 0 ? "" : `/${request.key}`}`);
555
+ else {
556
+ target.hostname = `${request.bucket}.${target.hostname}`;
557
+ target.pathname = escapeS3Path(`${basePath}/${request.key ?? ""}`);
558
+ }
559
+ const query = Object.entries(request.query ?? {}).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
560
+ target.search = query.map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`).join("&");
561
+ return target;
562
+ }
563
+ };
564
+ function header(response, name) {
565
+ const value = response.headers[name.toLowerCase()];
566
+ return Array.isArray(value) ? value.join(",") : value ?? "";
567
+ }
568
+ function retryAfter(response, now) {
569
+ return parseRetryAfter(header(response, "retry-after"), now);
570
+ }
571
+ function validateBucket(bucket) {
572
+ if (!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(bucket) || bucket.includes("..") || /^\d+\.\d+\.\d+\.\d+$/.test(bucket)) throw new TypeError("bucket must be a 3 to 63 character S3 bucket name");
573
+ }
574
+ function validateKey(value, field = "key", isPrefix = false) {
575
+ if (!isPrefix && !value) throw new TypeError("key must be 1 to 1024 bytes");
576
+ if (Buffer.byteLength(value) > 1024) throw new TypeError(`${field} must be at most 1024 bytes`);
577
+ if (/\p{Cc}/u.test(value)) throw new TypeError(`${field} must be UTF-8 text without control characters`);
578
+ if (!isPrefix && value.split("/").some((segment) => segment === "." || segment === "..")) throw new TypeError("key cannot contain . or .. path segments");
579
+ }
580
+ function containsCredential(value, session, includeAccessKey = false) {
581
+ return [session.secretAccessKey, session.sessionToken, ...includeAccessKey ? [session.accessKeyId] : []].some((secret) => secret.length > 0 && value.includes(secret));
582
+ }
583
+ function safeHeader(response, name, session) {
584
+ const value = header(response, name);
585
+ return value.length <= 2048 && !containsCredential(value, session) ? value : "";
586
+ }
587
+ function hmac(key, value) {
588
+ return createHmac("sha256", key).update(value).digest();
589
+ }
590
+ function escapeS3Path(path) {
591
+ return Array.from(encoder.encode(path)).map((byte) => byte >= 65 && byte <= 90 || byte >= 97 && byte <= 122 || byte >= 48 && byte <= 57 || [45, 46, 95, 126, 47].includes(byte) ? String.fromCharCode(byte) : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`).join("");
592
+ }
593
+
594
+ // src/connection.ts
595
+ import { SecretString } from "@superdurable/connectors-sdk";
596
+ import { z } from "zod";
597
+ function newProjectConnection(project, connectionName, options = {}) {
598
+ if (!project) throw new TypeError("loaded project is required");
599
+ const selected = project.configuration.connections.find((entry) => entry.connectorId === "amazon-s3" && entry.connectionName === connectionName);
600
+ if (!selected || selected.provider !== "amazon-s3") throw new TypeError("S3 project connection is not configured");
601
+ const settings = ConfigSchema.parse(selected.configuration);
602
+ const config = Object.fromEntries(Object.entries(settings).filter(([, value]) => value !== void 0));
603
+ const credentials = {
604
+ async resolve(_call, signal) {
605
+ const fields = await project.resolveCredential("amazon-s3", connectionName, signal);
606
+ const decoded = z.object({ access_key_id: z.string(), secret_access_key: z.string(), session_token: z.string().optional() }).parse(fields);
607
+ return { accessKeyId: new SecretString(decoded.access_key_id), secretAccessKey: new SecretString(decoded.secret_access_key), ...decoded.session_token ? { sessionToken: new SecretString(decoded.session_token) } : {} };
608
+ }
609
+ };
610
+ return newConnection(new S3Client(config, credentials, options), { provider: "amazon-s3", name: connectionName });
611
+ }
612
+
613
+ // src/generated/steps.ts
614
+ import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
615
+ function newListObjectsStep(configuration) {
616
+ const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
617
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
618
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listObjects(), connection: connection.reference, branches: [
619
+ goToBranch("found", found),
620
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
621
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
622
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
623
+ ...defect ? [goToBranch("defect", defect)] : []
624
+ ] });
625
+ }
626
+ function newHeadObjectStep(configuration) {
627
+ const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
628
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
629
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.headObject(), connection: connection.reference, branches: [
630
+ goToBranch("found", found),
631
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
632
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
633
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
634
+ ...defect ? [goToBranch("defect", defect)] : []
635
+ ] });
636
+ }
637
+ function newGetObjectTextStep(configuration) {
638
+ const { connection, connectionName, read, notFound, unsupportedContent, tooLarge, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
639
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
640
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getObjectText(), connection: connection.reference, branches: [
641
+ goToBranch("read", read),
642
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
643
+ ...unsupportedContent ? [goToBranch("unsupportedContent", unsupportedContent)] : [],
644
+ ...tooLarge ? [goToBranch("tooLarge", tooLarge)] : [],
645
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
646
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
647
+ ...defect ? [goToBranch("defect", defect)] : []
648
+ ] });
649
+ }
650
+ function newPutObjectStep(configuration) {
651
+ const { connection, connectionName, stored, alreadyExists, providerRejected, defect, ...stepConfiguration } = configuration;
652
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
653
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.putObject(), connection: connection.reference, branches: [
654
+ goToBranch("stored", stored),
655
+ ...alreadyExists ? [goToBranch("alreadyExists", alreadyExists)] : [],
656
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
657
+ ...defect ? [goToBranch("defect", defect)] : []
658
+ ] });
659
+ }
660
+ export {
661
+ ConfigSchema,
662
+ Connection,
663
+ ConnectionNameProvider,
664
+ ConnectorID,
665
+ GetObjectTextBranch,
666
+ GetObjectTextBranchDefect,
667
+ GetObjectTextBranchInvalidResponse,
668
+ GetObjectTextBranchNotFound,
669
+ GetObjectTextBranchProviderRejected,
670
+ GetObjectTextBranchRead,
671
+ GetObjectTextBranchTooLarge,
672
+ GetObjectTextBranchUnsupportedContent,
673
+ GetObjectTextDefinition,
674
+ GetObjectTextInputSchema,
675
+ GetObjectTextMetadata,
676
+ GetObjectTextOperation,
677
+ HeadObjectBranch,
678
+ HeadObjectBranchDefect,
679
+ HeadObjectBranchFound,
680
+ HeadObjectBranchInvalidResponse,
681
+ HeadObjectBranchNotFound,
682
+ HeadObjectBranchProviderRejected,
683
+ HeadObjectDefinition,
684
+ HeadObjectInputSchema,
685
+ HeadObjectMetadata,
686
+ HeadObjectOperation,
687
+ ListObjectsBranch,
688
+ ListObjectsBranchDefect,
689
+ ListObjectsBranchFound,
690
+ ListObjectsBranchInvalidResponse,
691
+ ListObjectsBranchNotFound,
692
+ ListObjectsBranchProviderRejected,
693
+ ListObjectsDefinition,
694
+ ListObjectsInputSchema,
695
+ ListObjectsMetadata,
696
+ ListObjectsOperation,
697
+ ListObjectsOutputSchema,
698
+ ObjectMetadataSchema,
699
+ ObjectSummarySchema,
700
+ ObjectTextSchema,
701
+ ProviderID,
702
+ PutObjectBranch,
703
+ PutObjectBranchAlreadyExists,
704
+ PutObjectBranchDefect,
705
+ PutObjectBranchProviderRejected,
706
+ PutObjectBranchStored,
707
+ PutObjectDefinition,
708
+ PutObjectInputSchema,
709
+ PutObjectMetadata,
710
+ PutObjectOperation,
711
+ S3Client,
712
+ StoredObjectSchema,
713
+ containsCredential,
714
+ header,
715
+ newConnection,
716
+ newConnectionWithOperations,
717
+ newGetObjectTextStep,
718
+ newHeadObjectStep,
719
+ newListObjectsStep,
720
+ newProjectConnection,
721
+ newPutObjectStep,
722
+ retryAfter,
723
+ safeHeader,
724
+ validateBucket,
725
+ validateKey
726
+ };