@superdurable/connector-amazon-sqs 0.1.1 → 0.2.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 CHANGED
@@ -11,6 +11,15 @@ import {
11
11
  ConfigSchema,
12
12
  Connection,
13
13
  ConnectorID,
14
+ CreateQueueBranch,
15
+ CreateQueueBranchCreated,
16
+ CreateQueueBranchDefect,
17
+ CreateQueueBranchInvalidResponse,
18
+ CreateQueueBranchProviderRejected,
19
+ CreateQueueDefinition,
20
+ CreateQueueInputSchema,
21
+ CreateQueueMetadata,
22
+ CredentialMaterialError,
14
23
  DeleteMessageBranch,
15
24
  DeleteMessageBranchDefect,
16
25
  DeleteMessageBranchDeleted,
@@ -19,10 +28,45 @@ import {
19
28
  DeleteMessageDefinition,
20
29
  DeleteMessageInputSchema,
21
30
  DeleteMessageMetadata,
31
+ DeleteQueueBranch,
32
+ DeleteQueueBranchDefect,
33
+ DeleteQueueBranchDeleted,
34
+ DeleteQueueBranchProviderRejected,
35
+ DeleteQueueDefinition,
36
+ DeleteQueueMetadata,
22
37
  DeletedMessageSchema,
38
+ GetQueueAttributesBranch,
39
+ GetQueueAttributesBranchDefect,
40
+ GetQueueAttributesBranchFound,
41
+ GetQueueAttributesBranchInvalidResponse,
42
+ GetQueueAttributesBranchMissing,
43
+ GetQueueAttributesBranchProviderRejected,
44
+ GetQueueAttributesDefinition,
45
+ GetQueueAttributesMetadata,
46
+ GetQueueURLBranch,
47
+ GetQueueURLBranchDefect,
48
+ GetQueueURLBranchFound,
49
+ GetQueueURLBranchInvalidResponse,
50
+ GetQueueURLBranchMissing,
51
+ GetQueueURLBranchProviderRejected,
52
+ GetQueueURLDefinition,
53
+ GetQueueURLMetadata,
54
+ ListQueuesBranch,
55
+ ListQueuesBranchDefect,
56
+ ListQueuesBranchInvalidResponse,
57
+ ListQueuesBranchPage,
58
+ ListQueuesBranchProviderRejected,
59
+ ListQueuesDefinition,
60
+ ListQueuesInputSchema,
61
+ ListQueuesMetadata,
23
62
  MessageAttributeValueSchema,
24
63
  MessageSchema,
25
64
  ProviderID,
65
+ QueueAttributesSchema,
66
+ QueueIdentitySchema,
67
+ QueueNameInputSchema,
68
+ QueuePageSchema,
69
+ QueueURLInputSchema,
26
70
  ReceiveMessagesBranch,
27
71
  ReceiveMessagesBranchDefect,
28
72
  ReceiveMessagesBranchEmpty,
@@ -33,14 +77,42 @@ import {
33
77
  ReceiveMessagesInputSchema,
34
78
  ReceiveMessagesMetadata,
35
79
  ReceivedMessagesSchema,
80
+ SendMessageBranch,
81
+ SendMessageBranchDefect,
82
+ SendMessageBranchProviderRejected,
83
+ SendMessageBranchSent,
84
+ SendMessageBranchUncertain,
85
+ SendMessageDefinition,
86
+ SendMessageInputSchema,
87
+ SendMessageMetadata,
88
+ SentMessageSchema,
89
+ SetQueueAttributeBranch,
90
+ SetQueueAttributeBranchDefect,
91
+ SetQueueAttributeBranchProviderRejected,
92
+ SetQueueAttributeBranchUpdated,
93
+ SetQueueAttributeDefinition,
94
+ SetQueueAttributeInputSchema,
95
+ SetQueueAttributeMetadata,
96
+ decodeCredentials,
97
+ isCredentialMaterialError,
36
98
  newConnection,
37
99
  newConnectionWithOperations
38
- } from "./chunk-JUNMI7YJ.js";
100
+ } from "./chunk-WRBFEUIT.js";
39
101
 
40
102
  // src/generated/steps.ts
41
- import { goToBranch, newMutationStep } from "@superdurable/connectors-sdk";
103
+ import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
104
+ function newSendMessageStep(configuration) {
105
+ const { connection, connectionName, sent, providerRejected, uncertain, defect: defect2, ...stepConfiguration } = configuration;
106
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
107
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.sendMessage(), connection: connection.reference, branches: [
108
+ goToBranch("sent", sent),
109
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
110
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : [],
111
+ ...defect2 ? [goToBranch("defect", defect2)] : []
112
+ ] });
113
+ }
42
114
  function newReceiveMessagesStep(configuration) {
43
- const { connection, connectionName, received, empty, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
115
+ const { connection, connectionName, received, empty, providerRejected, invalidResponse, defect: defect2, maxSends, ...stepConfiguration } = configuration;
44
116
  if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
45
117
  return newMutationStep({ ...stepConfiguration, operation: connection.operations.receiveMessages(), connection: connection.reference, branches: [
46
118
  goToBranch("received", received),
@@ -51,7 +123,7 @@ function newReceiveMessagesStep(configuration) {
51
123
  ] });
52
124
  }
53
125
  function newDeleteMessageStep(configuration) {
54
- const { connection, connectionName, deleted, receiptHandleInvalid, providerRejected, defect: defect2, ...stepConfiguration } = configuration;
126
+ const { connection, connectionName, deleted, receiptHandleInvalid, providerRejected, defect: defect2, maxSends, ...stepConfiguration } = configuration;
55
127
  if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
56
128
  return newMutationStep({ ...stepConfiguration, operation: connection.operations.deleteMessage(), connection: connection.reference, branches: [
57
129
  goToBranch("deleted", deleted),
@@ -61,7 +133,7 @@ function newDeleteMessageStep(configuration) {
61
133
  ] });
62
134
  }
63
135
  function newChangeMessageVisibilityStep(configuration) {
64
- const { connection, connectionName, changed, receiptHandleInvalid, providerRejected, defect: defect2, ...stepConfiguration } = configuration;
136
+ const { connection, connectionName, changed, receiptHandleInvalid, providerRejected, defect: defect2, maxSends, ...stepConfiguration } = configuration;
65
137
  if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
66
138
  return newMutationStep({ ...stepConfiguration, operation: connection.operations.changeMessageVisibility(), connection: connection.reference, branches: [
67
139
  goToBranch("changed", changed),
@@ -70,14 +142,108 @@ function newChangeMessageVisibilityStep(configuration) {
70
142
  ...defect2 ? [goToBranch("defect", defect2)] : []
71
143
  ] });
72
144
  }
145
+ function newListQueuesStep(configuration) {
146
+ const { connection, connectionName, page, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
147
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
148
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listQueues(), connection: connection.reference, branches: [
149
+ goToBranch("page", page),
150
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
151
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
152
+ ...defect2 ? [goToBranch("defect", defect2)] : []
153
+ ] });
154
+ }
155
+ function newCreateQueueStep(configuration) {
156
+ const { connection, connectionName, created, providerRejected, invalidResponse, defect: defect2, maxSends, ...stepConfiguration } = configuration;
157
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
158
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.createQueue(), connection: connection.reference, branches: [
159
+ goToBranch("created", created),
160
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
161
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
162
+ ...defect2 ? [goToBranch("defect", defect2)] : []
163
+ ] });
164
+ }
165
+ function newGetQueueURLStep(configuration) {
166
+ const { connection, connectionName, found, missing, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
167
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
168
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getQueueURL(), connection: connection.reference, branches: [
169
+ goToBranch("found", found),
170
+ ...missing ? [goToBranch("missing", missing)] : [],
171
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
172
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
173
+ ...defect2 ? [goToBranch("defect", defect2)] : []
174
+ ] });
175
+ }
176
+ function newGetQueueAttributesStep(configuration) {
177
+ const { connection, connectionName, found, missing, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
178
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
179
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getQueueAttributes(), connection: connection.reference, branches: [
180
+ goToBranch("found", found),
181
+ ...missing ? [goToBranch("missing", missing)] : [],
182
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
183
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
184
+ ...defect2 ? [goToBranch("defect", defect2)] : []
185
+ ] });
186
+ }
187
+ function newSetQueueAttributeStep(configuration) {
188
+ const { connection, connectionName, updated, providerRejected, defect: defect2, maxSends, ...stepConfiguration } = configuration;
189
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
190
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.setQueueAttribute(), connection: connection.reference, branches: [
191
+ goToBranch("updated", updated),
192
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
193
+ ...defect2 ? [goToBranch("defect", defect2)] : []
194
+ ] });
195
+ }
196
+ function newDeleteQueueStep(configuration) {
197
+ const { connection, connectionName, deleted, providerRejected, defect: defect2, maxSends, ...stepConfiguration } = configuration;
198
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
199
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.deleteQueue(), connection: connection.reference, branches: [
200
+ goToBranch("deleted", deleted),
201
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
202
+ ...defect2 ? [goToBranch("defect", defect2)] : []
203
+ ] });
204
+ }
73
205
 
