@aligent/aws-wrappers 0.5.8 → 0.5.10

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 (61) hide show
  1. package/README.md +130 -3
  2. package/cjs/index.cjs +424 -11
  3. package/cjs/package.json +4 -1
  4. package/cjs/src/eventbridge/eventbridge.d.ts +58 -0
  5. package/cjs/src/eventbridge/eventbridge.d.ts.map +1 -0
  6. package/cjs/src/index.d.ts +4 -0
  7. package/cjs/src/index.d.ts.map +1 -1
  8. package/cjs/src/lambda/lambda.d.ts +54 -0
  9. package/cjs/src/lambda/lambda.d.ts.map +1 -0
  10. package/cjs/src/scheduler/scheduler.d.ts +3 -2
  11. package/cjs/src/scheduler/scheduler.d.ts.map +1 -1
  12. package/cjs/src/ses/ses.d.ts +64 -0
  13. package/cjs/src/ses/ses.d.ts.map +1 -0
  14. package/cjs/src/ssm/ssm.d.ts +18 -3
  15. package/cjs/src/ssm/ssm.d.ts.map +1 -1
  16. package/cjs/src/util/batch-operation-error.d.ts +13 -7
  17. package/cjs/src/util/batch-operation-error.d.ts.map +1 -1
  18. package/cjs/src/util/chunk.d.ts +8 -0
  19. package/cjs/src/util/chunk.d.ts.map +1 -1
  20. package/cjs/src/util/lambda-function-error.d.ts +36 -0
  21. package/cjs/src/util/lambda-function-error.d.ts.map +1 -0
  22. package/docs/index/classes/APIGatewayService.md +6 -6
  23. package/docs/index/classes/APIGatewayV2Service.md +5 -5
  24. package/docs/index/classes/BatchOperationError.md +7 -6
  25. package/docs/index/classes/DynamoDBService.md +12 -12
  26. package/docs/index/classes/EventBridgeService.md +99 -0
  27. package/docs/index/classes/LambdaFunctionError.md +283 -0
  28. package/docs/index/classes/LambdaService.md +95 -0
  29. package/docs/index/classes/S3Service.md +15 -15
  30. package/docs/index/classes/SESService.md +123 -0
  31. package/docs/index/classes/SNSService.md +4 -4
  32. package/docs/index/classes/SQSService.md +7 -7
  33. package/docs/index/classes/SSMService.md +33 -10
  34. package/docs/index/classes/SchedulerService.md +14 -13
  35. package/docs/index/classes/SecretsManagerService.md +8 -8
  36. package/docs/index/classes/StepFunctionsService.md +6 -6
  37. package/docs/index/interfaces/BatchFailedEntry.md +6 -5
  38. package/docs/index/interfaces/EmptyBucketPageResult.md +2 -2
  39. package/docs/index/modules.md +4 -0
  40. package/docs/testing/testing/functions/createMockService.md +1 -1
  41. package/esm/index.mjs +421 -12
  42. package/esm/package.json +4 -1
  43. package/esm/src/eventbridge/eventbridge.d.ts +58 -0
  44. package/esm/src/eventbridge/eventbridge.d.ts.map +1 -0
  45. package/esm/src/index.d.ts +4 -0
  46. package/esm/src/index.d.ts.map +1 -1
  47. package/esm/src/lambda/lambda.d.ts +54 -0
  48. package/esm/src/lambda/lambda.d.ts.map +1 -0
  49. package/esm/src/scheduler/scheduler.d.ts +3 -2
  50. package/esm/src/scheduler/scheduler.d.ts.map +1 -1
  51. package/esm/src/ses/ses.d.ts +64 -0
  52. package/esm/src/ses/ses.d.ts.map +1 -0
  53. package/esm/src/ssm/ssm.d.ts +18 -3
  54. package/esm/src/ssm/ssm.d.ts.map +1 -1
  55. package/esm/src/util/batch-operation-error.d.ts +13 -7
  56. package/esm/src/util/batch-operation-error.d.ts.map +1 -1
  57. package/esm/src/util/chunk.d.ts +8 -0
  58. package/esm/src/util/chunk.d.ts.map +1 -1
  59. package/esm/src/util/lambda-function-error.d.ts +36 -0
  60. package/esm/src/util/lambda-function-error.d.ts.map +1 -0
  61. package/package.json +4 -1
package/cjs/index.cjs CHANGED
@@ -6,10 +6,13 @@ var xray = require('aws-xray-sdk-core');
6
6
  var clientApiGateway = require('@aws-sdk/client-api-gateway');
7
7
  var clientDynamodb = require('@aws-sdk/client-dynamodb');
8
8
  var libDynamodb = require('@aws-sdk/lib-dynamodb');
9
+ var clientEventbridge = require('@aws-sdk/client-eventbridge');
10
+ var clientLambda = require('@aws-sdk/client-lambda');
9
11
  var clientS3 = require('@aws-sdk/client-s3');
