@aligent/aws-wrappers 0.5.9 → 0.5.11

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.
Files changed (71) hide show
  1. package/README.md +78 -10
  2. package/cjs/index.cjs +427 -133
  3. package/cjs/package.json +3 -2
  4. package/cjs/src/dynamodb/dynamodb.d.ts +23 -4
  5. package/cjs/src/dynamodb/dynamodb.d.ts.map +1 -1
  6. package/cjs/src/eventbridge/eventbridge.d.ts.map +1 -1
  7. package/cjs/src/index.d.ts +1 -0
  8. package/cjs/src/index.d.ts.map +1 -1
  9. package/cjs/src/s3/s3.d.ts +6 -1
  10. package/cjs/src/s3/s3.d.ts.map +1 -1
  11. package/cjs/src/secrets-manager/secrets-manager.d.ts +3 -1
  12. package/cjs/src/secrets-manager/secrets-manager.d.ts.map +1 -1
  13. package/cjs/src/ses/ses.d.ts +64 -0
  14. package/cjs/src/ses/ses.d.ts.map +1 -0
  15. package/cjs/src/sns/sns.d.ts +8 -5
  16. package/cjs/src/sns/sns.d.ts.map +1 -1
  17. package/cjs/src/sqs/sqs.d.ts +7 -3
  18. package/cjs/src/sqs/sqs.d.ts.map +1 -1
  19. package/cjs/src/ssm/ssm.d.ts +3 -1
  20. package/cjs/src/ssm/ssm.d.ts.map +1 -1
  21. package/cjs/src/util/batch-operation-error.d.ts +19 -2
  22. package/cjs/src/util/batch-operation-error.d.ts.map +1 -1
  23. package/cjs/src/util/chunk.d.ts +8 -0
  24. package/cjs/src/util/chunk.d.ts.map +1 -1
  25. package/cjs/src/util/json.d.ts +14 -0
  26. package/cjs/src/util/json.d.ts.map +1 -0
  27. package/docs/index/classes/APIGatewayService.md +6 -6
  28. package/docs/index/classes/APIGatewayV2Service.md +5 -5
  29. package/docs/index/classes/BatchOperationError.md +15 -6
  30. package/docs/index/classes/DynamoDBService.md +39 -16
  31. package/docs/index/classes/EventBridgeService.md +3 -3
  32. package/docs/index/classes/LambdaFunctionError.md +7 -7
  33. package/docs/index/classes/LambdaService.md +3 -3
  34. package/docs/index/classes/S3Service.md +24 -16
  35. package/docs/index/classes/SESService.md +123 -0
  36. package/docs/index/classes/SNSService.md +12 -9
  37. package/docs/index/classes/SQSService.md +14 -10
  38. package/docs/index/classes/SSMService.md +10 -8
  39. package/docs/index/classes/SchedulerService.md +11 -11
  40. package/docs/index/classes/SecretsManagerService.md +11 -9
  41. package/docs/index/classes/StepFunctionsService.md +6 -6
  42. package/docs/index/interfaces/BatchFailedEntry.md +6 -5
  43. package/docs/index/interfaces/EmptyBucketPageResult.md +2 -2
  44. package/docs/index/modules.md +1 -0
  45. package/docs/testing/testing/functions/createMockService.md +1 -1
  46. package/esm/index.mjs +428 -135
  47. package/esm/package.json +3 -2
  48. package/esm/src/dynamodb/dynamodb.d.ts +23 -4
  49. package/esm/src/dynamodb/dynamodb.d.ts.map +1 -1
  50. package/esm/src/eventbridge/eventbridge.d.ts.map +1 -1
  51. package/esm/src/index.d.ts +1 -0
  52. package/esm/src/index.d.ts.map +1 -1
  53. package/esm/src/s3/s3.d.ts +6 -1
  54. package/esm/src/s3/s3.d.ts.map +1 -1
  55. package/esm/src/secrets-manager/secrets-manager.d.ts +3 -1
  56. package/esm/src/secrets-manager/secrets-manager.d.ts.map +1 -1
  57. package/esm/src/ses/ses.d.ts +64 -0
  58. package/esm/src/ses/ses.d.ts.map +1 -0
  59. package/esm/src/sns/sns.d.ts +8 -5
  60. package/esm/src/sns/sns.d.ts.map +1 -1
  61. package/esm/src/sqs/sqs.d.ts +7 -3
  62. package/esm/src/sqs/sqs.d.ts.map +1 -1
  63. package/esm/src/ssm/ssm.d.ts +3 -1
  64. package/esm/src/ssm/ssm.d.ts.map +1 -1
  65. package/esm/src/util/batch-operation-error.d.ts +19 -2
  66. package/esm/src/util/batch-operation-error.d.ts.map +1 -1
  67. package/esm/src/util/chunk.d.ts +8 -0
  68. package/esm/src/util/chunk.d.ts.map +1 -1
  69. package/esm/src/util/json.d.ts +14 -0
  70. package/esm/src/util/json.d.ts.map +1 -0
  71. package/package.json +3 -2
package/cjs/index.cjs CHANGED
@@ -12,6 +12,7 @@ var clientS3 = require('@aws-sdk/client-s3');
12
12
  var s3RequestPresigner = require('@aws-sdk/s3-request-presigner');
13
13
  var clientScheduler = require('@aws-sdk/client-scheduler');
14
14
  var clientSecretsManager = require('@aws-sdk/client-secrets-manager');
15
+ var clientSesv2 = require('@aws-sdk/client-sesv2');
15
16
  var clientSfn = require('@aws-sdk/client-sfn');
16
17
  var clientSns = require('@aws-sdk/client-sns');
17
18
  var clientSqs = require('@aws-sdk/client-sqs');
@@ -145,6 +146,110 @@ class APIGatewayService {
145
146
  }
146
147
  }