74
206
  // src/client.ts
75
207
  import { createHash as createHash2, createHmac } from "crypto";
76
- import { BodyTooLargeError, parseRetryAfter, sendProviderRequest } from "@superdurable/connectors-sdk/providerhttp";
208
+ import { ReauthorizationRequiredError } from "@superdurable/connectors-sdk";
209
+ import { ConnectionNotSelectedError, CredentialBrokerRejectedError, ObjectNotFoundError } from "@superdurable/connectors-sdk/projectconfig";
210
+ import { BodyTooLargeError, ProviderTransportError, parseRetryAfter as parseRetryAfter2, sendProviderRequest } from "@superdurable/connectors-sdk/providerhttp";
77
211
 
78
212
  // src/operations.ts
79
213
  import { createHash } from "crypto";
80
- import { newMutationBranch, newMutationRetry, zeroReceipt } from "@superdurable/connectors-sdk";
214
+ import { definitionMaxSends, newMutationBranch, newMutationRetry, newMutationUncertain, newQueryBranch, newQueryRetry, zeroReceipt } from "@superdurable/connectors-sdk";
215
+ import { parseRetryAfter } from "@superdurable/connectors-sdk/providerhttp";
216
+ import { DispatchNotAllowedError, newFence } from "@superdurable/connectors-sdk/singledispatch";
217
+
218
+ // src/queue_address.ts
219
+ var namePattern = /^[A-Za-z0-9_-]{1,80}$/;
220
+ var ownerPattern = /^[A-Za-z0-9_-]{1,64}$/;
221
+ function isValidQueueName(name) {
222
+ if (typeof name !== "string" || name.length > 80 || /[\r\n]/.test(name)) return false;
223
+ return namePattern.test(name.endsWith(".fifo") ? name.slice(0, -5) : name);
224
+ }
225
+ function parseQueueURL(queueUrl) {
226
+ if (typeof queueUrl !== "string" || Buffer.byteLength(queueUrl) > 2048) throw new TypeError("queueUrl must be a queue URL");
227
+ let parsed;
228
+ try {
229
+ parsed = new URL(queueUrl);
230
+ } catch {
231
+ throw new TypeError("queueUrl must be a queue URL");
232
+ }
233
+ if (!["https:", "http:"].includes(parsed.protocol) || !parsed.hostname || parsed.username || parsed.password || parsed.search || parsed.hash || parsed.href !== queueUrl) {
234
+ throw new TypeError("queueUrl must be a queue URL");
235
+ }
236
+ const match = /^\/([^/]+)\/([^/]+)$/.exec(parsed.pathname);
237
+ if (!match || !ownerPattern.test(match[1] ?? "")) throw new TypeError("queueUrl must be a queue URL");
238
+ const name = match[2] ?? "";
239
+ if (!isValidQueueName(name)) {
240
+ throw new TypeError("queueUrl must end with a queue name of 1 to 80 letters, digits, hyphens, and underscores, including any .fifo suffix");
241
+ }
242
+ const amazonRegion = /^sqs\.([a-z0-9-]+)\.amazonaws\.(?:com|com\.cn|eu)$/.exec(parsed.hostname)?.[1];
243
+ return { name, isFIFO: name.endsWith(".fifo"), ...amazonRegion ? { amazonRegion } : {} };
244
+ }
245
+
246
+ // src/operations.ts
81
247
  var provider = "amazon-sqs";
82
248
  var printable = /^[\x21-\x7e]+$/;
83
249
  var messageAttributeName = /^[A-Za-z0-9_.-]{1,256}$/;