10
12
  var s3RequestPresigner = require('@aws-sdk/s3-request-presigner');
11
13
  var clientScheduler = require('@aws-sdk/client-scheduler');
12
14
  var clientSecretsManager = require('@aws-sdk/client-secrets-manager');
15
+ var clientSesv2 = require('@aws-sdk/client-sesv2');
13
16
  var clientSfn = require('@aws-sdk/client-sfn');
14
17
  var clientSns = require('@aws-sdk/client-sns');
15
18
  var clientSqs = require('@aws-sdk/client-sqs');
@@ -519,7 +522,8 @@ class DynamoDBService {
519
522
  *
520
523
  * `results` holds the raw SDK output of every chunk, so the outputs of the
521
524
  * entries that succeeded (message ids, sequence numbers) stay readable. The
522
- * one exception is `S3.emptyBucket`, whose `results` are per-page deleted keys.
525
+ * exceptions are `S3.emptyBucket`, whose `results` are per-page deleted keys,
526
+ * and `SSM.getParameters`, whose `results` are empty.
523
527
  * `failed` is the normalised list of rejected entries across all chunks.
524
528
  *
525
529
  * Match on `name` rather than `instanceof` if both the CJS and ESM builds of
@@ -538,8 +542,7 @@ class BatchOperationError extends Error {
538
542
  /**
539
543
  * SQS and SNS report rejected entries under `Failed` on an otherwise
540
544
  * successful response, so a resolved chunk does not mean every entry was
541
- * accepted. Returns `results` untouched when nothing failed; otherwise warns
542
- * and throws a {@link BatchOperationError}.
545
+ * accepted. Extracts those entries and delegates to {@link throwIfAny}.
543
546
  *
544
547
  * Only id, code and message are copied out — never the entry itself — so
545
548
  * neither the error nor the warning can leak a payload.
@@ -566,9 +569,14 @@ function throwIfAnyDeleteErrors(logger, operation, results) {
566
569
  return throwIfAny(logger, operation, results, failed);
567
570
  }
568
571
  /**
569
- * Throws a {@link BatchOperationError} for operations whose `results` aren't a
570
- * plain list of SDK outputs, such as `S3.emptyBucket`. Returns `results`
571
- * untouched when `failed` is empty.
572
+ * Warn-and-throw step for services whose responses don't use the SQS/SNS
573
+ * `Failed` shape and so extract their own rejected entries (`EventBridge.putEvents`),
574
+ * or whose `results` aren't a plain list of SDK outputs (`S3.emptyBucket`).
575
+ * Returns `results` untouched when `failed` is empty.
576
+ *
577
+ * Callers must build `failed` by copying id, code and message explicitly —
578
+ * never by spreading the SDK entry — because it goes straight into the error
579
+ * and the warning.
572
580
  */
573
581
  function throwIfAny(logger, operation, results, failed) {
574
582
  if (failed.length === 0)
@@ -599,6 +607,240 @@ function chunk(items, size) {
599
607
  }
600
608
  return chunks;
601
609
  }
610
+ /**
611
+ * The index, as a string, that an entry had in the list `chunk` split, given
612
+ * its chunk number and its position within that chunk. Batch operations whose
613
+ * entries carry no identifier of their own report failures by this index.
614
+ * `chunk` fills every chunk but the last, so the chunk's offset is the chunk
615
+ * number times the chunk size.
616
+ */
617
+ function originalIndex(chunkIndex, chunkSize, position) {
618
+ return String(chunkIndex * chunkSize + position);
619
+ }
620
+
621
+ const PUT_EVENTS_LIMIT = 10;
622
+ /**
623
+ * `Detail`, `Resources` and the entries themselves are payload carriers, so
624
+ * the INFO line carries only the endpoint id and how many entries were sent.
625
+ */
626
+ function summariseEntries$1({ EndpointId, Entries }) {
627
+ return { EndpointId, entryCount: Entries?.length ?? 0 };
628
+ }
629
+ function extractPutEventsFailures(results) {
630
+ return results.flatMap(extractChunkFailures);
631
+ }
632
+ /**
633
+ * `PutEvents` reports a rejected entry by an error code on the result entry at
634
+ * the same position as the request entry.
635
+ *
636
+ * Copies only code and message out, never the request entry, so neither the
637
+ * error nor the warning can carry event detail.
638
+ */
639
+ function extractChunkFailures(result, chunkIndex) {
640
+ return (result.Entries ?? [])
641
+ .map(({ ErrorCode, ErrorMessage }, position) => ({
642
+ id: originalIndex(chunkIndex, PUT_EVENTS_LIMIT, position),
643
+ code: ErrorCode,
644
+ message: ErrorMessage,
645
+ }))
646
+ .filter(({ code }) => code !== undefined);
647
+ }
648
+ /**
649
+ * Wrapper around the AWS EventBridge client providing structured Powertools
650
+ * logging and X-Ray tracing by default.
651
+ *
652
+ * Where a method's input carries payloads, secret material or PII, the INFO
653
+ * log line omits them; the verbose levels (`POWERTOOLS_LOG_LEVEL=DEBUG` or
654
+ * `TRACE`) log full SDK inputs.
655
+ *
656
+ * Covers `putEvents` only. Named `EventBridgeService` for the event bus API;
657
+ * schedules live in `SchedulerService`.
658
+ */
659
+ class EventBridgeService {
660
+ client;
661
+ logger;
662
+ /**
663
+ * @param opts.logger - Optional Powertools logger. Defaults to `new Logger()`,
664
+ * which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
665
+ * @param opts.client - Optional pre-configured `EventBridgeClient`. When
666
+ * supplied, the wrapper does not apply X-Ray instrumentation.
667
+ */
668
+ constructor(opts) {
669
+ this.client = opts?.client ?? xray.captureAWSv3Client(new clientEventbridge.EventBridgeClient());
670
+ this.logger = opts?.logger ?? new logger.Logger();
671
+ }
672
+ /**
673
+ * Publish events to an event bus. The EventBridge API caps `PutEvents` at
674
+ * 10 entries per request, so this method auto-chunks the caller's `Entries`
675
+ * and sends one request per chunk, returning the array of outputs. The
676
+ * remaining request fields (such as `EndpointId`) are carried onto every
677
+ * chunk.
678
+ *
679
+ * Chunking is by count only. The 256 KB request size limit is not enforced
680
+ * here: a chunk that exceeds it fails at the SDK as a request-level error.
681
+ *
682
+ * Every chunk is sent before the outcome is judged. If EventBridge rejected
683
+ * any entry (it reports an error code on the result entry), a
684
+ * {@link BatchOperationError} is then thrown carrying the per-chunk results
685
+ * and the failed entries. For this method each failed entry's `id` is
686
+ * always set, to the entry's index in the caller's original `Entries` list
687
+ * across all chunks, as a string. Only `id`, `code` and `message` are
688
+ * copied out, so event detail never reaches the error.
689
+ *
690
+ * No retries are performed. Request-level SDK exceptions (throttling,
691
+ * access denied, oversize request) are not wrapped: they propagate
692
+ * unchanged and immediately, so earlier chunks may already have been
693
+ * published.
694
+ *
695
+ * At INFO level the log line includes only the endpoint id and the entry
696
+ * count, because `Detail`, `Resources` and the entries themselves are
697
+ * payload carriers.
698
+ *
699
+ * @param input - PutEventsCommandInput including Entries.
700
+ */
701
+ async putEvents(input) {
702
+ const entries = input.Entries ?? [];
703
+ this.logger.info('Putting EventBridge events', {
704
+ input: redactInput(this.logger, input, summariseEntries$1),
705
+ });
706
+ const results = [];
707
+ for (const batch of chunk(entries, PUT_EVENTS_LIMIT)) {
708
+ results.push(await this.client.send(new clientEventbridge.PutEventsCommand({ ...input, Entries: batch })));
709
+ }
710
+ return throwIfAny(this.logger, 'EventBridge putEvents', results, extractPutEventsFailures(results));
711
+ }
712
+ }
713
+
714
+ /**
715
+ * Thrown by `LambdaService.invoke` when a synchronous invocation reached the
716
+ * function but the function itself failed. Lambda reports that as an HTTP 200
717
+ * carrying a function error marker, so the SDK does not throw.
718
+ *
719
+ * `functionError` is the SDK's marker (`Handled` or `Unhandled`).
720
+ * `errorType` and `errorMessage` are parsed from the response payload when it
721
+ * has the usual `{ errorType, errorMessage }` JSON shape, otherwise undefined.
722
+ *
723
+ * Deliberately excludes the raw SDK output and the stack trace: either can
724
+ * contain the caller's payload or PII.
725
+ *
726
+ * Match on `name` rather than `instanceof` if both the CJS and ESM builds of
727
+ * this package may be loaded in one process.
728
+ */
729
+ class LambdaFunctionError extends Error {
730
+ functionName;
731
+ functionError;
732
+ name = 'LambdaFunctionError';
733
+ errorType;
734
+ errorMessage;
735
+ constructor(functionName, functionError, payload) {
736
+ super(`Lambda function ${functionName ?? '(unnamed)'} failed (${functionError})`);
737
+ this.functionName = functionName;
738
+ this.functionError = functionError;
739
+ this.errorType = payload.errorType;
740
+ this.errorMessage = payload.errorMessage;
741
+ }
742
+ }
743
+ /**
744
+ * Reads `errorType` and `errorMessage` out of a function error payload.
745
+ * Anything that is not a JSON object with string fields yields undefined for
746
+ * that field rather than failing, because the payload is whatever the invoked
747
+ * function (or runtime) chose to return.
748
+ */
749
+ function parseFunctionErrorPayload(payload) {
750
+ const empty = { errorType: undefined, errorMessage: undefined };
751
+ if (payload === undefined)
752
+ return empty;
753
+ let parsed;
754
+ try {
755
+ parsed = JSON.parse(new TextDecoder().decode(payload));
756
+ }
757
+ catch {
758
+ return empty;
759
+ }
760
+ if (typeof parsed !== 'object' || parsed === null)
761
+ return empty;
762
+ const { errorType, errorMessage } = parsed;
763
+ return {
764
+ errorType: typeof errorType === 'string' ? errorType : undefined,
765
+ errorMessage: typeof errorMessage === 'string' ? errorMessage : undefined,
766
+ };
767
+ }
768
+
769
+ /**
770
+ * `Invoke` inputs carry the invocation `Payload` and the base64 `ClientContext`
771
+ * handed to the function, both of which routinely contain caller data and PII.
772
+ * Everything else identifies the target or how to call it.
773
+ */
774
+ const INVOKE_SAFE_FIELDS = [
775
+ 'FunctionName',
776
+ 'InvocationType',
777
+ 'Qualifier',
778
+ 'LogType',
779
+ 'TenantId',
780
+ ];
781
+ /**
782
+ * Wrapper around the AWS Lambda client providing structured Powertools logging
783
+ * and X-Ray tracing by default.
784
+ *
785
+ * Where a method's input carries payloads, secret material or PII, the INFO
786
+ * log line omits them; the verbose levels (`POWERTOOLS_LOG_LEVEL=DEBUG` or
787
+ * `TRACE`) log full SDK inputs.
788
+ *
789
+ * Covers `invoke` only.
790
+ */
791
+ class LambdaService {
792
+ client;
793
+ logger;
794
+ /**
795
+ * @param opts.logger - Optional Powertools logger. Defaults to `new Logger()`,
796
+ * which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
797
+ * @param opts.client - Optional pre-configured `LambdaClient`. When
798
+ * supplied, the wrapper does not apply X-Ray instrumentation.
799
+ */
800
+ constructor(opts) {
801
+ this.client = opts?.client ?? xray.captureAWSv3Client(new clientLambda.LambdaClient());
802
+ this.logger = opts?.logger ?? new logger.Logger();
803
+ }
804
+ /**
805
+ * Invoke a Lambda function. The input is the SDK input unchanged and the
806
+ * output is the SDK output unchanged: `Payload` stays a `Uint8Array` you
807
+ * decode yourself. Choose synchronous, asynchronous or dry-run invocation
808
+ * with `InvocationType`; omitting it means synchronous (`RequestResponse`).
809
+ *
810
+ * Lambda answers HTTP 200 even when the invoked function threw, flagging it
811
+ * with `FunctionError` on the response. If that marker is present this
812
+ * method warns and throws a {@link LambdaFunctionError} carrying the
813
+ * function name, the marker, and the error type and message parsed from the
814
+ * payload when it has the usual JSON shape. The raw output and the stack
815
+ * trace are deliberately left off the error.
816
+ *
817
+ * The marker only appears on synchronous responses, so the check is
818
+ * unconditional: asynchronous (`Event`) and `DryRun` responses return
819
+ * without throwing. Failures of asynchronous invocations are therefore not
820
+ * observable here; they belong to dead-letter queues and destinations on
821
+ * the invoked function. No status code check is added; service-level
822
+ * errors such as throttling are thrown by the SDK and propagate unwrapped.
823
+ *
824
+ * At INFO level the log line includes only the function name, invocation
825
+ * type, qualifier, log type and tenant id. `Payload` and `ClientContext` are
826
+ * omitted, and responses are never logged.
827
+ *
828
+ * @param input - InvokeCommandInput including FunctionName.
829
+ */
830
+ async invoke(input) {
831
+ this.logger.info('Invoking Lambda function', {
832
+ input: redactInput(this.logger, input, INVOKE_SAFE_FIELDS),
833
+ });
834
+ const output = await this.client.send(new clientLambda.InvokeCommand(input));
835
+ if (output.FunctionError === undefined)
836
+ return output;
837
+ this.logger.warn('Lambda invoke function error', {
838
+ functionName: input.FunctionName,
839
+ functionError: output.FunctionError,
840
+ });
841
+ throw new LambdaFunctionError(input.FunctionName, output.FunctionError, parseFunctionErrorPayload(output.Payload));
842
+ }
843
+ }
602
844
 
603
845
  const DEFAULT_PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
604
846
  const DELETE_OBJECTS_BATCH_LIMIT = 1000;
@@ -901,8 +1143,9 @@ function stripTargetInput(input) {
901
1143
  * `TRACE`) log full SDK inputs.
902
1144
  *
903
1145
  * Covers CRUD on schedules and their groups. Named `SchedulerService` (not
904
- * `EventBridgeSchedulerService`) so it doesn't collide with a future wrapper
905
- * over the separate EventBridge bus/rules API (`@aws-sdk/client-eventbridge`).
1146
+ * `EventBridgeSchedulerService`) so it doesn't collide with `EventBridgeService`,
1147
+ * the wrapper over the separate EventBridge bus/rules API
1148
+ * (`@aws-sdk/client-eventbridge`).
906
1149
  *
907
1150
  * `FlexibleTimeWindow` is required by `CreateSchedule` and is passed through
908
1151
  * untouched — the wrapper bakes in no default, so the caller must state their
@@ -1154,6 +1397,139 @@ class SecretsManagerService {
1154
1397
  }
1155
1398
  }