147
148
 
149
+ /**
150
+ * Thrown by the batch methods once every chunk has been sent and at least one
151
+ * entry was rejected.
152
+ *
153
+ * `results` holds the raw SDK output of every chunk, so the outputs of the
154
+ * entries that succeeded (message ids, sequence numbers) stay readable. The
155
+ * exceptions are `S3.emptyBucket`, whose `results` are per-page deleted keys,
156
+ * `SSM.getParameters`, whose `results` are empty, and the DynamoDB batch
157
+ * methods, whose `results` hold a single output (the last response, with the
158
+ * `Responses` merged so far for `batchGet`) carrying what is still pending.
159
+ * `failed` is the normalised list of rejected entries across all chunks.
160
+ *
161
+ * Do not pass the error object itself to a logger. `results` is an enumerable
162
+ * property and the Powertools logger serialises every enumerable property of
163
+ * an error, so `logger.error('…', error)` writes `results` to the log — which
164
+ * for the DynamoDB batch methods holds the caller's keys and items. Log `name`,
165
+ * `message` and `failed`, which never carry a payload, and read `results` only
166
+ * to retry or recover.
167
+ *
168
+ * Match on `name` rather than `instanceof` if both the CJS and ESM builds of
169
+ * this package may be loaded in one process.
170
+ */
171
+ class BatchOperationError extends Error {
172
+ results;
173
+ failed;
174
+ name = 'BatchOperationError';
175
+ constructor(results, failed) {
176
+ super(failureMessage(failed));
177
+ this.results = results;
178
+ this.failed = failed;
179
+ }
180
+ }
181
+ function failureMessage(failed) {
182
+ const noun = failed.length === 1 ? 'entry' : 'entries';
183
+ const codes = distinctCodes(failed);
184
+ const suffix = codes.length === 0 ? '' : ` (${codes.join(', ')})`;
185
+ return `Batch operation failed for ${failed.length} ${noun}${suffix}`;
186
+ }
187
+ /**
188
+ * SQS and SNS report rejected entries under `Failed` on an otherwise
189
+ * successful response, so a resolved chunk does not mean every entry was
190
+ * accepted. Extracts those entries and delegates to {@link throwIfAny}.
191
+ *
192
+ * Only id, code and message are copied out — never the entry itself — so
193
+ * neither the error nor the warning can leak a payload.
194
+ */
195
+ function throwIfAnyFailed(logger, operation, results) {
196
+ const failed = results.flatMap(result => (result.Failed ?? []).map(({ Id, Code, Message }) => ({
197
+ id: Id,
198
+ code: Code,
199
+ message: Message,
200
+ })));
201
+ return throwIfAny(logger, operation, results, failed);
202
+ }
203
+ /**
204
+ * S3 reports undeleted keys under `Errors` on an otherwise successful
205
+ * `DeleteObjects` response. Same contract as {@link throwIfAnyFailed}; the
206
+ * key is carried as the failed entry's `id`, and `VersionId` is dropped.
207
+ */
208
+ function throwIfAnyDeleteErrors(logger, operation, results) {
209
+ const failed = results.flatMap(result => (result.Errors ?? []).map(({ Key, Code, Message }) => ({
210
+ id: Key,
211
+ code: Code,
212
+ message: Message,
213
+ })));
214
+ return throwIfAny(logger, operation, results, failed);
215
+ }
216
+ /**
217
+ * Warn-and-throw step for services whose responses don't use the SQS/SNS
218
+ * `Failed` shape and so extract their own rejected entries (`EventBridge.putEvents`),
219
+ * or whose `results` aren't a plain list of SDK outputs (`S3.emptyBucket`).
220
+ * Returns `results` untouched when `failed` is empty.
221
+ *
222
+ * Callers must build `failed` by copying id, code and message explicitly —
223
+ * never by spreading the SDK entry — because it goes straight into the error
224
+ * and the warning.
225
+ */
226
+ function throwIfAny(logger, operation, results, failed) {
227
+ if (failed.length === 0)
228
+ return results;
229
+ return throwBatchFailure(logger, operation, results, failed);
230
+ }
231
+ /**
232
+ * The warn-and-throw half of {@link throwIfAny}, for callers that already know
233
+ * `failed` is non-empty and need the compiler to see that the call never
234
+ * returns. The same rule applies: build `failed` by copying id, code and
235
+ * message explicitly.
236
+ */
237
+ function throwBatchFailure(logger, operation, results, failed) {
238
+ logger.warn(`${operation} had rejected entries`, {
239
+ failedCount: failed.length,
240
+ codes: distinctCodes(failed),
241
+ });
242
+ throw new BatchOperationError(results, failed);
243
+ }
244
+ /**
245
+ * Distinct error codes in first-seen order, for the error message and the
246
+ * warning log line.
247
+ */
248
+ function distinctCodes(failed) {
249
+ const codes = failed.flatMap(entry => (entry.code === undefined ? [] : [entry.code]));
250
+ return [...new Set(codes)];
251
+ }
252
+
148
253
  /**
149
254
  * Whether the logger is verbose enough that full SDK inputs may be written to
150
255
  * the log. The unlock rule is documented on {@link redactInput}.
@@ -180,6 +285,29 @@ const BATCH_GET_BASE_DELAY_MS = 200;
180
285
  function summariseTables(input) {
181
286
  return { tables: Object.keys(input.RequestItems ?? {}) };
182
287
  }
288
+ /**
289
+ * The tables that still have unprocessed keys or writes. Tables whose list is
290
+ * empty are dropped, so an empty result means there is nothing left to retry.
291
+ */
292
+ function pendingCounts(unprocessed, countOf) {
293
+ return Object.entries(unprocessed)
294
+ .map(([table, entry]) => ({ table, count: countOf(entry) ?? 0 }))
295
+ .filter(({ count }) => count > 0);
296
+ }
297
+ /**
298
+ * One failed entry per request still unprocessed after the final attempt. The
299
+ * `id` is the table name plus the position within that table's unprocessed
300
+ * list — deliberately not the key or item, which is caller data and must not
301
+ * reach the error message or the warning. The position indexes into the
302
+ * `UnprocessedKeys` / `UnprocessedItems` the error carries in `results`.
303
+ */
304
+ function unprocessedEntries(pending, code, attempts) {
305
+ return pending.flatMap(({ table, count }) => Array.from({ length: count }, (_, index) => ({
306
+ id: `${table}[${index}]`,
307
+ code,
308
+ message: `Still unprocessed after ${attempts} attempts`,
309
+ })));
310
+ }
183
311
  /**
184
312
  * Fields safe to log at INFO. Omits `Key` (may carry customer IDs / tenant IDs).
185
313
  */
