@superdurable/connector-amazon-sqs 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,641 @@
1
+ import {
2
+ ChangeMessageVisibilityBranch,
3
+ ChangeMessageVisibilityBranchChanged,
4
+ ChangeMessageVisibilityBranchDefect,
5
+ ChangeMessageVisibilityBranchProviderRejected,
6
+ ChangeMessageVisibilityBranchReceiptHandleInvalid,
7
+ ChangeMessageVisibilityDefinition,
8
+ ChangeMessageVisibilityInputSchema,
9
+ ChangeMessageVisibilityMetadata,
10
+ ChangedMessageVisibilitySchema,
11
+ ConfigSchema,
12
+ Connection,
13
+ ConnectorID,
14
+ DeleteMessageBranch,
15
+ DeleteMessageBranchDefect,
16
+ DeleteMessageBranchDeleted,
17
+ DeleteMessageBranchProviderRejected,
18
+ DeleteMessageBranchReceiptHandleInvalid,
19
+ DeleteMessageDefinition,
20
+ DeleteMessageInputSchema,
21
+ DeleteMessageMetadata,
22
+ DeletedMessageSchema,
23
+ MessageAttributeValueSchema,
24
+ MessageSchema,
25
+ ProviderID,
26
+ ReceiveMessagesBranch,
27
+ ReceiveMessagesBranchDefect,
28
+ ReceiveMessagesBranchEmpty,
29
+ ReceiveMessagesBranchInvalidResponse,
30
+ ReceiveMessagesBranchProviderRejected,
31
+ ReceiveMessagesBranchReceived,
32
+ ReceiveMessagesDefinition,
33
+ ReceiveMessagesInputSchema,
34
+ ReceiveMessagesMetadata,
35
+ ReceivedMessagesSchema,
36
+ newConnection,
37
+ newConnectionWithOperations
38
+ } from "./chunk-JUNMI7YJ.js";
39
+
40
+ // src/generated/steps.ts
41
+ import { goToBranch, newMutationStep } from "@superdurable/connectors-sdk";
42
+ function newReceiveMessagesStep(configuration) {
43
+ const { connection, connectionName, received, empty, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
44
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
45
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.receiveMessages(), connection: connection.reference, branches: [
46
+ goToBranch("received", received),
47
+ ...empty ? [goToBranch("empty", empty)] : [],
48
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
49
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
50
+ ...defect2 ? [goToBranch("defect", defect2)] : []
51
+ ] });
52
+ }
53
+ function newDeleteMessageStep(configuration) {
54
+ const { connection, connectionName, deleted, receiptHandleInvalid, providerRejected, defect: defect2, ...stepConfiguration } = configuration;
55
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
56
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.deleteMessage(), connection: connection.reference, branches: [
57
+ goToBranch("deleted", deleted),
58
+ ...receiptHandleInvalid ? [goToBranch("receiptHandleInvalid", receiptHandleInvalid)] : [],
59
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
60
+ ...defect2 ? [goToBranch("defect", defect2)] : []
61
+ ] });
62
+ }
63
+ function newChangeMessageVisibilityStep(configuration) {
64
+ const { connection, connectionName, changed, receiptHandleInvalid, providerRejected, defect: defect2, ...stepConfiguration } = configuration;
65
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
66
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.changeMessageVisibility(), connection: connection.reference, branches: [
67
+ goToBranch("changed", changed),
68
+ ...receiptHandleInvalid ? [goToBranch("receiptHandleInvalid", receiptHandleInvalid)] : [],
69
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
70
+ ...defect2 ? [goToBranch("defect", defect2)] : []
71
+ ] });
72
+ }
73
+
74
+ // src/client.ts
75
+ import { createHash as createHash2, createHmac } from "crypto";
76
+ import { BodyTooLargeError, parseRetryAfter, sendProviderRequest } from "@superdurable/connectors-sdk/providerhttp";
77
+
78
+ // src/operations.ts
79
+ import { createHash } from "crypto";
80
+ import { newMutationBranch, newMutationRetry, zeroReceipt } from "@superdurable/connectors-sdk";
81
+ var provider = "amazon-sqs";
82
+ var printable = /^[\x21-\x7e]+$/;
83
+ var messageAttributeName = /^[A-Za-z0-9_.-]{1,256}$/;
84
+ var zeroReceived = { queueUrl: "" };
85
+ var zeroDeleted = { queueUrl: "" };
86
+ var zeroChanged = { queueUrl: "", visibilityTimeoutSeconds: 0, visibleAfter: "0001-01-01T00:00:00Z" };
87
+ function failure(operation, kind, message) {
88
+ return { provider, operation, kind, message };
89
+ }
90
+ function defect(operation, output, message) {
91
+ return newMutationBranch("defect", output, zeroReceipt(), failure(operation, "VALIDATION", message));
92
+ }
93
+ function credentialsDefect(operation, output) {
94
+ return newMutationBranch("defect", output, zeroReceipt(), failure(operation, "AUTHENTICATION", "SQS connection credentials are unavailable; save an access key ID and secret access key for the connection"));
95
+ }
96
+ function transportRetry(operation, subject) {
97
+ return newMutationRetry(failure(operation, "TRANSPORT", `SQS could not be reached or did not finish the ${subject}`));
98
+ }
99
+ function validReceiptHandle(handle) {
100
+ return !!handle && Buffer.byteLength(handle) <= 4096 && printable.test(handle);
101
+ }
102
+ function validMessageId(id) {
103
+ return Buffer.byteLength(id) <= 128 && (!id || printable.test(id));
104
+ }
105
+ function acknowledgementInput(client, queueUrl, handle, messageId) {
106
+ const queue = client.resolveQueue(queueUrl);
107
+ if (!validReceiptHandle(handle)) throw new TypeError("receiptHandle must be the handle receiveMessages returned for the message");
108
+ if (!validMessageId(messageId ?? "")) throw new TypeError("messageId must be blank or the message ID receiveMessages returned");
109
+ return queue;
110
+ }
111
+ function classifyAcknowledgement(call, client, response, credentials, operation, subject, output, objectId) {
112
+ if (response.status >= 200 && response.status < 300) return void 0;
113
+ const classified = classifyResponse(operation, subject, response, credentials, client.now());
114
+ if (classified.branch === "retry") return newMutationRetry(classified.failure, classified.retryAfterMs);
115
+ return newMutationBranch(classified.branch, output, client.receipt(call, response, objectId), classified.failure);
116
+ }
117
+ var ReceiveMessagesOperation = class {
118
+ /** Bind one SQS client. */
119
+ constructor(client) {
120
+ this.client = client;
121
+ }
122
+ client;
123
+ /** Return the manifest operation identity. */
124
+ definition() {
125
+ return ReceiveMessagesDefinition;
126
+ }
127
+ /** Reuse the call ID for FIFO receive deduplication. */
128
+ idempotencyKey(callId) {
129
+ return callId;
130
+ }
131
+ /** Validate, sign, send, and classify one receive attempt. */
132
+ async invoke(call, input) {
133
+ const operation = "receiveMessages";
134
+ if (!ReceiveMessagesInputSchema.safeParse(input).success) return defect(operation, zeroReceived, "SQS receive input is invalid");
135
+ let queue;
136
+ try {
137
+ queue = this.client.resolveQueue(input.queueUrl);
138
+ } catch (error) {
139
+ return defect(operation, zeroReceived, error.message);
140
+ }
141
+ const max = input.maxMessages || this.client.maxMessagesPerReceive;
142
+ if (!Number.isSafeInteger(max) || max < 1 || max > 10) return defect(operation, zeroReceived, "maxMessages must be from 1 to 10, or zero for the connection's maxMessagesPerReceive");
143
+ const wait = input.waitTimeSeconds ?? this.client.receiveWaitSeconds;
144
+ if (!Number.isSafeInteger(wait) || wait < 0 || wait > 20) return defect(operation, zeroReceived, "waitTimeSeconds must be from 0 to 20");
145
+ const visibility = input.visibilityTimeoutSeconds;
146
+ if (visibility !== void 0 && (!Number.isSafeInteger(visibility) || visibility < 0 || visibility > 43200)) return defect(operation, zeroReceived, "visibilityTimeoutSeconds must be from 0 to 43200");
147
+ const attemptId = call.idempotencyKey ?? "";
148
+ if (queue.isFIFO && (!attemptId || Buffer.byteLength(attemptId) > 128 || !printable.test(attemptId))) return defect(operation, zeroReceived, "idempotency key is missing or not a valid ReceiveRequestAttemptId");
149
+ const credentials = await this.client.resolveCredentials(call);
150
+ if (!credentials) return credentialsDefect(operation, zeroReceived);
151
+ const batch = { queueUrl: queue.url, ...queue.isFIFO ? { isFifo: true } : {} };
152
+ const attributes = receiveSystemAttributes();
153
+ const request = {
154
+ QueueUrl: queue.url,
155
+ MaxNumberOfMessages: max,
156
+ WaitTimeSeconds: wait,
157
+ ...visibility !== void 0 ? { VisibilityTimeout: visibility } : {},
158
+ AttributeNames: attributes,
159
+ MessageSystemAttributeNames: attributes,
160
+ MessageAttributeNames: ["All"],
161
+ ...queue.isFIFO ? { ReceiveRequestAttemptId: attemptId } : {}
162
+ };
163
+ let response;
164
+ try {
165
+ response = await this.client.exchange(call, credentials, "ReceiveMessage", request);
166
+ } catch {
167
+ return transportRetry(operation, "receive");
168
+ }
169
+ if (response.status < 200 || response.status >= 300) {
170
+ const classified = classifyResponse(operation, "receive", response, credentials, this.client.now());
171
+ if (classified.branch === "retry") return newMutationRetry(classified.failure, classified.retryAfterMs);
172
+ return newMutationBranch("providerRejected", batch, this.client.receipt(call, response, queue.url), classified.failure);
173
+ }
174
+ const receipt = this.client.receipt(call, response, queue.url);
175
+ if (response.isTooLarge) return newMutationBranch("invalidResponse", batch, receipt, failure(operation, "RESPONSE_TOO_LARGE", "SQS receive batch exceeds maxResponseBytes; lower maxMessages"));
176
+ const body = Buffer.from(response.body).toString("utf8");
177
+ if ([credentials.secretAccessKey.reveal(), credentials.sessionToken?.reveal()].some((secret) => secret && body.includes(secret))) return newMutationBranch("invalidResponse", batch, receipt, failure(operation, "PROTOCOL", "SQS receive batch contains the connection's credentials"));
178
+ try {
179
+ const messages = decodeMessages(body, max);
180
+ if (messages.length) batch.messages = messages;
181
+ return newMutationBranch(messages.length ? "received" : "empty", batch, receipt);
182
+ } catch (error) {
183
+ return newMutationBranch("invalidResponse", batch, receipt, failure(operation, "PROTOCOL", `SQS returned an invalid receive batch: ${error.message}`));
184
+ }
185
+ }
186
+ };
187
+ var DeleteMessageOperation = class {
188
+ /** Bind one SQS client. */
189
+ constructor(client) {
190
+ this.client = client;
191
+ }
192
+ client;
193
+ /** Return the manifest operation identity. */
194
+ definition() {
195
+ return DeleteMessageDefinition;
196
+ }
197
+ /** Stable mutation key for Dex retries. */
198
+ idempotencyKey(callId) {
199
+ return callId;
200
+ }
201
+ /** Validate, sign, send, and classify one delete attempt. */
202
+ async invoke(call, input) {
203
+ const operation = "deleteMessage";
204
+ if (!DeleteMessageInputSchema.safeParse(input).success) return defect(operation, zeroDeleted, "SQS delete input is invalid");
205
+ let queue;
206
+ try {
207
+ queue = acknowledgementInput(this.client, input.queueUrl, input.receiptHandle, input.messageId);
208
+ } catch (error2) {
209
+ return defect(operation, zeroDeleted, error2.message);
210
+ }
211
+ const credentials = await this.client.resolveCredentials(call);
212
+ if (!credentials) return credentialsDefect(operation, zeroDeleted);
213
+ const deleted = { queueUrl: queue.url, ...input.messageId ? { messageId: input.messageId } : {} };
214
+ const objectId = input.messageId ? `${queue.url}#${input.messageId}` : queue.url;
215
+ let response;
216
+ try {
217
+ response = await this.client.exchange(call, credentials, "DeleteMessage", { QueueUrl: queue.url, ReceiptHandle: input.receiptHandle });
218
+ } catch {
219
+ return transportRetry(operation, "message deletion");
220
+ }
221
+ const error = classifyAcknowledgement(call, this.client, response, credentials, operation, "message deletion", deleted, objectId);
222
+ return error ?? newMutationBranch("deleted", deleted, this.client.receipt(call, response, objectId));
223
+ }
224
+ };
225
+ var ChangeMessageVisibilityOperation = class {
226
+ /** Bind one SQS client. */
227
+ constructor(client) {
228
+ this.client = client;
229
+ }
230
+ client;
231
+ /** Return the manifest operation identity. */
232
+ definition() {
233
+ return ChangeMessageVisibilityDefinition;
234
+ }
235
+ /** Stable mutation key for Dex retries. */
236
+ idempotencyKey(callId) {
237
+ return callId;
238
+ }
239
+ /** Validate, sign, send, and classify one visibility attempt. */
240
+ async invoke(call, input) {
241
+ const operation = "changeMessageVisibility";
242
+ if (!ChangeMessageVisibilityInputSchema.safeParse(input).success) return defect(operation, zeroChanged, "SQS visibility input is invalid");
243
+ let queue;
244
+ try {
245
+ queue = acknowledgementInput(this.client, input.queueUrl, input.receiptHandle, input.messageId);
246
+ } catch (error) {
247
+ return defect(operation, zeroChanged, error.message);
248
+ }
249
+ if (!Number.isSafeInteger(input.visibilityTimeoutSeconds) || input.visibilityTimeoutSeconds < 0 || input.visibilityTimeoutSeconds > 43200) return defect(operation, zeroChanged, "visibilityTimeoutSeconds must be from 0 to 43200");
250
+ const credentials = await this.client.resolveCredentials(call);
251
+ if (!credentials) return credentialsDefect(operation, zeroChanged);
252
+ const changed = { queueUrl: queue.url, ...input.messageId ? { messageId: input.messageId } : {}, visibilityTimeoutSeconds: input.visibilityTimeoutSeconds, visibleAfter: "0001-01-01T00:00:00Z" };
253
+ const objectId = input.messageId ? `${queue.url}#${input.messageId}` : queue.url;
254
+ let response;
255
+ try {
256
+ response = await this.client.exchange(call, credentials, "ChangeMessageVisibility", { QueueUrl: queue.url, ReceiptHandle: input.receiptHandle, VisibilityTimeout: input.visibilityTimeoutSeconds });
257
+ } catch {
258
+ return transportRetry(operation, "visibility change");
259
+ }
260
+ const classified = classifyAcknowledgement(call, this.client, response, credentials, operation, "visibility change", changed, objectId);
261
+ if (classified) return classified;
262
+ const receipt = this.client.receipt(call, response, objectId);
263
+ changed.visibleAfter = new Date(Date.parse(receipt.observedAt) + input.visibilityTimeoutSeconds * 1e3).toISOString().replace(/\.000Z$/, "Z");
264
+ return newMutationBranch("changed", changed, receipt);
265
+ }
266
+ };
267
+ function decodeMessages(body, max) {
268
+ let parsed;
269
+ try {
270
+ parsed = JSON.parse(body);
271
+ } catch {
272
+ throw new TypeError("the document is not a ReceiveMessage response");
273
+ }
274
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new TypeError("the document is not a ReceiveMessage response");
275
+ const raw = parsed.Messages;
276
+ if (raw !== void 0 && raw !== null && !Array.isArray(raw)) throw new TypeError("the document is not a ReceiveMessage response");
277
+ const entries = raw ?? [];
278
+ if (entries.length > max) throw new TypeError("the batch holds more messages than requested");
279
+ return entries.map(decodeMessage);
280
+ }
281
+ function decodeMessage(value) {
282
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("a message ID is missing or not printable");
283
+ const item = value;
284
+ const id = item.MessageId;
285
+ const handle = item.ReceiptHandle;
286
+ const body = item.Body;
287
+ if (typeof id !== "string" || !validMessageId(id) || !id) throw new TypeError("a message ID is missing or not printable");
288
+ if (typeof handle !== "string" || !validReceiptHandle(handle)) throw new TypeError("a receipt handle is missing or not printable");
289
+ if (typeof body !== "string") throw new TypeError("a message body is missing or not UTF-8");
290
+ const digest = createHash("md5").update(body).digest("hex");
291
+ if (item.MD5OfBody !== digest) throw new TypeError("a message body does not match its MD5 digest");
292
+ const attributes = item.Attributes && typeof item.Attributes === "object" ? item.Attributes : {};
293
+ const count = Number(attributes.ApproximateReceiveCount);
294
+ if (!Number.isSafeInteger(count) || count < 1) throw new TypeError("a receive count is not a positive integer");
295
+ const timestamp = (name) => {
296
+ const raw = attributes[name];
297
+ if (raw === void 0 || raw === "") return void 0;
298
+ if (typeof raw !== "string" || !/^\d+$/.test(raw) || !Number.isSafeInteger(Number(raw))) throw new TypeError("timestamp is not epoch milliseconds");
299
+ return new Date(Number(raw)).toISOString().replace(/\.000Z$/, "Z");
300
+ };
301
+ const message = {
302
+ messageId: id,
303
+ receiptHandle: handle,
304
+ body,
305
+ md5OfBody: digest,
306
+ receiveCount: count,
307
+ ...timestamp("SentTimestamp") ? { sentAt: timestamp("SentTimestamp") } : {},
308
+ ...timestamp("ApproximateFirstReceiveTimestamp") ? { firstReceivedAt: timestamp("ApproximateFirstReceiveTimestamp") } : {},
309
+ ...typeof attributes.MessageGroupId === "string" && attributes.MessageGroupId ? { messageGroupId: attributes.MessageGroupId } : {},
310
+ ...typeof attributes.MessageDeduplicationId === "string" && attributes.MessageDeduplicationId ? { messageDeduplicationId: attributes.MessageDeduplicationId } : {},
311
+ ...typeof attributes.SequenceNumber === "string" && attributes.SequenceNumber ? { sequenceNumber: attributes.SequenceNumber } : {}
312
+ };
313
+ const rawMessageAttributes = item.MessageAttributes;
314
+ if (rawMessageAttributes && typeof rawMessageAttributes === "object" && !Array.isArray(rawMessageAttributes)) {
315
+ const decoded = {};
316
+ for (const [name, rawValue] of Object.entries(rawMessageAttributes)) {
317
+ const attribute = rawValue;
318
+ if (!messageAttributeName.test(name) || typeof attribute.DataType !== "string" || !attribute.DataType || attribute.StringValue !== void 0 && typeof attribute.StringValue !== "string") throw new TypeError("a message attribute has an invalid name, data type, or value");
319
+ if (attribute.BinaryValue !== void 0 && (typeof attribute.BinaryValue !== "string" || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(attribute.BinaryValue))) throw new TypeError("a message attribute has an invalid name, data type, or value");
320
+ decoded[name] = {
321
+ dataType: attribute.DataType,
322
+ ...attribute.StringValue ? { stringValue: attribute.StringValue } : {},
323
+ ...attribute.BinaryValue ? { binaryValue: attribute.BinaryValue } : {}
324
+ };
325
+ }
326
+ if (Object.keys(decoded).length) message.messageAttributes = decoded;
327
+ }
328
+ return message;
329
+ }
330
+
331
+ // src/client.ts
332
+ var provider2 = "amazon-sqs";
333
+ var regionPattern = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
334
+ var queueNamePattern = /^[A-Za-z0-9_-]{1,80}$/;
335
+ var ownerPattern = /^[A-Za-z0-9_-]{1,64}$/;
336
+ var requestIdPattern = /^[A-Za-z0-9+/=._-]{1,128}$/;
337
+ var errorCodePattern = /^[A-Za-z0-9.]{1,96}$/;
338
+ var systemAttributes = ["ApproximateReceiveCount", "ApproximateFirstReceiveTimestamp", "SentTimestamp", "MessageGroupId", "MessageDeduplicationId", "SequenceNumber"];
339
+ var SQSClient = class {
340
+ /** Validated SQS JSON-protocol endpoint. */
341
+ endpoint;
342
+ /** Region used in every SigV4 credential scope. */
343
+ region;
344
+ /** Queue selected when an operation leaves queueUrl blank. */
345
+ defaultQueueUrl;
346
+ /** Default receive batch limit, from one through ten. */
347
+ maxMessagesPerReceive;
348
+ /** Default receive long-poll duration in seconds. */
349
+ receiveWaitSeconds;
350
+ /** Complete response bound in bytes. */
351
+ maxResponseBytes;
352
+ /** Whether the endpoint was derived from the Region. */
353
+ isAmazonEndpoint;
354
+ /** Clock used for signing and provider receipts. */
355
+ now;
356
+ credentials;
357
+ send;
358
+ /** Validate local settings and retain host-owned credentials. */
359
+ constructor(config, credentials, options = {}) {
360
+ if (!credentials) throw new TypeError("credential provider is required");
361
+ this.region = config.region || "us-east-1";
362
+ if (!regionPattern.test(this.region)) throw new TypeError("SQS region must be a Region code such as eu-west-1");
363
+ this.isAmazonEndpoint = !config.endpoint;
364
+ const suffix = this.region.startsWith("cn-") ? "amazonaws.com.cn" : this.region.startsWith("eusc-de-") ? "amazonaws.eu" : "amazonaws.com";
365
+ if (this.isAmazonEndpoint && !/^(?:(?:us|eu|ap|sa|ca|me|af|il|mx)-[a-z0-9-]+-[0-9]+|us-gov-[a-z0-9-]+-[0-9]+|cn-[a-z0-9-]+-[0-9]+|eusc-de-[a-z0-9-]+-[0-9]+)$/.test(this.region)) throw new TypeError("SQS region is not an Amazon SQS Region; set endpoint for an SQS-compatible server");
366
+ const endpoint = new URL(config.endpoint || `https://sqs.${this.region}.${suffix}`);
367
+ if (!endpoint.hostname || endpoint.username || endpoint.password || endpoint.search || endpoint.hash || !/^\/(?:[A-Za-z0-9._~-]+\/?)*$/.test(endpoint.pathname)) throw new TypeError("SQS endpoint is invalid");
368
+ if (endpoint.protocol !== "https:" && !(endpoint.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(endpoint.hostname))) throw new TypeError("SQS endpoint must use HTTPS or loopback HTTP");
369
+ this.endpoint = endpoint.href;
370
+ this.defaultQueueUrl = config.defaultQueueUrl || "";
371
+ if (this.defaultQueueUrl) this.resolveQueue(this.defaultQueueUrl);
372
+ this.maxMessagesPerReceive = config.maxMessagesPerReceive || 10;
373
+ this.receiveWaitSeconds = config.receiveWaitSeconds || 20;
374
+ this.maxResponseBytes = config.maxResponseBytes || 4194304;
375
+ if (!Number.isSafeInteger(this.maxMessagesPerReceive) || this.maxMessagesPerReceive < 1 || this.maxMessagesPerReceive > 10) throw new TypeError("SQS maxMessagesPerReceive must be from 1 to 10");
376
+ if (!Number.isSafeInteger(this.receiveWaitSeconds) || this.receiveWaitSeconds < 1 || this.receiveWaitSeconds > 20) throw new TypeError("SQS receiveWaitSeconds must be from 1 to 20");
377
+ if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes < 1) throw new TypeError("SQS maxResponseBytes must be positive");
378
+ this.credentials = credentials;
379
+ this.send = options.send ?? sendProviderRequest;
380
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
381
+ }
382
+ /** Bind the receive mutation. */
383
+ receiveMessages() {
384
+ return new ReceiveMessagesOperation(this);
385
+ }
386
+ /** Bind the delete mutation. */
387
+ deleteMessage() {
388
+ return new DeleteMessageOperation(this);
389
+ }
390
+ /** Bind the visibility mutation. */
391
+ changeMessageVisibility() {
392
+ return new ChangeMessageVisibilityOperation(this);
393
+ }
394
+ /** Select the input queue or the connection default and validate its identity. */
395
+ resolveQueue(inputQueueUrl) {
396
+ const queueUrl = inputQueueUrl || this.defaultQueueUrl;
397
+ if (!queueUrl) throw new TypeError("queueUrl is required because the connection has no defaultQueueUrl");
398
+ if (Buffer.byteLength(queueUrl) > 2048) throw new TypeError("queueUrl must be a queue URL");
399
+ let parsed;
400
+ try {
401
+ parsed = new URL(queueUrl);
402
+ } catch {
403
+ throw new TypeError("queueUrl must be a queue URL");
404
+ }
405
+ if (!["https:", "http:"].includes(parsed.protocol) || !parsed.hostname || parsed.username || parsed.password || parsed.search || parsed.hash || parsed.href !== queueUrl) throw new TypeError("queueUrl must be a queue URL");
406
+ const match = /^\/([^/]+)\/([^/]+)$/.exec(parsed.pathname);
407
+ if (!match || !ownerPattern.test(match[1] ?? "")) throw new TypeError("queueUrl must be a queue URL");
408
+ const name = match[2] ?? "";
409
+ const isFIFO = name.endsWith(".fifo");
410
+ if (!queueNamePattern.test(isFIFO ? name.slice(0, -5) : name) || name.length > 80) throw new TypeError("queueUrl must end with a queue name of 1 to 80 letters, digits, hyphens, and underscores, including any .fifo suffix");
411
+ const awsRegion = /^sqs\.([a-z0-9-]+)\.amazonaws\.(?:com|com\.cn|eu)$/.exec(parsed.hostname)?.[1];
412
+ if (this.isAmazonEndpoint && awsRegion && awsRegion !== this.region) throw new TypeError(`queueUrl is in Region ${awsRegion} but the connection signs for ${this.region}; set region to ${awsRegion}`);
413
+ return { url: queueUrl, isFIFO };
414
+ }
415
+ /** Resolve one current access key without retaining it in a result. */
416
+ async resolveCredentials(call) {
417
+ try {
418
+ const credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
419
+ const key = credentials.accessKeyId?.reveal();
420
+ const secret = credentials.secretAccessKey?.reveal();
421
+ const token = credentials.sessionToken?.reveal() ?? "";
422
+ if (!key || !secret || /[^\x21-\x7e]/.test(key + secret + token)) return void 0;
423
+ return credentials;
424
+ } catch {
425
+ return void 0;
426
+ }
427
+ }
428
+ /** Sign and send one JSON-protocol action with AWS Signature Version 4. */
429
+ async exchange(call, credentials, action, requestBody) {
430
+ const body = Buffer.from(JSON.stringify(requestBody));
431
+ const url = new URL(this.endpoint);
432
+ const now = this.now();
433
+ const timestamp = now.toISOString().replace(/[-:]|\.\d{3}/g, "");
434
+ const day = timestamp.slice(0, 8);
435
+ const payloadHash = createHash2("sha256").update(body).digest("hex");
436
+ const host = url.host;
437
+ const canonicalUri = url.pathname;
438
+ const headersForSignature = {
439
+ "content-length": String(body.length),
440
+ "content-type": "application/x-amz-json-1.0",
441
+ host,
442
+ "x-amz-date": timestamp,
443
+ "x-amz-target": `AmazonSQS.${action}`
444
+ };
445
+ const token = credentials.sessionToken?.reveal();
446
+ if (token) headersForSignature["x-amz-security-token"] = token;
447
+ const signedHeaders = Object.keys(headersForSignature).sort().join(";");
448
+ const canonicalHeaders = Object.entries(headersForSignature).sort(([left], [right]) => left.localeCompare(right)).map(([name, value]) => `${name}:${value.trim()}
449
+ `).join("");
450
+ const canonicalRequest = `POST
451
+ ${canonicalUri}
452
+
453
+ ${canonicalHeaders}
454
+ ${signedHeaders}
455
+ ${payloadHash}`;
456
+ const scope = `${day}/${this.region}/sqs/aws4_request`;
457
+ const stringToSign = `AWS4-HMAC-SHA256
458
+ ${timestamp}
459
+ ${scope}
460
+ ${createHash2("sha256").update(canonicalRequest).digest("hex")}`;
461
+ const hmac = (key, value) => createHmac("sha256", key).update(value).digest();
462
+ const signingKey = hmac(hmac(hmac(hmac(`AWS4${credentials.secretAccessKey.reveal()}`, day), this.region), "sqs"), "aws4_request");
463
+ const signature = createHmac("sha256", signingKey).update(stringToSign).digest("hex");
464
+ const headers = {
465
+ "Content-Type": headersForSignature["content-type"],
466
+ "X-Amz-Date": timestamp,
467
+ "X-Amz-Target": headersForSignature["x-amz-target"],
468
+ Authorization: `AWS4-HMAC-SHA256 Credential=${credentials.accessKeyId.reveal()}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`
469
+ };
470
+ if (token) headers["X-Amz-Security-Token"] = token;
471
+ const remaining = call.context.deadline ? call.context.deadline.getTime() - Date.now() : 25e3;
472
+ if (remaining <= 0) throw new TypeError("Dex Step attempt deadline has expired");
473
+ const request = {
474
+ url: this.endpoint,
475
+ method: "POST",
476
+ headers,
477
+ body,
478
+ maxResponseBytes: Math.max(this.maxResponseBytes, 65536),
479
+ timeoutMs: Math.min(25e3, remaining),
480
+ addressPolicy: this.isAmazonEndpoint ? "publicHTTPS" : "privateNetworkHTTP",
481
+ signal: call.context.cancellationSignal
482
+ };
483
+ try {
484
+ const response = await this.send(request);
485
+ return { ...response, isTooLarge: response.body.length > this.maxResponseBytes };
486
+ } catch (error) {
487
+ if (error instanceof BodyTooLargeError && error.status !== void 0 && error.headers !== void 0) {
488
+ return { status: error.status, headers: error.headers, body: new Uint8Array(), isTooLarge: true };
489
+ }
490
+ throw error;
491
+ }
492
+ }
493
+ /** Build one secret-safe receipt. */
494
+ receipt(call, response, objectId) {
495
+ const requestId = header(response.headers, "x-amzn-requestid");
496
+ return {
497
+ callId: call.id,
498
+ provider: provider2,
499
+ observedAt: this.now().toISOString().replace(/\.000Z$/, "Z"),
500
+ ...call.idempotencyKey ? { idempotencyKey: call.idempotencyKey } : {},
501
+ ...objectId ? { providerObjectId: objectId } : {},
502
+ ...requestIdPattern.test(requestId) ? { providerRequestId: requestId } : {}
503
+ };
504
+ }
505
+ };
506
+ function receiveSystemAttributes() {
507
+ return [...systemAttributes];
508
+ }
509
+ function header(headers, name) {
510
+ const value = headers[name.toLowerCase()];
511
+ return Array.isArray(value) ? value[0] ?? "" : value ?? "";
512
+ }
513
+ function classifyResponse(operation, subject, response, credentials, now) {
514
+ let code = header(response.headers, "x-amzn-query-error").split(";")[0] ?? "";
515
+ let message = "";
516
+ try {
517
+ const parsed = JSON.parse(Buffer.from(response.body.slice(0, 65536)).toString("utf8"));
518
+ if (typeof parsed.__type === "string") code = parsed.__type.split("#").pop()?.split(":")[0] ?? "";
519
+ if (typeof parsed.message === "string") message = parsed.message;
520
+ } catch {
521
+ }
522
+ if (!errorCodePattern.test(code) || [credentials.secretAccessKey.reveal(), credentials.sessionToken?.reveal()].some((secret) => secret && code.includes(secret))) code = "";
523
+ const status = response.status;
524
+ const withStatus = (summary) => `${summary} with HTTP ${status}${code ? ` ${code}` : ""}`;
525
+ let branch = "providerRejected";
526
+ let kind = "PROVIDER_REJECTION";
527
+ let description = withStatus(`SQS rejected the ${subject}`);
528
+ if (status === 429 || ["RequestThrottled", "ThrottlingException", "Throttling", "KmsThrottled", "AWS.SimpleQueueService.RequestThrottled"].includes(code)) {
529
+ branch = "retry";
530
+ kind = "RATE_LIMIT";
531
+ description = `SQS throttled the ${subject}`;
532
+ } else if (code === "RequestTimeout" || status === 408) {
533
+ branch = "retry";
534
+ kind = "TRANSPORT";
535
+ description = `SQS timed out the ${subject}`;
536
+ } else if (status >= 500 && status !== 501) {
537
+ branch = "retry";
538
+ kind = "AVAILABILITY";
539
+ description = withStatus(`SQS is temporarily unable to serve the ${subject}`);
540
+ } else if (["ReceiptHandleIsInvalid", "InvalidIdFormat", "MessageNotInflight", "AWS.SimpleQueueService.MessageNotInflight"].includes(code) || ["InvalidParameterValue", "InvalidParameterValueException"].includes(code) && /receipt ?handle/i.test(message)) {
541
+ branch = "receiptHandleInvalid";
542
+ kind = "NOT_FOUND";
543
+ description = `${withStatus(`SQS no longer accepts the receipt handle for the ${subject}`)}; the message may be delivered again`;
544
+ } else if (["QueueDoesNotExist", "AWS.SimpleQueueService.NonExistentQueue"].includes(code)) {
545
+ kind = "NOT_FOUND";
546
+ description = `${withStatus(`SQS rejected the ${subject}`)} because the queue does not exist; check queueUrl and region`;
547
+ } else if (["OverLimit", "AWS.SimpleQueueService.OverLimit"].includes(code)) {
548
+ description = `${withStatus(`SQS rejected the ${subject}`)} because the queue holds too many in-flight messages; delete or release received messages`;
549
+ } else if (["RequestTimeTooSkewed", "SignatureExpired"].includes(code)) {
550
+ kind = "AUTHENTICATION";
551
+ description = `SQS rejected the ${subject} because the Worker clock differs from AWS by more than 5 minutes`;
552
+ } else if (["InvalidClientTokenId", "UnrecognizedClientException", "SignatureDoesNotMatch", "IncompleteSignature", "ExpiredToken", "InvalidSecurity", "MissingAuthenticationToken", "InvalidAccessKeyId", "AWS.SimpleQueueService.InvalidSecurity"].includes(code) || status === 401) {
553
+ kind = "AUTHENTICATION";
554
+ description = `${withStatus(`SQS rejected the connection credentials for the ${subject}`)}; replace the access key or session token`;
555
+ } else if (["AccessDenied", "AccessDeniedException", "KmsAccessDenied", "KmsDisabled", "KmsInvalidState", "KmsNotFound", "KmsOptInRequired", "KmsInvalidKeyUsage"].includes(code) || status === 403) {
556
+ kind = "AUTHORIZATION";
557
+ description = withStatus(`SQS denied the ${subject}`);
558
+ }
559
+ const failure2 = { provider: provider2, operation, kind, message: description };
560
+ return { branch, failure: failure2, retryAfterMs: branch === "retry" ? parseRetryAfter(header(response.headers, "retry-after"), now) : 0 };
561
+ }
562
+
563
+ // src/connection.ts
564
+ import { SecretString } from "@superdurable/connectors-sdk";
565
+ import { z } from "zod";
566
+ function newProjectConnection(project, connectionName, options = {}) {
567
+ if (!project) throw new TypeError("SQS connection requires a loaded project");
568
+ const selected = project.configuration.connections.find((entry) => entry.connectorId === "amazon-sqs" && entry.connectionName === connectionName);
569
+ if (!selected || selected.provider !== "amazon-sqs") throw new TypeError("SQS project connection is not configured");
570
+ const config = z.object({
571
+ region: z.string().optional(),
572
+ endpoint: z.string().optional(),
573
+ defaultQueueUrl: z.string().optional(),
574
+ maxMessagesPerReceive: z.number().int().optional(),
575
+ receiveWaitSeconds: z.number().int().optional(),
576
+ maxResponseBytes: z.number().int().optional()
577
+ }).parse(selected.configuration);
578
+ const credentials = { async resolve(_call, signal) {
579
+ const fields = await project.resolveCredential("amazon-sqs", connectionName, signal);
580
+ const values = z.object({ access_key_id: z.string(), secret_access_key: z.string(), session_token: z.string().optional() }).parse(fields);
581
+ return {
582
+ accessKeyId: new SecretString(values.access_key_id),
583
+ secretAccessKey: new SecretString(values.secret_access_key),
584
+ ...values.session_token ? { sessionToken: new SecretString(values.session_token) } : {}
585
+ };
586
+ } };
587
+ return newConnection(new SQSClient(config, credentials, options), { provider: "amazon-sqs", name: connectionName });
588
+ }
589
+ function newSQSConnectionWithOperations(operations, connectionName) {
590
+ return newConnectionWithOperations(operations, { provider: "amazon-sqs", name: connectionName });
591
+ }
592
+ export {
593
+ ChangeMessageVisibilityBranch,
594
+ ChangeMessageVisibilityBranchChanged,
595
+ ChangeMessageVisibilityBranchDefect,
596
+ ChangeMessageVisibilityBranchProviderRejected,
597
+ ChangeMessageVisibilityBranchReceiptHandleInvalid,
598
+ ChangeMessageVisibilityDefinition,
599
+ ChangeMessageVisibilityInputSchema,
600
+ ChangeMessageVisibilityMetadata,
601
+ ChangeMessageVisibilityOperation,
602
+ ChangedMessageVisibilitySchema,
603
+ ConfigSchema,
604
+ Connection,
605
+ ConnectorID,
606
+ DeleteMessageBranch,
607
+ DeleteMessageBranchDefect,
608
+ DeleteMessageBranchDeleted,
609
+ DeleteMessageBranchProviderRejected,
610
+ DeleteMessageBranchReceiptHandleInvalid,
611
+ DeleteMessageDefinition,
612
+ DeleteMessageInputSchema,
613
+ DeleteMessageMetadata,
614
+ DeleteMessageOperation,
615
+ DeletedMessageSchema,
616
+ MessageAttributeValueSchema,
617
+ MessageSchema,
618
+ ProviderID,
619
+ ReceiveMessagesBranch,
620
+ ReceiveMessagesBranchDefect,
621
+ ReceiveMessagesBranchEmpty,
622
+ ReceiveMessagesBranchInvalidResponse,
623
+ ReceiveMessagesBranchProviderRejected,
624
+ ReceiveMessagesBranchReceived,
625
+ ReceiveMessagesDefinition,
626
+ ReceiveMessagesInputSchema,
627
+ ReceiveMessagesMetadata,
628
+ ReceiveMessagesOperation,
629
+ ReceivedMessagesSchema,
630
+ SQSClient,
631
+ classifyResponse,
632
+ header,
633
+ newChangeMessageVisibilityStep,
634
+ newConnection,
635
+ newConnectionWithOperations,
636
+ newDeleteMessageStep,
637
+ newProjectConnection,
638
+ newReceiveMessagesStep,
639
+ newSQSConnectionWithOperations,
640
+ receiveSystemAttributes
641
+ };