1156
1399
 
1400
+ const SEND_BULK_EMAIL_LIMIT = 50;
1401
+ /**
1402
+ * Sent entries whose result isn't `SUCCESS`, identified by their original
1403
+ * index in the caller's `BulkEmailEntries`. Walks the entries that were sent
1404
+ * rather than the results that came back, so an entry SES returned no result
1405
+ * for counts as failed instead of passing unnoticed. Only status and error are
1406
+ * copied out, never the entry, so no destination can leak.
1407
+ */
1408
+ function extractBulkEmailFailures(sentChunks, results) {
1409
+ return sentChunks.flatMap((sent, chunkIndex) => sent.flatMap((_, entryIndex) => {
1410
+ const result = results[chunkIndex]?.BulkEmailEntryResults?.[entryIndex];
1411
+ if (result?.Status === 'SUCCESS')
1412
+ return [];
1413
+ return [
1414
+ {
1415
+ id: originalIndex(chunkIndex, SEND_BULK_EMAIL_LIMIT, entryIndex),
1416
+ code: result?.Status,
1417
+ message: result?.Error ?? result?.Status ?? 'No status returned for entry',
1418
+ },
1419
+ ];
1420
+ }));
1421
+ }
1422
+ /**
1423
+ * Safe log shape for `sendEmail`. Keeps routing metadata and reduces the
1424
+ * recipients to a count; the sender and reply-to addresses, the subject, the
1425
+ * body and any template data are omitted as PII or payload. The template name
1426
+ * is operational metadata, not PII, so it is kept.
1427
+ */
1428
+ function summariseSendEmail(input) {
1429
+ const { ToAddresses, CcAddresses, BccAddresses } = input.Destination ?? {};
1430
+ return {
1431
+ FromEmailAddressIdentityArn: input.FromEmailAddressIdentityArn,
1432
+ ConfigurationSetName: input.ConfigurationSetName,
1433
+ EmailTags: input.EmailTags,
1434
+ EndpointId: input.EndpointId,
1435
+ TenantName: input.TenantName,
1436
+ templateName: input.Content?.Template?.TemplateName,
1437
+ recipientCount: (ToAddresses?.length ?? 0) + (CcAddresses?.length ?? 0) + (BccAddresses?.length ?? 0),
1438
+ };
1439
+ }
1440
+ /**
1441
+ * Safe log shape for `sendBulkEmail`. The entries carry destinations and
1442
+ * replacement data, and the default template data may carry PII, so they are
1443
+ * reduced to a count and the template name.
1444
+ */
1445
+ function summariseSendBulkEmail(input) {
1446
+ return {
1447
+ FromEmailAddressIdentityArn: input.FromEmailAddressIdentityArn,
1448
+ ConfigurationSetName: input.ConfigurationSetName,
1449
+ DefaultEmailTags: input.DefaultEmailTags,
1450
+ EndpointId: input.EndpointId,
1451
+ TenantName: input.TenantName,
1452
+ templateName: input.DefaultContent?.Template?.TemplateName,
1453
+ entryCount: input.BulkEmailEntries?.length ?? 0,
1454
+ };
1455
+ }
1456
+ /**
1457
+ * Wrapper around the AWS SES v2 client providing structured Powertools logging
1458
+ * and X-Ray tracing by default.
1459
+ *
1460
+ * Wraps SES v2 (`@aws-sdk/client-sesv2`), not the legacy v1 API. No defaults
1461
+ * are baked in: every send option, including `FromEmailAddress` and
1462
+ * `ConfigurationSetName`, comes from the caller.
1463
+ *
1464
+ * Where a method's input carries payloads or PII, the INFO log line omits
1465
+ * them; the verbose levels (`POWERTOOLS_LOG_LEVEL=DEBUG` or `TRACE`) log full
1466
+ * SDK inputs.
1467
+ */
1468
+ class SESService {
1469
+ client;
1470
+ logger;
1471
+ /**
1472
+ * @param opts.logger - Optional Powertools logger. Defaults to `new Logger()`,
1473
+ * which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
1474
+ * @param opts.client - Optional pre-configured `SESv2Client`. When supplied,
1475
+ * the wrapper does not apply X-Ray instrumentation.
1476
+ */
1477
+ constructor(opts) {
1478
+ this.client = opts?.client ?? xray.captureAWSv3Client(new clientSesv2.SESv2Client());
1479
+ this.logger = opts?.logger ?? new logger.Logger();
1480
+ }
1481
+ /**
1482
+ * Send a single email (Simple, Raw or Template content).
1483
+ *
1484
+ * At INFO level the log line includes only routing metadata and a
1485
+ * recipient count; see `summariseSendEmail`.
1486
+ *
1487
+ * Pass-through: SDK exceptions (`MessageRejected`, `SendingPausedException`,
1488
+ * …) propagate unwrapped.
1489
+ *
1490
+ * @returns The SDK output, including `MessageId`.
1491
+ */
1492
+ async sendEmail(input) {
1493
+ this.logger.info('Sending SES email', {
1494
+ input: redactInput(this.logger, input, summariseSendEmail),
1495
+ });
1496
+ return this.client.send(new clientSesv2.SendEmailCommand(input));
1497
+ }
1498
+ /**
1499
+ * Send a templated email to many destinations. SES caps `SendBulkEmail`
1500
+ * at 50 entries per request, so this method auto-chunks `BulkEmailEntries`
1501
+ * and sends one request per chunk, in order. Every chunk shares the other
1502
+ * input fields.
1503
+ *
1504
+ * At INFO level the log line includes only routing metadata, the template
1505
+ * name and an entry count; see `summariseSendBulkEmail`.
1506
+ *
1507
+ * SES answers HTTP 200 even when entries fail, so every chunk is sent
1508
+ * before the outcome is judged. If any entry's `Status` isn't `SUCCESS`
1509
+ * (or SES returned no result for it), a {@link BatchOperationError} is thrown whose
1510
+ * `failed[].id` is the entry's original index in `BulkEmailEntries` as a
1511
+ * string, and whose `results` are the per-chunk outputs — so a caller can
1512
+ * retry only the failed indexes. Request-level SDK exceptions are not
1513
+ * wrapped.
1514
+ *
1515
+ * Sending is not idempotent: retrying the whole batch after a throw
1516
+ * re-sends the entries that succeeded.
1517
+ *
1518
+ * @returns One SDK output per request sent.
1519
+ */
1520
+ async sendBulkEmail(input) {
1521
+ this.logger.info('Sending SES bulk email', {
1522
+ input: redactInput(this.logger, input, summariseSendBulkEmail),
1523
+ });
1524
+ const results = [];
1525
+ const sentChunks = chunk(input.BulkEmailEntries ?? [], SEND_BULK_EMAIL_LIMIT);
1526
+ for (const entries of sentChunks) {
1527
+ results.push(await this.client.send(new clientSesv2.SendBulkEmailCommand({ ...input, BulkEmailEntries: entries })));
1528
+ }
1529
+ return throwIfAny(this.logger, 'SES sendBulkEmail', results, extractBulkEmailFailures(sentChunks, results));
1530
+ }
1531
+ }
1532
+
1157
1533
  /**
1158
1534
  * Fields safe to log at INFO for `startExecution`. Omits `input` — the SFN
1159
1535
  * execution payload, which routinely carries PII (customer IDs, addresses,
@@ -1523,6 +1899,19 @@ class SQSService {
1523
1899
  }
1524
1900
 
1525
1901
  const GET_PARAMETERS_LIMIT = 10;
1902
+ /**
1903
+ * One failed entry per alias whose path SSM reported as invalid, so two
1904
+ * aliases sharing a missing path are both named.
1905
+ */
1906
+ function missingParameters(aliases, invalidPaths) {
1907
+ return Object.entries(aliases)
1908
+ .filter(([, path]) => invalidPaths.has(path))
1909
+ .map(([alias, path]) => ({
1910
+ id: path,
1911
+ code: 'ParameterNotFound',
1912
+ message: `Parameter not found for alias "${alias}"`,
1913
+ }));
1914
+ }
1526
1915
  /**
1527
1916
  * Fields safe to log at INFO level for `putParameter`. Omits `Value` (the
1528
1917
  * parameter content itself).
@@ -1573,6 +1962,9 @@ class SSMService {
1573
1962
  * @param name - The parameter name (or ARN).
1574
1963
  * @returns The parameter value, or `undefined` if the parameter has no
1575
1964
  * value set.
1965
+ * @throws When the parameter does not exist (the SDK's
1966
+ * `ParameterNotFound`). {@link SSMService.getParameters} instead returns
1967
+ * `undefined` for a missing parameter unless `required` is set.
1576
1968
  */