@@ -90,6 +256,9 @@ function failure(operation, kind, message) {
90
256
  function defect(operation, output, message) {
91
257
  return newMutationBranch("defect", output, zeroReceipt(), failure(operation, "VALIDATION", message));
92
258
  }
259
+ function credentialsRetry(operation) {
260
+ return newMutationRetry(failure(operation, "AVAILABILITY", "SQS connection credentials are temporarily unavailable; nothing was sent"));
261
+ }
93
262
  function credentialsDefect(operation, output) {
94
263
  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
264
  }
@@ -146,7 +315,8 @@ var ReceiveMessagesOperation = class {
146
315
  if (visibility !== void 0 && (!Number.isSafeInteger(visibility) || visibility < 0 || visibility > 43200)) return defect(operation, zeroReceived, "visibilityTimeoutSeconds must be from 0 to 43200");
147
316
  const attemptId = call.idempotencyKey ?? "";
148
317
  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);
318
+ const credentials = await this.client["resolveCredentialsOrTransient"](call);
319
+ if (credentials === null) return credentialsRetry(operation);
150
320
  if (!credentials) return credentialsDefect(operation, zeroReceived);
151
321
  const batch = { queueUrl: queue.url, ...queue.isFIFO ? { isFifo: true } : {} };
152
322
  const attributes = receiveSystemAttributes();
@@ -208,7 +378,8 @@ var DeleteMessageOperation = class {
208
378
  } catch (error2) {
209
379
  return defect(operation, zeroDeleted, error2.message);
210
380
  }
211
- const credentials = await this.client.resolveCredentials(call);
381
+ const credentials = await this.client["resolveCredentialsOrTransient"](call);
382
+ if (credentials === null) return credentialsRetry(operation);
212
383
  if (!credentials) return credentialsDefect(operation, zeroDeleted);
213
384
  const deleted = { queueUrl: queue.url, ...input.messageId ? { messageId: input.messageId } : {} };
214
385
  const objectId = input.messageId ? `${queue.url}#${input.messageId}` : queue.url;
@@ -247,7 +418,8 @@ var ChangeMessageVisibilityOperation = class {
247
418
  return defect(operation, zeroChanged, error.message);
248
419
  }
249
420
  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);
421
+ const credentials = await this.client["resolveCredentialsOrTransient"](call);
422
+ if (credentials === null) return credentialsRetry(operation);
251
423
  if (!credentials) return credentialsDefect(operation, zeroChanged);
252
424
  const changed = { queueUrl: queue.url, ...input.messageId ? { messageId: input.messageId } : {}, visibilityTimeoutSeconds: input.visibilityTimeoutSeconds, visibleAfter: "0001-01-01T00:00:00Z" };
253
425
  const objectId = input.messageId ? `${queue.url}#${input.messageId}` : queue.url;
@@ -258,7 +430,8 @@ var ChangeMessageVisibilityOperation = class {
258
430
  return transportRetry(operation, "visibility change");
259
431
  }
260
432
  const classified = classifyAcknowledgement(call, this.client, response, credentials, operation, "visibility change", changed, objectId);
261
- if (classified) return classified;
433
+ const isRepeatedRelease = input.visibilityTimeoutSeconds === 0 && call.context.attempt > 1 && classified?.kind === "branch" && classified.branch === "receiptHandleInvalid";
434
+ if (classified && !isRepeatedRelease) return classified;
262
435
  const receipt = this.client.receipt(call, response, objectId);
263
436
  changed.visibleAfter = new Date(Date.parse(receipt.observedAt) + input.visibilityTimeoutSeconds * 1e3).toISOString().replace(/\.000Z$/, "Z");
264
437
  return newMutationBranch("changed", changed, receipt);
@@ -327,12 +500,452 @@ function decodeMessage(value) {
327
500
  }
328
501
  return message;
329
502
  }
