@vouchington/aws 0.0.0-stage → 0.0.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/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jonathan Ong
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ # @vouchington/aws
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Primitives for AWS SDK v3: command builders, batching and chunking, attribute and record codecs,
4
+ and error classifiers. The application constructs and owns the clients, regions, credentials,
5
+ queue URLs, stream names, and namespaces, and decides when and how to send, retry, or record.
6
+ Each client package is an optional peer; install only the services you use. S3 stays in
7
+ `@vouchington/media`.
8
+
9
+ ## Subpaths
10
+
11
+ - `/ses`: `buildEmailCommand`, `buildSendEmailCommand`, `buildSendRawEmailCommand`,
12
+ `buildRawEmailMessage` (base64 MIME with caller headers, CR/LF rejected), and `SES_CLIENT_CONFIG`
13
+ (`maxAttempts: 1`, dual-stack). Source, reply-to, and BCC addresses are inputs.
14
+ - `/sqs`: `SQS_CLIENT_CONFIG`, `encodeMessageAttributes`, `decodeMessageAttributes`,
15
+ `chunkSendEntries`, `chunkDeleteEntries`, `buildSendMessageBatchCommand`,
16
+ `buildDeleteMessageBatchCommand`, `buildReceiveMessageCommand`, `classifyBatchFailures`.
17
+ - `/firehose`: `encodeJsonRecord`, `chunkFirehoseRecords`, `buildPutRecordBatchCommand`,
18
+ `getFailedFirehoseRecords`.
19
+ - `/cloudwatch`: `chunkMetricData`, `buildPutMetricDataCommand`.
20
+ - `/request-handler`: `createAwsRequestHandler` (default connection and socket deadlines,
21
+ timeout constants, `AWS_DUALSTACK_CLIENT_CONFIG`.
22
+ - `/errors`: `isAwsThrottlingError` and `getAwsErrorStatus`. Pass `getAwsErrorStatus` as
23
+ `getStatus` to `@vouchington/queue-errors` helpers; this package does not duplicate them.
24
+
25
+ ## Example
26
+
27
+ ```ts
28
+ import { SESClient } from '@aws-sdk/client-ses'
29
+ import { SES_CLIENT_CONFIG, buildEmailCommand } from '@vouchington/aws/ses'
30
+ import { createAwsRequestHandler } from '@vouchington/aws/request-handler'
31
+
32
+ const ses = new SESClient({
33
+ region,
34
+ requestHandler: createAwsRequestHandler(),
35
+ ...SES_CLIENT_CONFIG,
36
+ })
37
+ await ses.send(buildEmailCommand({ source, to, subject, text }))
38
+ ```
@@ -0,0 +1,7 @@
1
+ export interface ChunkOptions<T> {
2
+ maxItems: number;
3
+ maxBytes: number;
4
+ sizeOf: (item: T) => number;
5
+ }
6
+ export declare function chunkBySize<T>(items: readonly T[], options: ChunkOptions<T>): T[][];
7
+ export declare function byteLength(value: string | Uint8Array): number;
package/dist/chunk.mjs ADDED
@@ -0,0 +1,27 @@
1
+ // Splits items into ordered chunks bounded by count and total byte size. A single item larger
2
+ // than maxBytes can never be sent, so it throws instead of producing an unsendable chunk.
3
+ export function chunkBySize(items, options) {
4
+ const chunks = [];
5
+ let current = [];
6
+ let bytes = 0;
7
+ for (const item of items) {
8
+ const size = options.sizeOf(item);
9
+ if (size > options.maxBytes) {
10
+ throw new RangeError(`Item of ${size} bytes exceeds the ${options.maxBytes} byte limit`);
11
+ }
12
+ const full = current.length >= options.maxItems || bytes + size > options.maxBytes;
13
+ if (current.length > 0 && full) {
14
+ chunks.push(current);
15
+ current = [];
16
+ bytes = 0;
17
+ }
18
+ current.push(item);
19
+ bytes += size;
20
+ }
21
+ if (current.length > 0)
22
+ chunks.push(current);
23
+ return chunks;
24
+ }
25
+ export function byteLength(value) {
26
+ return typeof value === 'string' ? Buffer.byteLength(value, 'utf8') : value.byteLength;
27
+ }
@@ -0,0 +1,7 @@
1
+ import { PutMetricDataCommand, type MetricDatum } from '@aws-sdk/client-cloudwatch';
2
+ export declare const CLOUDWATCH_MAX_METRICS_PER_REQUEST = 1000;
3
+ export declare function chunkMetricData(metricData: readonly MetricDatum[], options?: {
4
+ maxItems?: number;
5
+ maxBytes?: number;
6
+ }): MetricDatum[][];
7
+ export declare function buildPutMetricDataCommand(namespace: string, metricData: readonly MetricDatum[]): PutMetricDataCommand;
@@ -0,0 +1,17 @@
1
+ import { PutMetricDataCommand } from '@aws-sdk/client-cloudwatch';
2
+ import { chunkBySize } from './chunk.mjs';
3
+ export const CLOUDWATCH_MAX_METRICS_PER_REQUEST = 1_000;
4
+ // CloudWatch caps requests at 1 MB; stay under it to leave room for the envelope.
5
+ const CLOUDWATCH_MAX_REQUEST_BYTES = 900_000;
6
+ // Splits metric data into PutMetricData-sized batches by count and approximate serialized size.
7
+ // The caller sends each batch. A single datum over the byte limit throws.
8
+ export function chunkMetricData(metricData, options = {}) {
9
+ return chunkBySize(metricData, {
10
+ maxItems: options.maxItems ?? CLOUDWATCH_MAX_METRICS_PER_REQUEST,
11
+ maxBytes: options.maxBytes ?? CLOUDWATCH_MAX_REQUEST_BYTES,
12
+ sizeOf: (datum) => Buffer.byteLength(JSON.stringify(datum), 'utf8'),
13
+ });
14
+ }
15
+ export function buildPutMetricDataCommand(namespace, metricData) {
16
+ return new PutMetricDataCommand({ Namespace: namespace, MetricData: [...metricData] });
17
+ }
@@ -0,0 +1,2 @@
1
+ export declare function getAwsErrorStatus(error: unknown): number | undefined;
2
+ export declare function isAwsThrottlingError(error: unknown): boolean;
@@ -0,0 +1,35 @@
1
+ const THROTTLING_NAMES = new Set([
2
+ 'BandwidthLimitExceeded',
3
+ 'EC2ThrottledException',
4
+ 'LimitExceededException',
5
+ 'PriorRequestNotComplete',
6
+ 'ProvisionedThroughputExceededException',
7
+ 'RequestLimitExceeded',
8
+ 'RequestThrottled',
9
+ 'RequestThrottledException',
10
+ 'ServiceUnavailableException',
11
+ 'SlowDown',
12
+ 'ThrottledException',
13
+ 'Throttling',
14
+ 'ThrottlingException',
15
+ 'TooManyRequestsException',
16
+ ]);
17
+ function asShape(error) {
18
+ return typeof error === 'object' && error !== null ? error : undefined;
19
+ }
20
+ // Returns the HTTP status from an AWS SDK v3 error. Pass it as `getStatus` to queue-errors helpers.
21
+ export function getAwsErrorStatus(error) {
22
+ const status = asShape(error)?.$metadata?.httpStatusCode;
23
+ return typeof status === 'number' ? status : undefined;
24
+ }
25
+ // Detects rate-limit style failures across SES, SQS, Firehose, and CloudWatch error shapes.
26
+ export function isAwsThrottlingError(error) {
27
+ const shape = asShape(error);
28
+ if (!shape)
29
+ return false;
30
+ if (shape.$retryable?.throttling === true)
31
+ return true;
32
+ if (getAwsErrorStatus(error) === 429)
33
+ return true;
34
+ return [shape.name, shape.Code, shape.code].some((value) => typeof value === 'string' && THROTTLING_NAMES.has(value));
35
+ }
@@ -0,0 +1,5 @@
1
+ import { PutRecordBatchCommand, type PutRecordBatchOutput } from '@aws-sdk/client-firehose';
2
+ export declare function encodeJsonRecord(value: unknown, delimiter?: string): Uint8Array;
3
+ export declare function chunkFirehoseRecords(records: readonly Uint8Array[]): Uint8Array[][];
4
+ export declare function buildPutRecordBatchCommand(deliveryStreamName: string, records: readonly Uint8Array[]): PutRecordBatchCommand;
5
+ export declare function getFailedFirehoseRecords(records: readonly Uint8Array[], output: Partial<Pick<PutRecordBatchOutput, 'FailedPutCount' | 'RequestResponses'>>): Uint8Array[];
@@ -0,0 +1,42 @@
1
+ import { PutRecordBatchCommand, } from '@aws-sdk/client-firehose';
2
+ import { byteLength, chunkBySize } from './chunk.mjs';
3
+ const FIREHOSE_MAX_RECORDS_PER_BATCH = 500;
4
+ const FIREHOSE_MAX_BATCH_BYTES = 4 * 1024 * 1024;
5
+ const FIREHOSE_MAX_RECORD_BYTES = 1_000 * 1024;
6
+ // Serializes a value as a delimiter-terminated JSON record (newline by default for S3 sinks).
7
+ export function encodeJsonRecord(value, delimiter = '\n') {
8
+ const json = JSON.stringify(value);
9
+ if (json === undefined)
10
+ throw new TypeError('Value is not JSON serializable');
11
+ return Buffer.from(`${json}${delimiter}`, 'utf8');
12
+ }
13
+ // Splits records by Firehose count and byte limits. A record over the per-record limit throws.
14
+ export function chunkFirehoseRecords(records) {
15
+ return chunkBySize(records, {
16
+ maxItems: FIREHOSE_MAX_RECORDS_PER_BATCH,
17
+ maxBytes: FIREHOSE_MAX_BATCH_BYTES,
18
+ sizeOf: (record) => {
19
+ const size = byteLength(record);
20
+ if (size > FIREHOSE_MAX_RECORD_BYTES) {
21
+ throw new RangeError(`Firehose record of ${size} bytes exceeds ${FIREHOSE_MAX_RECORD_BYTES}`);
22
+ }
23
+ return size;
24
+ },
25
+ });
26
+ }
27
+ export function buildPutRecordBatchCommand(deliveryStreamName, records) {
28
+ const Records = records.map((Data) => ({ Data }));
29
+ return new PutRecordBatchCommand({ DeliveryStreamName: deliveryStreamName, Records });
30
+ }
31
+ // Returns the input records Firehose rejected, aligned by index. The caller decides whether to retry.
32
+ export function getFailedFirehoseRecords(records, output) {
33
+ if (!output.FailedPutCount)
34
+ return [];
35
+ const failed = [];
36
+ for (const [index, response] of (output.RequestResponses ?? []).entries()) {
37
+ const record = records[index];
38
+ if (response.ErrorCode && record)
39
+ failed.push(record);
40
+ }
41
+ return failed;
42
+ }
@@ -0,0 +1,8 @@
1
+ import { NodeHttpHandler, type NodeHttpHandlerOptions } from '@smithy/node-http-handler';
2
+ export declare const AWS_CONNECTION_TIMEOUT_MS = 3000;
3
+ export declare const AWS_SOCKET_TIMEOUT_MS = 10000;
4
+ export declare const AWS_LONG_POLL_SOCKET_TIMEOUT_MS = 25000;
5
+ export declare const AWS_DUALSTACK_CLIENT_CONFIG: {
6
+ readonly useDualstackEndpoint: true;
7
+ };
8
+ export declare function createAwsRequestHandler(overrides?: NodeHttpHandlerOptions): NodeHttpHandler;
@@ -0,0 +1,16 @@
1
+ import { NodeHttpHandler } from '@smithy/node-http-handler';
2
+ export const AWS_CONNECTION_TIMEOUT_MS = 3_000;
3
+ export const AWS_SOCKET_TIMEOUT_MS = 10_000;
4
+ // SQS receives wait up to 20 seconds by protocol; keep the transport idle deadline above that.
5
+ export const AWS_LONG_POLL_SOCKET_TIMEOUT_MS = 25_000;
6
+ // Opt supported clients into dual-stack endpoints explicitly instead of AWS_USE_DUALSTACK_ENDPOINT.
7
+ export const AWS_DUALSTACK_CLIENT_CONFIG = { useDualstackEndpoint: true };
8
+ // Node HTTP handler configured with default connection and socket deadlines. Response-body
9
+ // lifecycle handling beyond the SDK's own timeouts belongs in the application.
10
+ export function createAwsRequestHandler(overrides = {}) {
11
+ return new NodeHttpHandler({
12
+ connectionTimeout: AWS_CONNECTION_TIMEOUT_MS,
13
+ socketTimeout: AWS_SOCKET_TIMEOUT_MS,
14
+ ...overrides,
15
+ });
16
+ }
@@ -0,0 +1,12 @@
1
+ export interface RawEmailOptions {
2
+ source: string;
3
+ to: string | readonly string[];
4
+ replyTo?: string | readonly string[] | undefined;
5
+ subject: string;
6
+ text?: string | undefined;
7
+ html?: string | undefined;
8
+ headers?: Readonly<Record<string, string>> | undefined;
9
+ boundaryPrefix?: string;
10
+ boundary?: string;
11
+ }
12
+ export declare function buildRawEmailMessage(options: RawEmailOptions): string;
@@ -0,0 +1,84 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ function list(value) {
3
+ return typeof value === 'string' ? [value] : [...value];
4
+ }
5
+ function assertSafe(label, value) {
6
+ if (/[\r\n]/.test(value))
7
+ throw new TypeError(`${label} must not contain line breaks`);
8
+ return value;
9
+ }
10
+ // RFC 2046 boundary grammar without the trailing-space allowance.
11
+ const BOUNDARY = /^[0-9A-Za-z'()+_,\-./:=?]{1,70}$/;
12
+ // Folds an address list across lines so no header line nears the 998-character limit.
13
+ function addressHeader(name, value) {
14
+ const addresses = list(value).map((address) => assertSafe(name, address));
15
+ return `${name}: ${addresses.join(',\r\n ')}`;
16
+ }
17
+ function normalizeCrLf(value) {
18
+ return value.replace(/\r\n|\r|\n/g, '\r\n');
19
+ }
20
+ function encodeMimeBody(value) {
21
+ const encoded = Buffer.from(normalizeCrLf(value), 'utf8').toString('base64');
22
+ return (encoded.match(/.{1,76}/g) ?? ['']).join('\r\n');
23
+ }
24
+ // RFC 2047 caps an encoded-word at 75 characters: 45 UTF-8 bytes encode to 60 base64 characters.
25
+ const ENCODED_WORD_MAX_BYTES = 45;
26
+ function encodeHeaderValue(value) {
27
+ if (/^[\x20-\x7E]*$/.test(value))
28
+ return value;
29
+ const words = [];
30
+ let current = '';
31
+ for (const character of value) {
32
+ if (current && Buffer.byteLength(current + character, 'utf8') > ENCODED_WORD_MAX_BYTES) {
33
+ words.push(current);
34
+ current = '';
35
+ }
36
+ current += character;
37
+ }
38
+ words.push(current);
39
+ return words
40
+ .map((word) => `=?UTF-8?B?${Buffer.from(word, 'utf8').toString('base64')}?=`)
41
+ .join('\r\n ');
42
+ }
43
+ // Builds a base64-encoded RFC 5322 message, preserving caller headers such as List-Unsubscribe.
44
+ // Header names and values containing CR or LF are rejected to prevent header injection.
45
+ export function buildRawEmailMessage(options) {
46
+ const headers = [
47
+ `From: ${assertSafe('source', options.source)}`,
48
+ addressHeader('To', options.to),
49
+ ...(options.replyTo ? [addressHeader('Reply-To', options.replyTo)] : []),
50
+ `Subject: ${encodeHeaderValue(assertSafe('subject', options.subject))}`,
51
+ 'MIME-Version: 1.0',
52
+ ...Object.entries(options.headers ?? {}).map(([name, value]) => `${assertSafe('header name', name)}: ${assertSafe('header value', value)}`),
53
+ ];
54
+ if (options.text && options.html) {
55
+ const boundary = options.boundary ?? `${options.boundaryPrefix ?? 'mime'}-${randomUUID()}`;
56
+ if (!BOUNDARY.test(boundary))
57
+ throw new TypeError('Invalid MIME boundary');
58
+ const part = (type, body) => [
59
+ `--${boundary}`,
60
+ `Content-Type: ${type}; charset=UTF-8`,
61
+ 'Content-Transfer-Encoding: base64',
62
+ '',
63
+ encodeMimeBody(body),
64
+ '',
65
+ ];
66
+ return [
67
+ ...headers,
68
+ `Content-Type: multipart/alternative; boundary="${boundary}"`,
69
+ '',
70
+ ...part('text/plain', options.text),
71
+ ...part('text/html', options.html),
72
+ `--${boundary}--`,
73
+ '',
74
+ ].join('\r\n');
75
+ }
76
+ const contentType = options.html ? 'text/html' : 'text/plain';
77
+ return [
78
+ ...headers,
79
+ `Content-Type: ${contentType}; charset=UTF-8`,
80
+ 'Content-Transfer-Encoding: base64',
81
+ '',
82
+ encodeMimeBody(options.html ?? options.text ?? ''),
83
+ ].join('\r\n');
84
+ }
package/dist/ses.d.mts ADDED
@@ -0,0 +1,14 @@
1
+ import { SendEmailCommand, SendRawEmailCommand } from '@aws-sdk/client-ses';
2
+ import { buildRawEmailMessage, type RawEmailOptions } from './ses-mime.mts';
3
+ export { buildRawEmailMessage };
4
+ export declare const SES_CLIENT_CONFIG: {
5
+ readonly useDualstackEndpoint: true;
6
+ readonly maxAttempts: 1;
7
+ };
8
+ export interface SesEmail extends RawEmailOptions {
9
+ bcc?: readonly string[] | undefined;
10
+ configurationSetName?: string | undefined;
11
+ }
12
+ export declare function buildSendRawEmailCommand(email: SesEmail): SendRawEmailCommand;
13
+ export declare function buildSendEmailCommand(email: SesEmail): SendEmailCommand;
14
+ export declare function buildEmailCommand(email: SesEmail): SendEmailCommand | SendRawEmailCommand;
package/dist/ses.mjs ADDED
@@ -0,0 +1,43 @@
1
+ import { SendEmailCommand, SendRawEmailCommand, } from '@aws-sdk/client-ses';
2
+ import { AWS_DUALSTACK_CLIENT_CONFIG } from './request-handler.mjs';
3
+ import { buildRawEmailMessage } from './ses-mime.mjs';
4
+ export { buildRawEmailMessage };
5
+ // SES sends carry no idempotency token, so an SDK retry after an ambiguous timeout can deliver
6
+ // twice. Spread this into the SESClient options; retries then become the caller's decision.
7
+ export const SES_CLIENT_CONFIG = { ...AWS_DUALSTACK_CLIENT_CONFIG, maxAttempts: 1 };
8
+ function toList(value) {
9
+ return typeof value === 'string' ? [value] : [...value];
10
+ }
11
+ // Builds a SendRawEmail command. Both To and Bcc are envelope destinations.
12
+ export function buildSendRawEmailCommand(email) {
13
+ return new SendRawEmailCommand({
14
+ RawMessage: { Data: Buffer.from(buildRawEmailMessage(email), 'utf8') },
15
+ Destinations: [...toList(email.to), ...(email.bcc ?? [])],
16
+ Source: email.source,
17
+ ...(email.configurationSetName ? { ConfigurationSetName: email.configurationSetName } : {}),
18
+ });
19
+ }
20
+ // Builds a structured SendEmail command (no custom headers).
21
+ export function buildSendEmailCommand(email) {
22
+ if (!email.text && !email.html)
23
+ throw new TypeError('SendEmail requires a text or html body');
24
+ const Body = {};
25
+ if (email.text)
26
+ Body.Text = { Charset: 'UTF-8', Data: email.text };
27
+ if (email.html)
28
+ Body.Html = { Charset: 'UTF-8', Data: email.html };
29
+ const input = {
30
+ Destination: { BccAddresses: [...(email.bcc ?? [])], ToAddresses: toList(email.to) },
31
+ Source: email.source,
32
+ Message: { Subject: { Charset: 'UTF-8', Data: email.subject }, Body },
33
+ ...(email.replyTo ? { ReplyToAddresses: toList(email.replyTo) } : {}),
34
+ ...(email.configurationSetName ? { ConfigurationSetName: email.configurationSetName } : {}),
35
+ };
36
+ return new SendEmailCommand(input);
37
+ }
38
+ // Picks SendRawEmail when custom headers are present (SendEmail cannot carry them).
39
+ export function buildEmailCommand(email) {
40
+ return Object.keys(email.headers ?? {}).length > 0
41
+ ? buildSendRawEmailCommand(email)
42
+ : buildSendEmailCommand(email);
43
+ }
package/dist/sqs.d.mts ADDED
@@ -0,0 +1,22 @@
1
+ import { DeleteMessageBatchCommand, ReceiveMessageCommand, SendMessageBatchCommand, type BatchResultErrorEntry, type DeleteMessageBatchRequestEntry, type MessageAttributeValue, type SendMessageBatchRequestEntry } from '@aws-sdk/client-sqs';
2
+ export declare const SQS_CLIENT_CONFIG: {
3
+ readonly useDualstackEndpoint: true;
4
+ readonly useQueueUrlAsEndpoint: false;
5
+ };
6
+ export type SqsAttributeInput = string | number | Uint8Array;
7
+ export declare function encodeMessageAttributes(attributes: Readonly<Record<string, SqsAttributeInput>>): Record<string, MessageAttributeValue>;
8
+ export declare function decodeMessageAttributes(attributes: Readonly<Record<string, MessageAttributeValue>> | undefined): Record<string, SqsAttributeInput>;
9
+ export declare function chunkSendEntries(entries: readonly SendMessageBatchRequestEntry[]): SendMessageBatchRequestEntry[][];
10
+ export declare function chunkDeleteEntries(entries: readonly DeleteMessageBatchRequestEntry[]): DeleteMessageBatchRequestEntry[][];
11
+ export declare function buildSendMessageBatchCommand(queueUrl: string, entries: readonly SendMessageBatchRequestEntry[]): SendMessageBatchCommand;
12
+ export declare function buildDeleteMessageBatchCommand(queueUrl: string, entries: readonly DeleteMessageBatchRequestEntry[]): DeleteMessageBatchCommand;
13
+ export interface ReceiveOptions {
14
+ maxMessages?: number;
15
+ waitTimeSeconds?: number;
16
+ visibilityTimeoutSeconds?: number;
17
+ }
18
+ export declare function buildReceiveMessageCommand(queueUrl: string, options?: ReceiveOptions): ReceiveMessageCommand;
19
+ export declare function classifyBatchFailures(failed: readonly BatchResultErrorEntry[] | undefined): {
20
+ senderFault: BatchResultErrorEntry[];
21
+ retryable: BatchResultErrorEntry[];
22
+ };
package/dist/sqs.mjs ADDED
@@ -0,0 +1,86 @@
1
+ import { DeleteMessageBatchCommand, ReceiveMessageCommand, SendMessageBatchCommand, } from '@aws-sdk/client-sqs';
2
+ import { byteLength, chunkBySize } from './chunk.mjs';
3
+ import { AWS_DUALSTACK_CLIENT_CONFIG } from './request-handler.mjs';
4
+ const SQS_MAX_BATCH_ENTRIES = 10;
5
+ const SQS_MAX_BATCH_BYTES = 1_048_576;
6
+ // Client options for the application's SQSClient. QueueUrls use the IPv4 host, and the SDK default
7
+ // useQueueUrlAsEndpoint would override the resolved dual-stack endpoint on every call.
8
+ export const SQS_CLIENT_CONFIG = {
9
+ ...AWS_DUALSTACK_CLIENT_CONFIG,
10
+ useQueueUrlAsEndpoint: false,
11
+ };
12
+ export function encodeMessageAttributes(attributes) {
13
+ const encoded = {};
14
+ for (const [name, value] of Object.entries(attributes)) {
15
+ if (typeof value === 'string')
16
+ encoded[name] = { DataType: 'String', StringValue: value };
17
+ else if (typeof value === 'number') {
18
+ encoded[name] = { DataType: 'Number', StringValue: String(value) };
19
+ }
20
+ else
21
+ encoded[name] = { DataType: 'Binary', BinaryValue: value };
22
+ }
23
+ return encoded;
24
+ }
25
+ export function decodeMessageAttributes(attributes) {
26
+ const decoded = {};
27
+ for (const [name, attribute] of Object.entries(attributes ?? {})) {
28
+ if (attribute.DataType?.startsWith('Binary') && attribute.BinaryValue) {
29
+ decoded[name] = attribute.BinaryValue;
30
+ }
31
+ else if (attribute.StringValue !== undefined) {
32
+ // Number attributes stay strings: SQS allows 38 digits, which a JS number would round.
33
+ decoded[name] = attribute.StringValue;
34
+ }
35
+ }
36
+ return decoded;
37
+ }
38
+ function entrySize(entry) {
39
+ let size = byteLength(entry.MessageBody ?? '');
40
+ for (const [name, value] of Object.entries(entry.MessageAttributes ?? {})) {
41
+ size += byteLength(name) + byteLength(value.DataType ?? '');
42
+ size += value.BinaryValue ? value.BinaryValue.byteLength : byteLength(value.StringValue ?? '');
43
+ }
44
+ return size;
45
+ }
46
+ // Splits entries into SendMessageBatch-sized groups (10 entries, 1 MiB). Oversized entries throw.
47
+ export function chunkSendEntries(entries) {
48
+ return chunkBySize(entries, {
49
+ maxItems: SQS_MAX_BATCH_ENTRIES,
50
+ maxBytes: SQS_MAX_BATCH_BYTES,
51
+ sizeOf: entrySize,
52
+ });
53
+ }
54
+ export function chunkDeleteEntries(entries) {
55
+ return chunkBySize(entries, {
56
+ maxItems: SQS_MAX_BATCH_ENTRIES,
57
+ maxBytes: Number.MAX_SAFE_INTEGER,
58
+ sizeOf: () => 0,
59
+ });
60
+ }
61
+ export function buildSendMessageBatchCommand(queueUrl, entries) {
62
+ return new SendMessageBatchCommand({ QueueUrl: queueUrl, Entries: [...entries] });
63
+ }
64
+ export function buildDeleteMessageBatchCommand(queueUrl, entries) {
65
+ return new DeleteMessageBatchCommand({ QueueUrl: queueUrl, Entries: [...entries] });
66
+ }
67
+ // One receive call, long-polling by default (20s). Pair with AWS_LONG_POLL_SOCKET_TIMEOUT_MS.
68
+ export function buildReceiveMessageCommand(queueUrl, options = {}) {
69
+ return new ReceiveMessageCommand({
70
+ QueueUrl: queueUrl,
71
+ MaxNumberOfMessages: options.maxMessages ?? SQS_MAX_BATCH_ENTRIES,
72
+ WaitTimeSeconds: options.waitTimeSeconds ?? 20,
73
+ MessageAttributeNames: ['All'],
74
+ ...(options.visibilityTimeoutSeconds === undefined
75
+ ? {}
76
+ : { VisibilityTimeout: options.visibilityTimeoutSeconds }),
77
+ });
78
+ }
79
+ // Splits a batch result's failures into sender faults (do not retry) and the rest.
80
+ export function classifyBatchFailures(failed) {
81
+ const senderFault = [];
82
+ const retryable = [];
83
+ for (const entry of failed ?? [])
84
+ (entry.SenderFault ? senderFault : retryable).push(entry);
85
+ return { senderFault, retryable };
86
+ }
package/package.json CHANGED
@@ -1,6 +1,95 @@
1
1
  {
2
2
  "name": "@vouchington/aws",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "description": "AWS SDK v3 command builders, batching, codecs, and error classifiers for SES, SQS, Firehose, and CloudWatch.",
5
+ "homepage": "https://github.com/vouchington/vouchington-platform/tree/main/packages/aws#readme",
6
+ "bugs": {
7
+ "url": "https://github.com/vouchington/vouchington-platform/issues"
8
+ },
9
+ "license": "MIT",
10
+ "author": "Jonathan Ong",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/vouchington/vouchington-platform.git",
14
+ "directory": "packages/aws"
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "type": "module",
22
+ "exports": {
23
+ "./ses": {
24
+ "types": "./dist/ses.d.mts",
25
+ "import": "./dist/ses.mjs",
26
+ "default": "./dist/ses.mjs"
27
+ },
28
+ "./sqs": {
29
+ "types": "./dist/sqs.d.mts",
30
+ "import": "./dist/sqs.mjs",
31
+ "default": "./dist/sqs.mjs"
32
+ },
33
+ "./firehose": {
34
+ "types": "./dist/firehose.d.mts",
35
+ "import": "./dist/firehose.mjs",
36
+ "default": "./dist/firehose.mjs"
37
+ },
38
+ "./cloudwatch": {
39
+ "types": "./dist/cloudwatch.d.mts",
40
+ "import": "./dist/cloudwatch.mjs",
41
+ "default": "./dist/cloudwatch.mjs"
42
+ },
43
+ "./request-handler": {
44
+ "types": "./dist/request-handler.d.mts",
45
+ "import": "./dist/request-handler.mjs",
46
+ "default": "./dist/request-handler.mjs"
47
+ },
48
+ "./errors": {
49
+ "types": "./dist/errors.d.mts",
50
+ "import": "./dist/errors.mjs",
51
+ "default": "./dist/errors.mjs"
52
+ }
53
+ },
54
+ "publishConfig": {
55
+ "access": "public"
56
+ },
57
+ "scripts": {
58
+ "build": "tsc --project tsconfig.build.json",
59
+ "prepack": "pnpm run build"
60
+ },
61
+ "devDependencies": {
62
+ "@aws-sdk/client-cloudwatch": "^3.1152.0",
63
+ "@aws-sdk/client-firehose": "^3.1152.0",
64
+ "@aws-sdk/client-ses": "^3.1152.0",
65
+ "@aws-sdk/client-sqs": "^3.1152.0",
66
+ "@smithy/node-http-handler": "^4.12.1"
67
+ },
68
+ "peerDependencies": {
69
+ "@aws-sdk/client-cloudwatch": "^3.1152.0",
70
+ "@aws-sdk/client-firehose": "^3.1152.0",
71
+ "@aws-sdk/client-ses": "^3.1152.0",
72
+ "@aws-sdk/client-sqs": "^3.1152.0",
73
+ "@smithy/node-http-handler": "^4.12.1"
74
+ },
75
+ "peerDependenciesMeta": {
76
+ "@aws-sdk/client-cloudwatch": {
77
+ "optional": true
78
+ },
79
+ "@aws-sdk/client-firehose": {
80
+ "optional": true
81
+ },
82
+ "@aws-sdk/client-ses": {
83
+ "optional": true
84
+ },
85
+ "@aws-sdk/client-sqs": {
86
+ "optional": true
87
+ },
88
+ "@smithy/node-http-handler": {
89
+ "optional": true
90
+ }
91
+ },
92
+ "engines": {
93
+ "node": ">=24.0.0"
94
+ }
95
+ }