@@ -396,63 +524,101 @@ class DynamoDBService {
396
524
  /**
397
525
  * Batch-get items from one or more DynamoDB tables, retrying
398
526
  * `UnprocessedKeys` with jittered exponential backoff. Up to 5 attempts
399
- * (200ms base delay). Throws when keys remain unprocessed after the final
400
- * attempt. `Responses` are merged across attempts, keyed by table name.
527
+ * (200ms base delay). `Responses` are merged across attempts, keyed by
528
+ * table name.
401
529
  *
402
530
  * Note: this method is intentionally **not** generic. `BatchGet`'s
403
531
  * `Responses` field is a multi-table `Record<string, item[]>` whose item
404
532
  * shapes can differ per table — no single `T` can soundly describe it.
405
533
  * Callers should narrow the result type at the call site.
534
+ *
535
+ * @throws {@link BatchOperationError} when keys remain unprocessed after
536
+ * the final attempt. `results` holds one output: the merged `Responses`
537
+ * retrieved so far, plus the still-pending `UnprocessedKeys` to retry.
538
+ * `failed` has one entry per pending key with `code: 'UnprocessedKeys'`
539
+ * and an `id` of `<table>[<index>]`, the key's position in
540
+ * `results[0].UnprocessedKeys[<table>].Keys`. The `failed` list never
541
+ * carries key values; `results` does, as it is data the caller requested,
542
+ * so don't log the error object itself (see {@link BatchOperationError}).
543
+ * Request-level SDK exceptions propagate unchanged.
406
544
  */
407
545
  async batchGet(input) {
408
546
  this.logger.info('Batch getting DynamoDB items', {
409
547
  input: redactInput(this.logger, input, summariseTables),
410
548
  });
411
- let current = input;
412
549
  const mergedResponses = {};
413
- for (let attempt = 0; attempt < BATCH_GET_MAX_ATTEMPTS; attempt++) {
414
- const response = await this.client.send(new libDynamodb.BatchGetCommand(current));
550
+ const attempt = async (request) => {
551
+ const response = await this.client.send(new libDynamodb.BatchGetCommand(request));
415
552
  for (const [table, items] of Object.entries(response.Responses ?? {})) {
416
553
  mergedResponses[table] = [...(mergedResponses[table] ?? []), ...items];
417
554
  }
418
- const unprocessed = response.UnprocessedKeys;
419
- if (!unprocessed || Object.keys(unprocessed).length === 0) {
420
- return { ...response, Responses: mergedResponses };
421
- }
555
+ const unprocessed = response.UnprocessedKeys ?? {};
556
+ return {
557
+ output: { ...response, Responses: mergedResponses },
558
+ unprocessed,
559
+ pending: pendingCounts(unprocessed, ({ Keys }) => Keys?.length),
560
+ };
561
+ };
562
+ let current = input;
563
+ for (let attemptNumber = 1; attemptNumber < BATCH_GET_MAX_ATTEMPTS; attemptNumber++) {
564
+ const { output, unprocessed, pending } = await attempt(current);
565
+ if (pending.length === 0)
566
+ return output;
422
567
  this.logger.warn('Retrying unprocessed DynamoDB items', {
423
- attempt: attempt + 1,
424
- tables: Object.keys(unprocessed),
568
+ attempt: attemptNumber,
569
+ tables: pending.map(({ table }) => table),
425
570
  });
426
- if (attempt < BATCH_GET_MAX_ATTEMPTS - 1)
427
- await sleep(backoffDelay(attempt, BATCH_GET_BASE_DELAY_MS));
571
+ await sleep(backoffDelay(attemptNumber - 1, BATCH_GET_BASE_DELAY_MS));
428
572
  current = { ...input, RequestItems: unprocessed };
429
573
  }
430
- throw new Error(`batchGet failed after ${BATCH_GET_MAX_ATTEMPTS} attempts`);
574
+ const { output, pending } = await attempt(current);
575
+ if (pending.length === 0)
576
+ return output;
577
+ return throwBatchFailure(this.logger, 'DynamoDB batchGet', [output], unprocessedEntries(pending, 'UnprocessedKeys', BATCH_GET_MAX_ATTEMPTS));
431
578
  }
432
579
  /**
433
580
  * Batch-write items to DynamoDB, retrying `UnprocessedItems` with jittered
434
- * exponential backoff. Up to 5 attempts (200ms base delay). Throws when
435
- * items remain unprocessed after the final attempt.
581
+ * exponential backoff. Up to 5 attempts (200ms base delay).
582
+ *
583
+ * @throws {@link BatchOperationError} when items remain unprocessed after
584
+ * the final attempt. `results` holds one output: the last response, whose
585
+ * `UnprocessedItems` are the writes still to retry. `failed` has one entry
586
+ * per pending write with `code: 'UnprocessedItems'` and an `id` of
587
+ * `<table>[<index>]`, the write's position in
588
+ * `results[0].UnprocessedItems[<table>]`. The `failed` list never carries
589
+ * item data; `results` does, as it is data the caller supplied, so don't
590
+ * log the error object itself (see {@link BatchOperationError}).
591
+ * Request-level SDK exceptions propagate unchanged.
436
592
  */
437
593
  async batchWrite(input) {
438
594
  this.logger.info('Batch writing DynamoDB items', {
439
595
  input: redactInput(this.logger, input, summariseTables),
440
596
  });
597
+ const attempt = async (request) => {
598
+ const response = await this.client.send(new libDynamodb.BatchWriteCommand(request));
599
+ const unprocessed = response.UnprocessedItems ?? {};
600
+ return {
601
+ response,
602
+ unprocessed,
603
+ pending: pendingCounts(unprocessed, writes => writes.length),
604
+ };
605
+ };
441
606
  let current = input;
442
- for (let attempt = 0; attempt < BATCH_WRITE_MAX_ATTEMPTS; attempt++) {
443
- const response = await this.client.send(new libDynamodb.BatchWriteCommand(current));
444
- const unprocessed = response.UnprocessedItems;
445
- if (!unprocessed || Object.keys(unprocessed).length === 0)
607
+ for (let attemptNumber = 1; attemptNumber < BATCH_WRITE_MAX_ATTEMPTS; attemptNumber++) {
608
+ const { response, unprocessed, pending } = await attempt(current);
609
+ if (pending.length === 0)
446
610
  return response;
447
611
  this.logger.warn('Retrying unprocessed DynamoDB items', {
448
- attempt: attempt + 1,
449
- tables: Object.keys(unprocessed),
612
+ attempt: attemptNumber,
613
+ tables: pending.map(({ table }) => table),
450
614
  });
451
- if (attempt < BATCH_WRITE_MAX_ATTEMPTS - 1)
452
- await sleep(backoffDelay(attempt, BATCH_WRITE_BASE_DELAY_MS));
615
+ await sleep(backoffDelay(attemptNumber - 1, BATCH_WRITE_BASE_DELAY_MS));
453
616
  current = { ...input, RequestItems: unprocessed };
454
617
  }
455
- throw new Error(`batchWrite failed after ${BATCH_WRITE_MAX_ATTEMPTS} attempts`);
618
+ const { response, pending } = await attempt(current);
619
+ if (pending.length === 0)
620
+ return response;
621
+ return throwBatchFailure(this.logger, 'DynamoDB batchWrite', [response], unprocessedEntries(pending, 'UnprocessedItems', BATCH_WRITE_MAX_ATTEMPTS));
456
622
  }
457
623
  /**
458
624
  * Paginate over Query results, yielding one unmarshalled item at a time.
@@ -515,86 +681,6 @@ class DynamoDBService {
515
681
  }
516
682
  }
517
683
 
518
- /**
519
- * Thrown by the batch methods once every chunk has been sent and at least one
520
- * entry was rejected.
521
- *
522
- * `results` holds the raw SDK output of every chunk, so the outputs of the
523
- * entries that succeeded (message ids, sequence numbers) stay readable. The
524
- * exceptions are `S3.emptyBucket`, whose `results` are per-page deleted keys,
525
- * and `SSM.getParameters`, whose `results` are empty.
526
- * `failed` is the normalised list of rejected entries across all chunks.
527
- *
528
- * Match on `name` rather than `instanceof` if both the CJS and ESM builds of
529
- * this package may be loaded in one process.
530
- */
531
- class BatchOperationError extends Error {
532
- results;
533
- failed;
534
- name = 'BatchOperationError';
535
- constructor(results, failed) {
536
- super(`Batch operation failed for ${failed.length} entries (${distinctCodes(failed).join(', ')})`);
537
- this.results = results;
538
- this.failed = failed;
539
- }
540
- }
541
- /**
542
- * SQS and SNS report rejected entries under `Failed` on an otherwise
543
- * successful response, so a resolved chunk does not mean every entry was
544
- * accepted. Extracts those entries and delegates to {@link throwIfAny}.
545
- *
546
- * Only id, code and message are copied out — never the entry itself — so
547
- * neither the error nor the warning can leak a payload.
548
- */
549
- function throwIfAnyFailed(logger, operation, results) {
550
- const failed = results.flatMap(result => (result.Failed ?? []).map(({ Id, Code, Message }) => ({
551
- id: Id,
552
- code: Code,
553
- message: Message,
554
- })));
555
- return throwIfAny(logger, operation, results, failed);
556
- }
557
- /**
558
- * S3 reports undeleted keys under `Errors` on an otherwise successful
559
- * `DeleteObjects` response. Same contract as {@link throwIfAnyFailed}; the
560
- * key is carried as the failed entry's `id`, and `VersionId` is dropped.
561
- */
562
- function throwIfAnyDeleteErrors(logger, operation, results) {
563
- const failed = results.flatMap(result => (result.Errors ?? []).map(({ Key, Code, Message }) => ({
564
- id: Key,
565
- code: Code,
566
- message: Message,
567
- })));
568
- return throwIfAny(logger, operation, results, failed);
569
- }
570
- /**
571
- * Warn-and-throw step for services whose responses don't use the SQS/SNS
572
- * `Failed` shape and so extract their own rejected entries (`EventBridge.putEvents`),
573
- * or whose `results` aren't a plain list of SDK outputs (`S3.emptyBucket`).
574
- * Returns `results` untouched when `failed` is empty.
575
- *
576
- * Callers must build `failed` by copying id, code and message explicitly —
577
- * never by spreading the SDK entry — because it goes straight into the error
578
- * and the warning.
579
- */
580
- function throwIfAny(logger, operation, results, failed) {
581
- if (failed.length === 0)
582
- return results;
583
- logger.warn(`${operation} had rejected entries`, {
584
- failedCount: failed.length,
585
- codes: distinctCodes(failed),
586
- });
587
- throw new BatchOperationError(results, failed);
588
- }
589
- /**
590
- * Distinct error codes in first-seen order, for the error message and the
591
- * warning log line.
592
- */
593
- function distinctCodes(failed) {
594
- const codes = failed.flatMap(entry => (entry.code === undefined ? [] : [entry.code]));
595
- return [...new Set(codes)];
596
- }
597
-
598
684
  /**
599
685
  * Split a list into consecutive chunks of at most `size` items, mirroring the
600
686
  * per-request caps the AWS APIs enforce on batch operations.
@@ -606,6 +692,16 @@ function chunk(items, size) {
606
692
  }
607
693
  return chunks;
608
694
  }
695
+ /**
696
+ * The index, as a string, that an entry had in the list `chunk` split, given
697
+ * its chunk number and its position within that chunk. Batch operations whose
698
+ * entries carry no identifier of their own report failures by this index.
699
+ * `chunk` fills every chunk but the last, so the chunk's offset is the chunk
700
+ * number times the chunk size.
701
+ */
702
+ function originalIndex(chunkIndex, chunkSize, position) {
703
+ return String(chunkIndex * chunkSize + position);
704
+ }
609
705
 
610
706
  const PUT_EVENTS_LIMIT = 10;
611
707
  /**
@@ -615,13 +711,8 @@ const PUT_EVENTS_LIMIT = 10;
615
711
  function summariseEntries$1({ EndpointId, Entries }) {
616
712
  return { EndpointId, entryCount: Entries?.length ?? 0 };
617
713
  }
618
- /**
619
- * Chunks are full except the last, so the caller's original index of a
620
- * rejected entry is the chunk's offset (chunk number times the chunk size)
621
- * plus its position within the chunk.
622
- */
623
714
  function extractPutEventsFailures(results) {
624
- return results.flatMap((result, chunkIndex) => extractChunkFailures(result, chunkIndex * PUT_EVENTS_LIMIT));
715
+ return results.flatMap(extractChunkFailures);
625
716
  }
626
717
  /**
627
718
  * `PutEvents` reports a rejected entry by an error code on the result entry at
@@ -630,10 +721,10 @@ function extractPutEventsFailures(results) {
630
721
  * Copies only code and message out, never the request entry, so neither the
631
722
  * error nor the warning can carry event detail.
632
723
  */
633
- function extractChunkFailures(result, offset) {
724
+ function extractChunkFailures(result, chunkIndex) {
634
725
  return (result.Entries ?? [])
635
726
  .map(({ ErrorCode, ErrorMessage }, position) => ({
636
- id: String(offset + position),
727
+ id: originalIndex(chunkIndex, PUT_EVENTS_LIMIT, position),
637
728
  code: ErrorCode,
638
729
  message: ErrorMessage,
639
730
  }))
@@ -836,8 +927,34 @@ class LambdaService {
836
927
  }
837
928
  }
838
929
 
930
+ /**
931
+ * `JSON.parse` that never leaks the parsed text. V8's `SyntaxError` message
932
+ * embeds a snippet of the input (`Unexpected token 'h', ..."assword": hunter2}"
933
+ * is not valid JSON`), and the wrappers parse secrets and stored objects, so
934
+ * letting it through would put that content into the caller's error logs.
935
+ *
936
+ * The original error is deliberately not attached as `cause`: loggers serialise
937
+ * `cause` and its message carries the snippet. `context` should identify the
938
+ * source (a secret id, a bucket and key) so the failure is still diagnosable.
939
+ *
940
+ * @throws An `Error` naming `context`, without any of the input text.
941
+ */
942
+ function parseJson(text, context) {
943
+ try {
944
+ return JSON.parse(text);
945
+ }
946
+ catch {
947
+ throw new Error(`${context} does not contain valid JSON`);
948
+ }
949
+ }
950
+
839
951
  const DEFAULT_PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
840
952
  const DELETE_OBJECTS_BATCH_LIMIT = 1000;
953
+ /**
954
+ * `Key` is `string | undefined` here because the SDK types a required `Key`
955
+ * that way even through `Required<Pick<...>>`.
956
+ */
957
+ const parseJsonObject = (body, bucket, key) => parseJson(body, `S3 object s3://${bucket}/${key}`);
841
958
  /**
842
959
  * Fields safe to log at INFO for `putObject`. Omits `Body` (object payload).
843
960
  */
@@ -932,13 +1049,15 @@ class S3Service {
932
1049
  * Get an object from S3 and parse it as JSON.
933
1050
  * @template T - Expected type of the parsed value.
934
1051
  * @returns The parsed value, or `undefined` if the response has no body.
935
- * @throws If the body is non-empty and not valid JSON.
1052
+ * @throws If the body is non-empty and not valid JSON. The error names the
1053
+ * object and never includes any of its content, unlike the native
1054
+ * `SyntaxError`.
936
1055
  */
937
1056
  async getJsonObject(input) {
938
1057
  this.logger.info('Getting S3 JSON object', { input });
939
1058
  const response = await this.client.send(new clientS3.GetObjectCommand(input));
940
1059
  const body = await response.Body?.transformToString();
941
- return body ? JSON.parse(body) : undefined;
1060
+ return body ? parseJsonObject(body, input.Bucket, input.Key) : undefined;
942
1061
  }
943
1062
  /**
944
1063
  * Fetch the metadata for an S3 object without downloading its body.
@@ -968,6 +1087,9 @@ class S3Service {
968
1087
  * List and JSON-parse every object under a bucket and optional prefix.
969
1088
  * Auto-paginated. Objects without a body are skipped.
970
1089
  * @template T - Expected type of each parsed object.
1090
+ * @throws If any object is not valid JSON. The error names that object's
1091
+ * key and never includes any of its content, unlike the native
1092
+ * `SyntaxError`; objects after it are not fetched.
971
1093
  */
972
1094
  async getAllObjects(bucket, prefix) {
973
1095
  this.logger.info('Getting all S3 objects', { input: { bucket, prefix } });
@@ -980,7 +1102,7 @@ class S3Service {
980
1102
  const response = await this.client.send(new clientS3.GetObjectCommand({ Bucket: bucket, Key: object.Key }));
981
1103
  const body = await response.Body?.transformToString();
982
1104
  if (body)
983
- bodies.push(JSON.parse(body));
1105
+ bodies.push(parseJsonObject(body, bucket, object.Key));
984
1106
  }
985
1107
  }
986
1108
  return bodies;
@@ -1325,12 +1447,14 @@ class SecretsManagerService {
1325
1447
  * @param secretId - The ARN or friendly name of the secret.
1326
1448
  * @template T - Expected shape of the parsed secret.
1327
1449
  * @returns The parsed secret value.
1328
- * @throws If the secret has no `SecretString` or the value is not valid JSON.
1450
+ * @throws If the secret has no `SecretString`, or the value is not valid
1451
+ * JSON. The latter error names the secret and never includes any of its
1452
+ * value, unlike the native `SyntaxError`.
1329
1453
  */
1330
1454
  async getJsonSecret(secretId) {
1331
1455
  this.logger.info('Fetching JSON secret', { input: { secretId } });
1332
1456
  const secretString = await this.fetchSecretString(secretId);
1333
- return JSON.parse(secretString);
1457
+ return parseJson(secretString, `Secret '${secretId}'`);
1334
1458
  }
1335
1459
  /**
1336
1460
  * Create a new secret. At INFO level the log line includes only identity
@@ -1391,6 +1515,139 @@ class SecretsManagerService {
1391
1515
  }
1392
1516
  }
1393
1517
 
1518
+ const SEND_BULK_EMAIL_LIMIT = 50;
1519
+ /**
1520
+ * Sent entries whose result isn't `SUCCESS`, identified by their original
1521
+ * index in the caller's `BulkEmailEntries`. Walks the entries that were sent
1522
+ * rather than the results that came back, so an entry SES returned no result
1523
+ * for counts as failed instead of passing unnoticed. Only status and error are
1524
+ * copied out, never the entry, so no destination can leak.
1525
+ */
1526
+ function extractBulkEmailFailures(sentChunks, results) {
1527
+ return sentChunks.flatMap((sent, chunkIndex) => sent.flatMap((_, entryIndex) => {
1528
+ const result = results[chunkIndex]?.BulkEmailEntryResults?.[entryIndex];
1529
+ if (result?.Status === 'SUCCESS')
1530
+ return [];
1531
+ return [
1532
+ {
1533
+ id: originalIndex(chunkIndex, SEND_BULK_EMAIL_LIMIT, entryIndex),
1534
+ code: result?.Status,
1535
+ message: result?.Error ?? result?.Status ?? 'No status returned for entry',
1536
+ },
1537
+ ];
1538
+ }));
1539
+ }
1540
+ /**
1541
+ * Safe log shape for `sendEmail`. Keeps routing metadata and reduces the
1542
+ * recipients to a count; the sender and reply-to addresses, the subject, the
1543
+ * body and any template data are omitted as PII or payload. The template name
1544
+ * is operational metadata, not PII, so it is kept.
1545
+ */
1546
+ function summariseSendEmail(input) {
1547
+ const { ToAddresses, CcAddresses, BccAddresses } = input.Destination ?? {};
1548
+ return {
1549
+ FromEmailAddressIdentityArn: input.FromEmailAddressIdentityArn,
1550
+ ConfigurationSetName: input.ConfigurationSetName,
1551
+ EmailTags: input.EmailTags,
1552
+ EndpointId: input.EndpointId,
1553
+ TenantName: input.TenantName,
1554
+ templateName: input.Content?.Template?.TemplateName,
1555
+ recipientCount: (ToAddresses?.length ?? 0) + (CcAddresses?.length ?? 0) + (BccAddresses?.length ?? 0),
1556
+ };
1557
+ }
1558
+ /**
1559
+ * Safe log shape for `sendBulkEmail`. The entries carry destinations and
1560
+ * replacement data, and the default template data may carry PII, so they are
1561
+ * reduced to a count and the template name.
1562
+ */
1563
+ function summariseSendBulkEmail(input) {
1564
+ return {
1565
+ FromEmailAddressIdentityArn: input.FromEmailAddressIdentityArn,
1566
+ ConfigurationSetName: input.ConfigurationSetName,
1567
+ DefaultEmailTags: input.DefaultEmailTags,
1568
+ EndpointId: input.EndpointId,
1569
+ TenantName: input.TenantName,
1570
+ templateName: input.DefaultContent?.Template?.TemplateName,
1571
+ entryCount: input.BulkEmailEntries?.length ?? 0,
1572
+ };
1573
+ }
1574
+ /**
1575
+ * Wrapper around the AWS SES v2 client providing structured Powertools logging
1576
+ * and X-Ray tracing by default.
1577
+ *
1578
+ * Wraps SES v2 (`@aws-sdk/client-sesv2`), not the legacy v1 API. No defaults
1579
+ * are baked in: every send option, including `FromEmailAddress` and
1580
+ * `ConfigurationSetName`, comes from the caller.
1581
+ *
1582
+ * Where a method's input carries payloads or PII, the INFO log line omits
1583
+ * them; the verbose levels (`POWERTOOLS_LOG_LEVEL=DEBUG` or `TRACE`) log full
1584
+ * SDK inputs.
1585
+ */
1586
+ class SESService {
1587
+ client;
1588
+ logger;
1589
+ /**
1590
+ * @param opts.logger - Optional Powertools logger. Defaults to `new Logger()`,
1591
+ * which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
1592
+ * @param opts.client - Optional pre-configured `SESv2Client`. When supplied,
1593
+ * the wrapper does not apply X-Ray instrumentation.
1594
+ */
1595
+ constructor(opts) {
1596
+ this.client = opts?.client ?? xray.captureAWSv3Client(new clientSesv2.SESv2Client());
1597
+ this.logger = opts?.logger ?? new logger.Logger();
1598
+ }
1599
+ /**
1600
+ * Send a single email (Simple, Raw or Template content).
1601
+ *
1602
+ * At INFO level the log line includes only routing metadata and a
1603
+ * recipient count; see `summariseSendEmail`.
1604
+ *
1605
+ * Pass-through: SDK exceptions (`MessageRejected`, `SendingPausedException`,
1606
+ * …) propagate unwrapped.
1607
+ *
1608
+ * @returns The SDK output, including `MessageId`.
1609
+ */
1610
+ async sendEmail(input) {
1611
+ this.logger.info('Sending SES email', {
1612
+ input: redactInput(this.logger, input, summariseSendEmail),
1613
+ });
1614
+ return this.client.send(new clientSesv2.SendEmailCommand(input));
1615
+ }
1616
+ /**
1617
+ * Send a templated email to many destinations. SES caps `SendBulkEmail`
1618
+ * at 50 entries per request, so this method auto-chunks `BulkEmailEntries`
1619
+ * and sends one request per chunk, in order. Every chunk shares the other
1620
+ * input fields.
1621
+ *
1622
+ * At INFO level the log line includes only routing metadata, the template
1623
+ * name and an entry count; see `summariseSendBulkEmail`.
1624
+ *
1625
+ * SES answers HTTP 200 even when entries fail, so every chunk is sent
1626
+ * before the outcome is judged. If any entry's `Status` isn't `SUCCESS`
1627
+ * (or SES returned no result for it), a {@link BatchOperationError} is thrown whose
1628
+ * `failed[].id` is the entry's original index in `BulkEmailEntries` as a
1629
+ * string, and whose `results` are the per-chunk outputs — so a caller can
1630
+ * retry only the failed indexes. Request-level SDK exceptions are not
1631
+ * wrapped.
1632
+ *
1633
+ * Sending is not idempotent: retrying the whole batch after a throw
1634
+ * re-sends the entries that succeeded.
1635
+ *
1636
+ * @returns One SDK output per request sent.
1637
+ */
1638
+ async sendBulkEmail(input) {
1639
+ this.logger.info('Sending SES bulk email', {
1640
+ input: redactInput(this.logger, input, summariseSendBulkEmail),
1641
+ });
1642
+ const results = [];
1643
+ const sentChunks = chunk(input.BulkEmailEntries ?? [], SEND_BULK_EMAIL_LIMIT);
1644
+ for (const entries of sentChunks) {
1645
+ results.push(await this.client.send(new clientSesv2.SendBulkEmailCommand({ ...input, BulkEmailEntries: entries })));
1646
+ }
1647
+ return throwIfAny(this.logger, 'SES sendBulkEmail', results, extractBulkEmailFailures(sentChunks, results));
1648
+ }
1649
+ }
1650
+
1394
1651
  /**
1395
1652
  * Fields safe to log at INFO for `startExecution`. Omits `input` — the SFN
1396
1653
  * execution payload, which routinely carries PII (customer IDs, addresses,
@@ -1491,8 +1748,16 @@ function truncateCodepoints(str, maxChars) {
1491
1748
  }
1492
1749
 
1493
1750
  const PUBLISH_BATCH_LIMIT = 10;
1751
+ /**
1752
+ * The default `MaximumMessageSize` of an SNS topic. Topics can be raised to
1753
+ * 1 MiB, but the wrapper does not know a topic's setting, so it cuts at the
1754
+ * size every topic accepts. Message attributes count toward the topic limit
1755
+ * too and are not truncated, so a message at this size plus attributes can
1756
+ * still be rejected.
1757
+ */
1494
1758
  const SNS_MESSAGE_MAX_BYTES = 256 * 1024;
1495
- const SNS_SUBJECT_MAX_CHARS = 100;
1759
+ /** SNS requires a subject of *less than* 100 characters, so 99 is the maximum. */
1760
+ const SNS_SUBJECT_MAX_CHARS = 99;
1496
1761
  /**
1497
1762
  * Fields safe to log at INFO level for `publish`. Omits `Message`, `Subject`,
1498
1763
  * `MessageAttributes`, and `PhoneNumber` — payloads, user-visible content
@@ -1523,11 +1788,14 @@ class SNSService {
1523
1788
  * which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
1524
1789
  * @param opts.client - Optional pre-configured `SNSClient`. When supplied,
1525
1790
  * the wrapper does not apply X-Ray instrumentation.
1526
- * @param opts.truncate - When `true`, oversized `Message` / `Subject` are
1527
- * truncated (byte-safe / codepoint-safe) before sending instead of failing
1528
- * at the SDK. Defaults to `false` — the SDK throws on oversize, which is
1529
- * usually the right failure mode. Each `publish` call can override via
1530
- * its own `truncate` option.
1791
+ * @param opts.truncate - When `true`, an oversized `Message` (above 256 KiB,
1792
+ * the default topic limit — raising a topic's `MaximumMessageSize` does not
1793
+ * raise this cut-off) or `Subject` (above 99 characters) is truncated
1794
+ * (byte-safe / codepoint-safe) before sending instead of failing at the
1795
+ * SDK. Truncating a structured `Message` such as JSON can leave it invalid.
1796
+ * Defaults to `false` — the SDK throws on oversize, which is usually the
1797
+ * right failure mode. Each `publish` call can override via its own
1798
+ * `truncate` option.
1531
1799
  */
1532
1800
  constructor(opts) {
1533
1801
  this.client = opts?.client ?? xray.captureAWSv3Client(new clientSns.SNSClient());
@@ -1613,7 +1881,12 @@ class SNSService {
1613
1881
  }
1614
1882
 
1615
1883
  const SQS_BATCH_LIMIT = 10;
1616
- const SQS_MESSAGE_BODY_MAX_BYTES = 256 * 1024;
1884
+ /**
1885
+ * The SQS maximum message size. A queue's own `MaximumMessageSize` may be set
1886
+ * lower, and the wrapper cannot see it, so a queue configured below this still
1887
+ * rejects a body truncated to it.
1888
+ */
1889
+ const SQS_MESSAGE_BODY_MAX_BYTES = 1024 * 1024;
1617
1890
  /**
1618
1891
  * Fields safe to log at INFO level for `sendMessage`. Omits `MessageBody` and
1619
1892
  * `MessageAttributes` — both carry payload content.
@@ -1648,9 +1921,13 @@ class SQSService {
1648
1921
  * which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
1649
1922
  * @param opts.client - Optional pre-configured `SQSClient`. When supplied,
1650
1923
  * the wrapper does not apply X-Ray instrumentation.
1651
- * @param opts.truncate - When `true`, oversized `MessageBody` is truncated
1652
- * (byte-safe) before sending instead of failing at the SDK. Defaults to
1653
- * `false`. Each `sendMessage` call can override via its own `truncate`
1924
+ * @param opts.truncate - When `true`, a `MessageBody` above 1 MiB is
1925
+ * truncated (byte-safe) before sending instead of failing at the SDK. This
1926
+ * is the SQS maximum; a queue configured with a lower `MaximumMessageSize`
1927
+ * is not known to the wrapper. Message attributes count toward the limit
1928
+ * too and are not truncated.
1929
+ * Truncating a structured body such as JSON can leave it invalid. Defaults
1930
+ * to `false`. Each `sendMessage` call can override via its own `truncate`
1654
1931
  * option.
1655
1932
  */
1656
1933
  constructor(opts) {
@@ -1760,6 +2037,20 @@ class SQSService {
1760
2037
  }
1761
2038
 
1762
2039
  const GET_PARAMETERS_LIMIT = 10;
2040
+ /**
2041
+ * Every string a caller may have used to request this parameter. SSM answers
2042
+ * with the plain `Name` whatever was requested, so an ARN or a
2043
+ * `name:version` / `name:label` selector can only be matched through `ARN`
2044
+ * and `Selector`. A response carrying a `Selector` is keyed by its selector
2045
+ * forms only, so it can't shadow a request for the unversioned parameter.
2046
+ * `Selector` already carries its leading colon (`:3`, `:prod`).
2047
+ */
2048
+ function requestKeys({ Name, ARN, Selector }) {
2049
+ const identifiers = [Name, ARN].filter((id) => id !== undefined);
2050
+ if (Selector === undefined)
2051
+ return identifiers;
2052
+ return identifiers.map(id => `${id}${Selector}`);
2053
+ }
1763
2054
  /**
1764
2055
  * One failed entry per alias whose path SSM reported as invalid, so two
1765
2056
  * aliases sharing a missing path are both named.
@@ -1859,7 +2150,9 @@ class SSMService {
1859
2150
  * alias in `message`. Request-level SDK exceptions are not wrapped.
1860
2151
  *
1861
2152
  * @param aliases - Record mapping each desired local alias to its SSM
1862
- * parameter name (or ARN).
2153
+ * parameter name, ARN, or a `name:version` / `name:label` selector. The
2154
+ * value is matched back to the response by the name, ARN and selector SSM
2155
+ * reports, so each of those forms resolves to its own parameter.
1863
2156
  * @param opts.required - Throw when any requested parameter does not
1864
2157
  * exist. Defaults to `false`.
1865
2158
  * @returns A record keyed by the same aliases, mapping each to the
@@ -1869,7 +2162,7 @@ class SSMService {
1869
2162
  async getParameters(aliases, opts) {
1870
2163
  this.logger.info('Fetching SSM parameters', { input: { aliases } });
1871
2164
  const names = Object.values(aliases);
1872
- const byPath = new Map();
2165
+ const byRequest = new Map();
1873
2166
  const invalidPaths = new Set();
1874
2167
  for (const batch of chunk(names, GET_PARAMETERS_LIMIT)) {
1875
2168
  const response = await this.client.send(new clientSsm.GetParametersCommand({
@@ -1877,8 +2170,8 @@ class SSMService {
1877
2170
  WithDecryption: true,
1878
2171
  }));
1879
2172
  for (const parameter of response.Parameters ?? []) {
1880
- if (parameter.Name !== undefined)
1881
- byPath.set(parameter.Name, parameter.Value);
2173
+ for (const key of requestKeys(parameter))
2174
+ byRequest.set(key, parameter.Value);
1882
2175
  }
1883
2176
  for (const name of response.InvalidParameters ?? [])
1884
2177
  invalidPaths.add(name);
@@ -1889,7 +2182,7 @@ class SSMService {
1889
2182
  }
1890
2183
  const result = {};
1891
2184
  for (const alias of Object.keys(aliases)) {
1892
- result[alias] = byPath.get(aliases[alias]);
2185
+ result[alias] = byRequest.get(aliases[alias]);
1893
2186
  }
1894
2187
  return result;
1895
2188
  }
@@ -1945,6 +2238,7 @@ exports.EventBridgeService = EventBridgeService;
1945
2238
  exports.LambdaFunctionError = LambdaFunctionError;
1946
2239
  exports.LambdaService = LambdaService;
1947
2240
  exports.S3Service = S3Service;
2241
+ exports.SESService = SESService;
1948
2242
  exports.SNSService = SNSService;
1949
2243
  exports.SQSService = SQSService;
1950
2244
  exports.SSMService = SSMService;