503
+ var SendMessageOperation = class {
504
+ /** Bind one SQS client. */
505
+ constructor(client) {
506
+ this.client = client;
507
+ }
508
+ client;
509
+ /** Return the manifest operation identity. */
510
+ definition() {
511
+ return SendMessageDefinition;
512
+ }
513
+ /** Use the stable Dex call ID to correlate retries. */
514
+ idempotencyKey(callId) {
515
+ return callId;
516
+ }
517
+ /** Send one message to an Amazon SQS queue. */
518
+ async invoke(call, input) {
519
+ return sendMessage(this.client, call, input);
520
+ }
521
+ };
522
+ var ListQueuesOperation = class {
523
+ /** Bind one SQS client. */
524
+ constructor(client) {
525
+ this.client = client;
526
+ }
527
+ client;
528
+ /** Return the manifest operation identity. */
529
+ definition() {
530
+ return ListQueuesDefinition;
531
+ }
532
+ /** List one bounded page of Amazon SQS queues. */
533
+ async invoke(call, input) {
534
+ return listQueues(this.client, call, input);
535
+ }
536
+ };
537
+ var CreateQueueOperation = class {
538
+ /** Bind one SQS client. */
539
+ constructor(client) {
540
+ this.client = client;
541
+ }
542
+ client;
543
+ /** Return the manifest operation identity. */
544
+ definition() {
545
+ return CreateQueueDefinition;
546
+ }
547
+ /** Use the stable Dex call ID to correlate retries. */
548
+ idempotencyKey(callId) {
549
+ return callId;
550
+ }
551
+ /** Create an Amazon SQS queue with explicit settings. */
552
+ async invoke(call, input) {
553
+ return createQueue(this.client, call, input);
554
+ }
555
+ };
556
+ var GetQueueURLOperation = class {
557
+ /** Bind one SQS client. */
558
+ constructor(client) {
559
+ this.client = client;
560
+ }
561
+ client;
562
+ /** Return the manifest operation identity. */
563
+ definition() {
564
+ return GetQueueURLDefinition;
565
+ }
566
+ /** Resolve an Amazon SQS queue name to its URL. */
567
+ async invoke(call, input) {
568
+ return getQueueURL(this.client, call, input);
569
+ }
570
+ };
571
+ var GetQueueAttributesOperation = class {
572
+ /** Bind one SQS client. */
573
+ constructor(client) {
574
+ this.client = client;
575
+ }
576
+ client;
577
+ /** Return the manifest operation identity. */
578
+ definition() {
579
+ return GetQueueAttributesDefinition;
580
+ }
581
+ /** Read settings from an Amazon SQS queue. */
582
+ async invoke(call, input) {
583
+ return getQueueAttributes(this.client, call, input);
584
+ }
585
+ };
586
+ var SetQueueAttributeOperation = class {
587
+ /** Bind one SQS client. */
588
+ constructor(client) {
589
+ this.client = client;
590
+ }
591
+ client;
592
+ /** Return the manifest operation identity. */
593
+ definition() {
594
+ return SetQueueAttributeDefinition;
595
+ }
596
+ /** Use the stable Dex call ID to correlate retries. */
597
+ idempotencyKey(callId) {
598
+ return callId;
599
+ }
600
+ /** Replace one setting on an Amazon SQS queue. */
601
+ async invoke(call, input) {
602
+ return setQueueAttribute(this.client, call, input);
603
+ }
604
+ };
605
+ var DeleteQueueOperation = class {
606
+ /** Bind one SQS client. */
607
+ constructor(client) {
608
+ this.client = client;
609
+ }
610
+ client;
611
+ /** Return the manifest operation identity. */
612
+ definition() {
613
+ return DeleteQueueDefinition;
614
+ }
615
+ /** Use the stable Dex call ID to correlate retries. */
616
+ idempotencyKey(callId) {
617
+ return callId;
618
+ }
619
+ /** Delete an Amazon SQS queue and its messages. */
620
+ async invoke(call, input) {
621
+ return deleteQueue(this.client, call, input);
622
+ }
623
+ };
624
+ var sendOperation = "sendMessage";
625
+ var queueMissingCodes = /* @__PURE__ */ new Set(["QueueDoesNotExist", "AWS.SimpleQueueService.NonExistentQueue"]);
626
+ var definiteRefusalStatuses = /* @__PURE__ */ new Set([400, 401, 403, 404, 411, 413, 414, 415, 422]);
627
+ var queueSettings = /* @__PURE__ */ new Map([
628
+ ["VisibilityTimeout", [0, 43200]],
629
+ ["ReceiveMessageWaitTimeSeconds", [0, 20]],
630
+ ["DelaySeconds", [0, 900]],
631
+ ["MaximumMessageSize", [1024, 1048576]]
632
+ ]);
633
+ async function listQueues(client, call, input) {
634
+ const operation = "listQueues";
635
+ const { queueNamePrefix = "", nextToken = "", maxResults = 0 } = input;
636
+ const limit = maxResults || 100;
637
+ const empty = { queueUrls: [] };
638
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e3 || !validText(queueNamePrefix, 80) || !validText(nextToken, 1024)) {
639
+ return queryDefect(operation, empty, "SQS queue filter or page token is invalid");
640
+ }
641
+ const document = {
642
+ MaxResults: limit,
643
+ ...queueNamePrefix ? { QueueNamePrefix: queueNamePrefix } : {},
644
+ ...nextToken ? { NextToken: nextToken } : {}
645
+ };
646
+ const result = await queueRequest(client, call, operation, "queue list", "ListQueues", document);
647
+ if ("failure" in result) return queueQueryFailure(result, empty);
648
+ try {
649
+ const reply = queueDocument(result);
650
+ const urls = reply.QueueUrls ?? [];
651
+ const token = reply.NextToken ?? "";
652
+ if (!Array.isArray(urls) || urls.length > limit || typeof token !== "string" || Buffer.byteLength(token) > 1024) throw new TypeError();
653
+ const queueUrls = urls.map((value) => {
654
+ if (typeof value !== "string") throw new TypeError();
655
+ parseQueueURL(value);
656
+ return value;
657
+ });
658
+ return newQueryBranch("page", { queueUrls, ...token ? { nextToken: token } : {} });
659
+ } catch {
660
+ return queryInvalid(operation, empty, "SQS returned invalid queue list");
661
+ }
662
+ }
663
+ async function createQueue(client, call, input) {
664
+ const operation = "createQueue";
665
+ const empty = { queueUrl: "" };
666
+ if (!isValidQueueName(input.queueName) || !validQueueCreation(input)) {
667
+ return defect(operation, empty, "SQS queue name or attributes are invalid");
668
+ }
669
+ const result = await queueRequest(client, call, operation, "queue creation", "CreateQueue", {
670
+ QueueName: input.queueName,
671
+ Attributes: input.attributes ?? null
672
+ });
673
+ if ("failure" in result) return queueMutationFailure(client, call, result, empty);
674
+ const identity = namedQueueIdentity(result, input.queueName);
675
+ if (!identity) return newMutationRetry(failure(operation, "PROTOCOL", "SQS returned invalid created queue URL"));
676
+ return newMutationBranch("created", identity, client.receipt(call, result, identity.queueUrl));
677
+ }
678
+ async function getQueueURL(client, call, input) {
679
+ const operation = "getQueueURL";
680
+ const empty = { queueUrl: "" };
681
+ if (!isValidQueueName(input.queueName)) return queryDefect(operation, empty, "SQS queue name is invalid");
682
+ const result = await queueRequest(client, call, operation, "queue lookup", "GetQueueUrl", { QueueName: input.queueName });
683
+ if ("failure" in result) return queueQueryFailure(result, empty, true);
684
+ const identity = namedQueueIdentity(result, input.queueName);
685
+ return identity ? newQueryBranch("found", identity) : queryInvalid(operation, empty, "SQS returned invalid queue URL");
686
+ }
687
+ async function getQueueAttributes(client, call, input) {
688
+ const operation = "getQueueAttributes";
689
+ const empty = { queueUrl: "", attributes: {} };
690
+ let queue;
691
+ try {
692
+ queue = client.resolveQueue(input.queueUrl);
693
+ } catch {
694
+ return queryDefect(operation, empty, "SQS queue URL is invalid");
695
+ }
696
+ const result = await queueRequest(client, call, operation, "queue attribute read", "GetQueueAttributes", {
697
+ QueueUrl: queue.url,
698
+ AttributeNames: ["All"]
699
+ });
700
+ if ("failure" in result) return queueQueryFailure(result, empty, true);
701
+ try {
702
+ const attributes = queueDocument(result).Attributes;
703
+ if (!isQueueDocument(attributes)) throw new TypeError();
704
+ const entries = Object.entries(attributes);
705
+ if (entries.length > 128) throw new TypeError();
706
+ const values = Object.fromEntries(entries.map(([key, value]) => {
707
+ const text = value ?? "";
708
+ if (!key || !validText(key, 128) || typeof text !== "string" || Buffer.byteLength(text) > 1 << 20) throw new TypeError();
709
+ return [key, text];
710
+ }));
711
+ return newQueryBranch("found", { queueUrl: queue.url, attributes: values });
712
+ } catch {
713
+ return queryInvalid(operation, empty, "SQS returned invalid queue attributes");
714
+ }
715
+ }
716
+ async function setQueueAttribute(client, call, input) {
717
+ const operation = "setQueueAttribute";
718
+ const empty = { queueUrl: "" };
719
+ let queue;
720
+ try {
721
+ queue = client.resolveQueue(input.queueUrl);
722
+ } catch {
723
+ return defect(operation, empty, "SQS queue URL is invalid");
724
+ }
725
+ if (!validQueueSetting(input.attributeName, input.attributeValue)) return defect(operation, empty, "SQS queue setting is invalid");
726
+ const result = await queueRequest(client, call, operation, "queue attribute update", "SetQueueAttributes", {
727
+ QueueUrl: queue.url,
728
+ Attributes: { [input.attributeName]: input.attributeValue }
729
+ });
730
+ if ("failure" in result) return queueMutationFailure(client, call, result, empty, queue.url);
731
+ return newMutationBranch("updated", { queueUrl: queue.url }, client.receipt(call, result, queue.url));
732
+ }
733
+ async function deleteQueue(client, call, input) {
734
+ const operation = "deleteQueue";
735
+ const empty = { queueUrl: "" };
736
+ let queue;
737
+ try {
738
+ queue = client.resolveQueue(input.queueUrl);
739
+ } catch {
740
+ return defect(operation, empty, "SQS queue URL is invalid");
741
+ }
742
+ const result = await queueRequest(client, call, operation, "queue deletion", "DeleteQueue", { QueueUrl: queue.url });
743
+ if ("failure" in result) return queueMutationFailure(client, call, result, empty, queue.url);
744
+ return newMutationBranch("deleted", { queueUrl: queue.url }, client.receipt(call, result, queue.url));
745
+ }
746
+ async function sendMessage(client, call, input) {
747
+ const empty = emptySentMessage();
748
+ let queue;
749
+ try {
750
+ queue = client.resolveQueue(input.queueUrl);
751
+ } catch {
752
+ return defect(sendOperation, empty, "SQS queue URL is invalid");
753
+ }
754
+ const group = input.messageGroupId ?? "";
755
+ const body = typeof input.body === "string" ? Buffer.from(input.body) : Buffer.alloc(0);
756
+ if (!body.length || body.length > 256 * 1024 || body.toString() !== input.body || queue.isFIFO && !group || group.length > 128 || group && /[^!-~]/.test(group)) {
757
+ return defect(sendOperation, empty, "SQS message body or group ID is invalid");
758
+ }
759
+ const maxSends = call.maxSendsOverride ?? definitionMaxSends(SendMessageDefinition);
760
+ let fence;
761
+ try {
762
+ fence = newFence(call, SendMessageDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4, { maxSends });
763
+ } catch {
764
+ return newMutationBranch("defect", empty, zeroReceipt(), failure(sendOperation, "LOCAL_DEFECT", "SQS send fence could not be initialized"));
765
+ }
766
+ const decision = fence.decide();
767
+ if (decision.kind === "failClosed") return checkpointRetry("SQS send checkpoint is unavailable");
768
+ if (decision.kind === "readBackRequired") {
769
+ return newMutationUncertain(empty, failure(sendOperation, "TRANSPORT", "SQS send outcome could not be confirmed"), zeroReceipt());
770
+ }
771
+ const priorSends = decision.priorSendUpperBound ?? 0;
772
+ const credentials = await client["resolveCredentialsOrTransient"](call);
773
+ if (credentials === null) return credentialsRetry(sendOperation);
774
+ if (!credentials) {
775
+ try {
776
+ await fence.recordNotSent();
777
+ } catch (error) {
778
+ if (!(error instanceof DispatchNotAllowedError)) return checkpointRetry("SQS unsent checkpoint could not be recorded");
779
+ }
780
+ const auth = credentialsFailure(sendOperation);
781
+ return priorSends ? newMutationRetry(auth) : newMutationBranch("defect", empty, zeroReceipt(), auth);
782
+ }
783
+ const request = {
784
+ QueueUrl: queue.url,
785
+ MessageBody: input.body,
786
+ ...group ? { MessageGroupId: group } : {},
787
+ ...queue.isFIFO && call.idempotencyKey ? { MessageDeduplicationId: call.idempotencyKey } : {}
788
+ };
789
+ const finalSend = priorSends + 1 >= maxSends;
790
+ let response;
791
+ try {
792
+ response = await fence.dispatch(async (signal) => {
793
+ try {
794
+ return await client.exchange(call, credentials, "SendMessage", request, { signal, responseLimit: 65536 });
795
+ } catch {
796
+ return void 0;
797
+ }
798
+ });
799
+ } catch {
800
+ return checkpointRetry("SQS send dispatch checkpoint is unavailable");
801
+ }
802
+ if (!response) {
803
+ return sendUnknown(finalSend, failure(sendOperation, "TRANSPORT", "SQS could not be reached or did not finish the message send"));
804
+ }
805
+ if (response.status < 200 || response.status >= 300) {
806
+ const classified = classifyResponse(sendOperation, "message send", response, credentials, client.now());
807
+ const isDeferred = classified.branch === "retry" && [429, 503].includes(response.status);
808
+ const isFirstRefusal = classified.branch !== "retry" && !priorSends && isDefiniteRefusal(response.status, classified.code);
809
+ if (isDeferred || isFirstRefusal) {
810
+ try {
811
+ await fence.recordCanResend();
812
+ } catch {
813
+ return checkpointRetry("SQS resend checkpoint could not be recorded");
814
+ }
815
+ if (isDeferred) return newMutationRetry(classified.failure, classified.retryAfterMs);
816
+ return newMutationBranch("providerRejected", empty, zeroReceipt(), classified.failure);
817
+ }
818
+ return sendUnknown(finalSend, classified.failure);
819
+ }
820
+ if (response.isTooLarge) {
821
+ return sendUnknown(finalSend, failure(sendOperation, "TRANSPORT", "SQS send response was interrupted"));
822
+ }
823
+ const md5OfBody = createHash("md5").update(body).digest("hex");
824
+ try {
825
+ const receipt = queueDocument(response);
826
+ const messageId = receipt.MessageId;
827
+ if (typeof messageId !== "string" || !messageId || !validMessageId(messageId) || receipt.MD5OfMessageBody !== md5OfBody || containsCredential(messageId, credentials)) throw new TypeError();
828
+ return newMutationBranch(
829
+ "sent",
830
+ { queueUrl: queue.url, messageId, md5OfBody },
831
+ client.receipt(call, response, `${queue.url}#${messageId}`)
832
+ );
833
+ } catch {
834
+ return sendUnknown(finalSend, failure(sendOperation, "PROTOCOL", "SQS send response has no usable message ID or checksum"));
835
+ }
836
+ }
837
+ async function queueRequest(client, call, operation, subject, action, request) {
838
+ const credentials = await client["resolveCredentialsOrTransient"](call);
839
+ if (credentials === null) {
840
+ return { branch: "retry", failure: failure(operation, "AVAILABILITY", "SQS connection credentials are temporarily unavailable; nothing was sent"), retryAfterMs: 0 };
841
+ }
842
+ if (!credentials) return { branch: "defect", failure: credentialsFailure(operation), retryAfterMs: 0 };
843
+ let response;
844
+ try {
845
+ response = await client.exchange(call, credentials, action, request, { sortKeys: true });
846
+ } catch {
847
+ return { branch: "retry", failure: failure(operation, "TRANSPORT", `SQS ${subject} request failed`), retryAfterMs: 0 };
848
+ }
849
+ if (response.status < 200 || response.status >= 300) {
850
+ const classified = classifyResponse(operation, subject, response, credentials, client.now());
851
+ const branch = classified.branch === "retry" ? "retry" : queueMissingCodes.has(classified.code) ? "missing" : "providerRejected";
852
+ return {
853
+ branch,
854
+ response,
855
+ failure: classified.failure,
856
+ retryAfterMs: parseRetryAfter(header(response.headers, "retry-after"), client.now()),
857
+ isDefiniteRefusal: isDefiniteRefusal(response.status, classified.code)
858
+ };
859
+ }
860
+ if (response.isTooLarge) {
861
+ return { branch: "invalidResponse", failure: failure(operation, "RESPONSE_TOO_LARGE", `SQS ${subject} response was too large`), retryAfterMs: 0 };
862
+ }
863
+ if (containsCredential(Buffer.from(response.body).toString(), credentials)) {
864
+ return { branch: "invalidResponse", failure: failure(operation, "PROTOCOL", "SQS response contained connection credentials"), retryAfterMs: 0 };
865
+ }
866
+ return response;
867
+ }
868
+ function queueQueryFailure(result, empty, allowsMissing = false) {
869
+ if (result.branch === "retry") return newQueryRetry(result.failure, result.retryAfterMs);
870
+ if (result.branch === "missing" && allowsMissing) return newQueryBranch("missing", empty);
871
+ const branch = result.branch === "missing" ? "providerRejected" : result.branch;
872
+ return newQueryBranch(branch, empty, {}, result.failure);
873
+ }
874
+ function queueMutationFailure(client, call, result, empty, objectId = "") {
875
+ const hasPriorAttempt = call.context.attempt > 1;
876
+ if (result.branch === "retry" || result.branch === "invalidResponse" || hasPriorAttempt && result.branch === "defect" || result.response && (hasPriorAttempt || !result.isDefiniteRefusal)) {
877
+ return newMutationRetry(result.failure, result.retryAfterMs);
878
+ }
879
+ const branch = result.branch === "defect" ? "defect" : "providerRejected";
880
+ const receipt = client.receipt(call, result.response ?? { status: 0, body: new Uint8Array(), isTooLarge: false, headers: {} }, objectId);
881
+ return newMutationBranch(branch, empty, receipt, result.failure);
882
+ }
883
+ function queryDefect(operation, empty, message) {
884
+ return newQueryBranch("defect", empty, {}, failure(operation, "VALIDATION", message));
885
+ }
886
+ function queryInvalid(operation, empty, message) {
887
+ return newQueryBranch("invalidResponse", empty, {}, failure(operation, "PROTOCOL", message));
888
+ }
889
+ function emptySentMessage() {
890
+ return { queueUrl: "", messageId: "", md5OfBody: "" };
891
+ }
892
+ function credentialsFailure(operation) {
893
+ return failure(operation, "AUTHENTICATION", "SQS connection credentials are unavailable; save an access key ID and secret access key for the connection");
894
+ }
895
+ function checkpointRetry(message) {
896
+ return newMutationRetry(failure(sendOperation, "AVAILABILITY", message));
897
+ }
898
+ function sendUnknown(finalSend, outcome) {
899
+ return finalSend ? newMutationUncertain(emptySentMessage(), outcome, zeroReceipt()) : newMutationRetry(outcome);
900
+ }
901
+ function containsCredential(value, credentials) {
902
+ return [credentials.secretAccessKey.reveal(), credentials.sessionToken?.reveal()].some((secret) => !!secret && value.includes(secret));
903
+ }
904
+ function isDefiniteRefusal(status, code) {
905
+ return definiteRefusalStatuses.has(status) && code !== "";
906
+ }
907
+ function queueDocument(response) {
908
+ const value = JSON.parse(Buffer.from(response.body).toString());
909
+ if (value === null) return {};
910
+ if (!isQueueDocument(value)) throw new TypeError("invalid SQS response");
911
+ return value;
912
+ }
913
+ function isQueueDocument(value) {
914
+ return value !== null && typeof value === "object" && !Array.isArray(value);
915
+ }
916
+ function namedQueueIdentity(response, name) {
917
+ try {
918
+ const url = queueDocument(response).QueueUrl;
919
+ if (typeof url === "string" && parseQueueURL(url).name === name) return { queueUrl: url };
920
+ } catch {
921
+ return void 0;
922
+ }
923
+ return void 0;
924
+ }
925
+ function validQueueCreation(input) {
926
+ const attributes = input.attributes ?? {};
927
+ const pairs = Object.entries(attributes);
928
+ if (pairs.length > 6 || input.queueName.endsWith(".fifo") !== (attributes.FifoQueue === "true")) return false;
929
+ return pairs.every(([key, value]) => key === "FifoQueue" && value === "true" || validQueueSetting(key, value));
930
+ }
931
+ function validQueueSetting(name, value) {
932
+ const range = queueSettings.get(name);
933
+ if (!range || typeof value !== "string" || !/^(?:0|[1-9][0-9]{0,6})$/.test(value) || /[\r\n]/.test(value)) return false;
934
+ const number = Number(value);
935
+ return number >= range[0] && number <= range[1];
936
+ }
937
+ function validText(value, limit) {
938
+ if (typeof value !== "string" || /[\r\n]/.test(value)) return false;
939
+ const bytes = Buffer.from(value);
940
+ return bytes.length <= limit && bytes.toString() === value;
941
+ }
330
942
 