1577
1969
  async getParameter(name) {
1578
1970
  this.logger.info('Fetching SSM parameter', { input: { name } });
@@ -1597,16 +1989,27 @@ class SSMService {
1597
1989
  * the underlying parameter names and sends one request per chunk,
1598
1990
  * merging the results before building the alias-keyed return value.
1599
1991
  *
1992
+ * Unlike {@link SSMService.getParameter}, which throws when the parameter
1993
+ * does not exist, a missing parameter here maps to `undefined` — so a
1994
+ * typo'd path surfaces later as an undefined value. Pass
1995
+ * `{ required: true }` to fail fast instead: every chunk is still sent,
1996
+ * then a {@link BatchOperationError} is thrown whose `failed` entries
1997
+ * carry each missing path as `id`, the code `ParameterNotFound`, and the
1998
+ * alias in `message`. Request-level SDK exceptions are not wrapped.
1999
+ *
1600
2000
  * @param aliases - Record mapping each desired local alias to its SSM
1601
2001
  * parameter name (or ARN).
2002
+ * @param opts.required - Throw when any requested parameter does not
2003
+ * exist. Defaults to `false`.
1602
2004
  * @returns A record keyed by the same aliases, mapping each to the
1603
- * parameter's value, or `undefined` when the parameter is missing or has
1604
- * no value.
2005
+ * parameter's value, or `undefined` when the parameter is missing (unless
2006
+ * `required` is set) or has no value.
1605
2007
  */
1606
- async getParameters(aliases) {
2008
+ async getParameters(aliases, opts) {
1607
2009
  this.logger.info('Fetching SSM parameters', { input: { aliases } });
1608
2010
  const names = Object.values(aliases);
1609
2011
  const byPath = new Map();
2012
+ const invalidPaths = new Set();
1610
2013
  for (const batch of chunk(names, GET_PARAMETERS_LIMIT)) {
1611
2014
  const response = await this.client.send(new clientSsm.GetParametersCommand({
1612
2015
  Names: batch,
@@ -1616,6 +2019,12 @@ class SSMService {
1616
2019
  if (parameter.Name !== undefined)
1617
2020
  byPath.set(parameter.Name, parameter.Value);
1618
2021
  }
2022
+ for (const name of response.InvalidParameters ?? [])
2023
+ invalidPaths.add(name);
2024
+ }
2025
+ if (opts?.required) {
2026
+ // No per-chunk results: the SDK output of a failed lookup adds nothing
2027
+ throwIfAny(this.logger, 'SSM getParameters', [], missingParameters(aliases, invalidPaths));
1619
2028
  }
1620
2029
  const result = {};
1621
2030
  for (const alias of Object.keys(aliases)) {
@@ -1671,7 +2080,11 @@ exports.APIGatewayService = APIGatewayService;
1671
2080
  exports.APIGatewayV2Service = APIGatewayV2Service;
1672
2081
  exports.BatchOperationError = BatchOperationError;
1673
2082
  exports.DynamoDBService = DynamoDBService;
2083
+ exports.EventBridgeService = EventBridgeService;
2084
+ exports.LambdaFunctionError = LambdaFunctionError;
2085
+ exports.LambdaService = LambdaService;
1674
2086
  exports.S3Service = S3Service;
2087
+ exports.SESService = SESService;
1675
2088
  exports.SNSService = SNSService;
1676
2089
  exports.SQSService = SQSService;
1677
2090
  exports.SSMService = SSMService;
package/cjs/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aligent/aws-wrappers",
3
- "version": "0.5.8",
3
+ "version": "0.5.10",
4
4
  "description": "Opinionated AWS SDK wrappers with Powertools logging and X-Ray tracing",
5
5
  "engines": {
6
6
  "node": ">=18"
@@ -47,9 +47,12 @@
47
47
  "@aws-sdk/client-api-gateway": "^3.1160.0",
48
48
  "@aws-sdk/client-apigatewayv2": "^3.1160.0",
49
49
  "@aws-sdk/client-dynamodb": "^3.1160.0",
50
+ "@aws-sdk/client-eventbridge": "^3.1160.0",
51
+ "@aws-sdk/client-lambda": "^3.1160.0",
50
52
  "@aws-sdk/client-s3": "^3.1160.0",
51
53
  "@aws-sdk/client-scheduler": "^3.1160.0",
52
54
  "@aws-sdk/client-secrets-manager": "^3.1160.0",
55
+ "@aws-sdk/client-sesv2": "^3.1160.0",
53
56
  "@aws-sdk/client-sfn": "^3.1160.0",
54
57
  "@aws-sdk/client-sns": "^3.1160.0",
55
58
  "@aws-sdk/client-sqs": "^3.1160.0",
@@ -0,0 +1,58 @@
1
+ import type { LoggerInterface } from '@aws-lambda-powertools/logger/types';
2
+ import { EventBridgeClient, PutEventsCommandInput, PutEventsCommandOutput } from '@aws-sdk/client-eventbridge';
3
+ /**
4
+ * Wrapper around the AWS EventBridge client providing structured Powertools
5
+ * logging and X-Ray tracing by default.
6
+ *
7
+ * Where a method's input carries payloads, secret material or PII, the INFO
8
+ * log line omits them; the verbose levels (`POWERTOOLS_LOG_LEVEL=DEBUG` or
9
+ * `TRACE`) log full SDK inputs.
10
+ *
11
+ * Covers `putEvents` only. Named `EventBridgeService` for the event bus API;
12
+ * schedules live in `SchedulerService`.
13
+ */
14
+ export declare class EventBridgeService {
15
+ private readonly client;
16
+ private readonly logger;
17
+ /**
18
+ * @param opts.logger - Optional Powertools logger. Defaults to `new Logger()`,
19
+ * which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
20
+ * @param opts.client - Optional pre-configured `EventBridgeClient`. When
21
+ * supplied, the wrapper does not apply X-Ray instrumentation.
22
+ */
23
+ constructor(opts?: {
24
+ logger?: LoggerInterface;
25
+ client?: EventBridgeClient;
26
+ });
27
+ /**
28
+ * Publish events to an event bus. The EventBridge API caps `PutEvents` at
29
+ * 10 entries per request, so this method auto-chunks the caller's `Entries`
30
+ * and sends one request per chunk, returning the array of outputs. The
31
+ * remaining request fields (such as `EndpointId`) are carried onto every
32
+ * chunk.
33
+ *
34
+ * Chunking is by count only. The 256 KB request size limit is not enforced
35
+ * here: a chunk that exceeds it fails at the SDK as a request-level error.
36
+ *
37
+ * Every chunk is sent before the outcome is judged. If EventBridge rejected
38
+ * any entry (it reports an error code on the result entry), a
39
+ * {@link BatchOperationError} is then thrown carrying the per-chunk results
40
+ * and the failed entries. For this method each failed entry's `id` is
41
+ * always set, to the entry's index in the caller's original `Entries` list
42
+ * across all chunks, as a string. Only `id`, `code` and `message` are
43
+ * copied out, so event detail never reaches the error.
44
+ *
45
+ * No retries are performed. Request-level SDK exceptions (throttling,
46
+ * access denied, oversize request) are not wrapped: they propagate
47
+ * unchanged and immediately, so earlier chunks may already have been
48
+ * published.
49
+ *
50
+ * At INFO level the log line includes only the endpoint id and the entry
51
+ * count, because `Detail`, `Resources` and the entries themselves are
52
+ * payload carriers.
53
+ *
54
+ * @param input - PutEventsCommandInput including Entries.
55
+ */
56
+ putEvents(input: PutEventsCommandInput): Promise<PutEventsCommandOutput[]>;
57
+ }
58
+ //# sourceMappingURL=eventbridge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"eventbridge.d.ts","sourceRoot":"","sources":["../../../../src/eventbridge/eventbridge.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AAC3E,OAAO,EACH,iBAAiB,EAEjB,qBAAqB,EACrB,sBAAsB,EAEzB,MAAM,6BAA6B,CAAC;AAwCrC;;;;;;;;;;GAUG;AACH,qBAAa,kBAAkB;IAC3B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAoB;IAC3C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAkB;IAEzC;;;;;OAKG;gBACS,IAAI,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,eAAe,CAAC;QAAC,MAAM,CAAC,EAAE,iBAAiB,CAAA;KAAE;IAK3E;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4BG;IACG,SAAS,CAAC,KAAK,EAAE,qBAAqB,GAAG,OAAO,CAAC,sBAAsB,EAAE,CAAC;CAkBnF"}
@@ -1,14 +1,18 @@
1
1
  export { APIGatewayV2Service } from './api-gateway-v2/api-gateway-v2.js';
2
2
  export { APIGatewayService } from './api-gateway/api-gateway.js';
3
3
  export { DynamoDBService } from './dynamodb/dynamodb.js';
4
+ export { EventBridgeService } from './eventbridge/eventbridge.js';
5
+ export { LambdaService } from './lambda/lambda.js';
4
6
  export { S3Service } from './s3/s3.js';
5
7
  export type { EmptyBucketPageResult } from './s3/s3.js';
6
8
  export { SchedulerService } from './scheduler/scheduler.js';
7
9
  export { SecretsManagerService } from './secrets-manager/secrets-manager.js';
10
+ export { SESService } from './ses/ses.js';
8
11
  export { StepFunctionsService } from './sfn/sfn.js';
9
12
  export { SNSService } from './sns/sns.js';
10
13
  export { SQSService } from './sqs/sqs.js';
11
14
  export { SSMService } from './ssm/ssm.js';
12
15
  export { BatchOperationError } from './util/batch-operation-error.js';
13
16
  export type { BatchFailedEntry } from './util/batch-operation-error.js';
17
+ export { LambdaFunctionError } from './util/lambda-function-error.js';
14
18
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,YAAY,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AACtE,YAAY,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,YAAY,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AACtE,YAAY,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC"}