331
943
  // src/client.ts
332
944
  var provider2 = "amazon-sqs";
945
+ function isTerminalCredentialError(error) {
946
+ return isCredentialMaterialError(error) || error instanceof ReauthorizationRequiredError || error instanceof ObjectNotFoundError || error instanceof ConnectionNotSelectedError || error instanceof CredentialBrokerRejectedError;
947
+ }
333
948
  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
949
  var requestIdPattern = /^[A-Za-z0-9+/=._-]{1,128}$/;
337
950
  var errorCodePattern = /^[A-Za-z0-9.]{1,96}$/;
338
951
  var systemAttributes = ["ApproximateReceiveCount", "ApproximateFirstReceiveTimestamp", "SentTimestamp", "MessageGroupId", "MessageDeduplicationId", "SequenceNumber"];
@@ -391,31 +1004,57 @@ var SQSClient = class {
391
1004
  changeMessageVisibility() {
392
1005
  return new ChangeMessageVisibilityOperation(this);
393
1006
  }
1007
+ /** Send one message to an Amazon SQS queue. */
1008
+ sendMessage() {
1009
+ return new SendMessageOperation(this);
1010
+ }
1011
+ /** List one bounded page of Amazon SQS queues. */
1012
+ listQueues() {
1013
+ return new ListQueuesOperation(this);
1014
+ }
1015
+ /** Create an Amazon SQS queue with explicit settings. */
1016
+ createQueue() {
1017
+ return new CreateQueueOperation(this);
1018
+ }
1019
+ /** Resolve an Amazon SQS queue name to its URL. */
1020
+ getQueueURL() {
1021
+ return new GetQueueURLOperation(this);
1022
+ }
1023
+ /** Read settings from an Amazon SQS queue. */
1024
+ getQueueAttributes() {
1025
+ return new GetQueueAttributesOperation(this);
1026
+ }
1027
+ /** Replace one setting on an Amazon SQS queue. */
1028
+ setQueueAttribute() {
1029
+ return new SetQueueAttributeOperation(this);
1030
+ }
1031
+ /** Delete an Amazon SQS queue and its messages. */
1032
+ deleteQueue() {
1033
+ return new DeleteQueueOperation(this);
1034
+ }
394
1035
  /** Select the input queue or the connection default and validate its identity. */
395
1036
  resolveQueue(inputQueueUrl) {
396
1037
  const queueUrl = inputQueueUrl || this.defaultQueueUrl;
397
1038
  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");
1039
+ const { isFIFO, amazonRegion } = parseQueueURL(queueUrl);
1040
+ if (this.isAmazonEndpoint && amazonRegion && amazonRegion !== this.region) {
1041
+ throw new TypeError(`queueUrl is in Region ${amazonRegion} but the connection signs for ${this.region}; set region to ${amazonRegion}`);
404
1042
  }
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
1043
  return { url: queueUrl, isFIFO };
414
1044
  }
415
1045
  /** Resolve one current access key without retaining it in a result. */
416
1046
  async resolveCredentials(call) {
1047
+ return await this.resolveCredentialsOrTransient(call) ?? void 0;
1048
+ }
1049
+ /** Return null for a transient credential failure and undefined for a terminal or invalid one. */
1050
+ async resolveCredentialsOrTransient(call) {
1051
+ let credentials;
1052
+ try {
1053
+ credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
1054
+ } catch (error) {
1055
+ return isTerminalCredentialError(error) ? void 0 : null;
1056
+ }
417
1057
  try {
418
- const credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
419
1058
  const key = credentials.accessKeyId?.reveal();
420
1059
  const secret = credentials.secretAccessKey?.reveal();
421
1060
  const token = credentials.sessionToken?.reveal() ?? "";
@@ -426,8 +1065,11 @@ var SQSClient = class {
426
1065
  }
427
1066
  }
428
1067
  /** 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));
1068
+ async exchange(call, credentials, action, requestBody, options = {}) {
1069
+ const replacer = options.sortKeys ? (_key, value) => orderJSONKeys(value) : void 0;
1070
+ const json = JSON.stringify(requestBody, replacer);
1071
+ const body = Buffer.from(json.replace(/[&<>\u2028\u2029]/gu, (character) => "\\u" + character.charCodeAt(0).toString(16).padStart(4, "0")));
1072
+ const responseLimit = options.responseLimit ?? this.maxResponseBytes;
431
1073
  const url = new URL(this.endpoint);
432
1074
  const now = this.now();
433
1075
  const timestamp = now.toISOString().replace(/[-:]|\.\d{3}/g, "");
@@ -475,18 +1117,21 @@ ${createHash2("sha256").update(canonicalRequest).digest("hex")}`;
475
1117
  method: "POST",
476
1118
  headers,
477
1119
  body,
478
- maxResponseBytes: Math.max(this.maxResponseBytes, 65536),
1120
+ maxResponseBytes: Math.max(responseLimit, 65536),
479
1121
  timeoutMs: Math.min(25e3, remaining),
480
1122
  addressPolicy: this.isAmazonEndpoint ? "publicHTTPS" : "privateNetworkHTTP",
481
- signal: call.context.cancellationSignal
1123
+ signal: options.signal ?? call.context.cancellationSignal
482
1124
  };
483
1125
  try {
484
1126
  const response = await this.send(request);
485
- return { ...response, isTooLarge: response.body.length > this.maxResponseBytes };
1127
+ return { ...response, isTooLarge: response.body.length > responseLimit };
486
1128
  } catch (error) {
487
1129
  if (error instanceof BodyTooLargeError && error.status !== void 0 && error.headers !== void 0) {
488
1130
  return { status: error.status, headers: error.headers, body: new Uint8Array(), isTooLarge: true };
489
1131
  }
1132
+ if (error instanceof ProviderTransportError && error.status !== void 0 && (error.status < 200 || error.status >= 300)) {
1133
+ return { status: error.status, headers: error.headers ?? {}, body: new Uint8Array(), isTooLarge: false };
1134
+ }
490
1135
  throw error;
491
1136
  }
492
1137
  }
@@ -514,12 +1159,15 @@ function classifyResponse(operation, subject, response, credentials, now) {
514
1159
  let code = header(response.headers, "x-amzn-query-error").split(";")[0] ?? "";
515
1160
  let message = "";
516
1161
  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;
1162
+ const parsed = response.body.length <= 65536 ? JSON.parse(Buffer.from(response.body).toString("utf8")) : {};
1163
+ if (typeof parsed?.__type === "string") {
1164
+ const typeCode = parsed.__type.split("#").pop()?.split(":")[0] ?? "";
1165
+ if (isSafeErrorCode(typeCode, credentials)) code = typeCode;
1166
+ }
1167
+ if (typeof parsed?.message === "string") message = parsed.message;
520
1168
  } catch {
521
1169
  }
522
- if (!errorCodePattern.test(code) || [credentials.secretAccessKey.reveal(), credentials.sessionToken?.reveal()].some((secret) => secret && code.includes(secret))) code = "";
1170
+ if (!isSafeErrorCode(code, credentials)) code = "";
523
1171
  const status = response.status;
524
1172
  const withStatus = (summary) => `${summary} with HTTP ${status}${code ? ` ${code}` : ""}`;
525
1173
  let branch = "providerRejected";
@@ -555,9 +1203,20 @@ function classifyResponse(operation, subject, response, credentials, now) {
555
1203
  } else if (["AccessDenied", "AccessDeniedException", "KmsAccessDenied", "KmsDisabled", "KmsInvalidState", "KmsNotFound", "KmsOptInRequired", "KmsInvalidKeyUsage"].includes(code) || status === 403) {
556
1204
  kind = "AUTHORIZATION";
557
1205
  description = withStatus(`SQS denied the ${subject}`);
1206
+ } else if (![400, 401, 403, 404, 411, 413, 414, 415, 422, 501].includes(status)) {
1207
+ branch = "retry";
1208
+ kind = "AVAILABILITY";
1209
+ description = withStatus(`SQS answered the ${subject} ambiguously`);
558
1210
  }
559
1211
  const failure2 = { provider: provider2, operation, kind, message: description };
560
- return { branch, failure: failure2, retryAfterMs: branch === "retry" ? parseRetryAfter(header(response.headers, "retry-after"), now) : 0 };
1212
+ return { branch, failure: failure2, code, retryAfterMs: branch === "retry" ? parseRetryAfter2(header(response.headers, "retry-after"), now) : 0 };
1213
+ }
1214
+ function isSafeErrorCode(code, credentials) {
1215
+ return errorCodePattern.test(code) && ![credentials.secretAccessKey.reveal(), credentials.sessionToken?.reveal()].some((secret) => secret && code.includes(secret));
1216
+ }
1217
+ function orderJSONKeys(value) {
1218
+ if (!value || typeof value !== "object" || Array.isArray(value)) return value;
1219
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, value[key]]));
561
1220
  }
562
1221
 
563
1222
  // src/connection.ts
@@ -603,6 +1262,16 @@ export {
603
1262
  ConfigSchema,
604
1263
  Connection,
605
1264
  ConnectorID,
1265
+ CreateQueueBranch,
1266
+ CreateQueueBranchCreated,
1267
+ CreateQueueBranchDefect,
1268
+ CreateQueueBranchInvalidResponse,
1269
+ CreateQueueBranchProviderRejected,
1270
+ CreateQueueDefinition,
1271
+ CreateQueueInputSchema,
1272
+ CreateQueueMetadata,
1273
+ CreateQueueOperation,
1274
+ CredentialMaterialError,
606
1275
  DeleteMessageBranch,
607
1276
  DeleteMessageBranchDefect,
608
1277
  DeleteMessageBranchDeleted,
@@ -612,10 +1281,49 @@ export {
612
1281
  DeleteMessageInputSchema,
613
1282
  DeleteMessageMetadata,
614
1283
  DeleteMessageOperation,
1284
+ DeleteQueueBranch,
1285
+ DeleteQueueBranchDefect,
1286
+ DeleteQueueBranchDeleted,
1287
+ DeleteQueueBranchProviderRejected,
1288
+ DeleteQueueDefinition,
1289
+ DeleteQueueMetadata,
1290
+ DeleteQueueOperation,
615
1291
  DeletedMessageSchema,
1292
+ GetQueueAttributesBranch,
1293
+ GetQueueAttributesBranchDefect,
1294
+ GetQueueAttributesBranchFound,
1295
+ GetQueueAttributesBranchInvalidResponse,
1296
+ GetQueueAttributesBranchMissing,
1297
+ GetQueueAttributesBranchProviderRejected,
1298
+ GetQueueAttributesDefinition,
1299
+ GetQueueAttributesMetadata,
1300
+ GetQueueAttributesOperation,
1301
+ GetQueueURLBranch,
1302
+ GetQueueURLBranchDefect,
1303
+ GetQueueURLBranchFound,
1304
+ GetQueueURLBranchInvalidResponse,
1305
+ GetQueueURLBranchMissing,
1306
+ GetQueueURLBranchProviderRejected,
1307
+ GetQueueURLDefinition,
1308
+ GetQueueURLMetadata,
1309
+ GetQueueURLOperation,
1310
+ ListQueuesBranch,
1311
+ ListQueuesBranchDefect,
1312
+ ListQueuesBranchInvalidResponse,
1313
+ ListQueuesBranchPage,
1314
+ ListQueuesBranchProviderRejected,
1315
+ ListQueuesDefinition,
1316
+ ListQueuesInputSchema,
1317
+ ListQueuesMetadata,
1318
+ ListQueuesOperation,
616
1319
  MessageAttributeValueSchema,
617
1320
  MessageSchema,
618
1321
  ProviderID,
1322
+ QueueAttributesSchema,
1323
+ QueueIdentitySchema,
1324
+ QueueNameInputSchema,
1325
+ QueuePageSchema,
1326
+ QueueURLInputSchema,
619
1327
  ReceiveMessagesBranch,
620
1328
  ReceiveMessagesBranchDefect,
621
1329
  ReceiveMessagesBranchEmpty,
@@ -628,14 +1336,41 @@ export {
628
1336
  ReceiveMessagesOperation,
629
1337
  ReceivedMessagesSchema,
630
1338
  SQSClient,
1339
+ SendMessageBranch,
1340
+ SendMessageBranchDefect,
1341
+ SendMessageBranchProviderRejected,
1342
+ SendMessageBranchSent,
1343
+ SendMessageBranchUncertain,
1344
+ SendMessageDefinition,
1345
+ SendMessageInputSchema,
1346
+ SendMessageMetadata,
1347
+ SendMessageOperation,
1348
+ SentMessageSchema,
1349
+ SetQueueAttributeBranch,
1350
+ SetQueueAttributeBranchDefect,
1351
+ SetQueueAttributeBranchProviderRejected,
1352
+ SetQueueAttributeBranchUpdated,
1353
+ SetQueueAttributeDefinition,
1354
+ SetQueueAttributeInputSchema,
1355
+ SetQueueAttributeMetadata,
1356
+ SetQueueAttributeOperation,
631
1357
  classifyResponse,
1358
+ decodeCredentials,
632
1359
  header,
1360
+ isCredentialMaterialError,
633
1361
  newChangeMessageVisibilityStep,
634
1362
  newConnection,
635
1363
  newConnectionWithOperations,
1364
+ newCreateQueueStep,
636
1365
  newDeleteMessageStep,
1366
+ newDeleteQueueStep,
1367
+ newGetQueueAttributesStep,
1368
+ newGetQueueURLStep,
1369
+ newListQueuesStep,
637
1370
  newProjectConnection,
638
1371
  newReceiveMessagesStep,
639
1372
  newSQSConnectionWithOperations,
1373
+ newSendMessageStep,
1374
+ newSetQueueAttributeStep,
640
1375
  receiveSystemAttributes
641
1376
  };