@aligent/aws-wrappers 0.5.7 → 0.5.9

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 (56) hide show
  1. package/README.md +106 -4
  2. package/cjs/index.cjs +393 -66
  3. package/cjs/package.json +16 -14
  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/s3/s3.d.ts +26 -4
  11. package/cjs/src/s3/s3.d.ts.map +1 -1
  12. package/cjs/src/scheduler/scheduler.d.ts +3 -2
  13. package/cjs/src/scheduler/scheduler.d.ts.map +1 -1
  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 +33 -4
  17. package/cjs/src/util/batch-operation-error.d.ts.map +1 -1
  18. package/cjs/src/util/lambda-function-error.d.ts +36 -0
  19. package/cjs/src/util/lambda-function-error.d.ts.map +1 -0
  20. package/docs/index/classes/APIGatewayService.md +6 -6
  21. package/docs/index/classes/APIGatewayV2Service.md +5 -5
  22. package/docs/index/classes/BatchOperationError.md +10 -6
  23. package/docs/index/classes/DynamoDBService.md +34 -12
  24. package/docs/index/classes/EventBridgeService.md +99 -0
  25. package/docs/index/classes/LambdaFunctionError.md +283 -0
  26. package/docs/index/classes/LambdaService.md +95 -0
  27. package/docs/index/classes/S3Service.md +42 -19
  28. package/docs/index/classes/SNSService.md +4 -4
  29. package/docs/index/classes/SQSService.md +7 -7
  30. package/docs/index/classes/SSMService.md +35 -10
  31. package/docs/index/classes/SchedulerService.md +14 -13
  32. package/docs/index/classes/SecretsManagerService.md +10 -8
  33. package/docs/index/classes/StepFunctionsService.md +6 -6
  34. package/docs/index/interfaces/BatchFailedEntry.md +6 -5
  35. package/docs/index/interfaces/EmptyBucketPageResult.md +23 -0
  36. package/docs/index/modules.md +4 -0
  37. package/docs/testing/testing/functions/createMockService.md +5 -1
  38. package/esm/index.mjs +391 -67
  39. package/esm/package.json +16 -14
  40. package/esm/src/eventbridge/eventbridge.d.ts +58 -0
  41. package/esm/src/eventbridge/eventbridge.d.ts.map +1 -0
  42. package/esm/src/index.d.ts +4 -0
  43. package/esm/src/index.d.ts.map +1 -1
  44. package/esm/src/lambda/lambda.d.ts +54 -0
  45. package/esm/src/lambda/lambda.d.ts.map +1 -0
  46. package/esm/src/s3/s3.d.ts +26 -4
  47. package/esm/src/s3/s3.d.ts.map +1 -1
  48. package/esm/src/scheduler/scheduler.d.ts +3 -2
  49. package/esm/src/scheduler/scheduler.d.ts.map +1 -1
  50. package/esm/src/ssm/ssm.d.ts +18 -3
  51. package/esm/src/ssm/ssm.d.ts.map +1 -1
  52. package/esm/src/util/batch-operation-error.d.ts +33 -4
  53. package/esm/src/util/batch-operation-error.d.ts.map +1 -1
  54. package/esm/src/util/lambda-function-error.d.ts +36 -0
  55. package/esm/src/util/lambda-function-error.d.ts.map +1 -0
  56. package/package.json +16 -14
package/cjs/index.cjs CHANGED
@@ -6,6 +6,8 @@ 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');
@@ -513,6 +515,86 @@ class DynamoDBService {
513
515
  }
514
516
  }
515
517
 
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
+
516
598
  /**
517
599
  * Split a list into consecutive chunks of at most `size` items, mirroring the
518
600
  * per-request caps the AWS APIs enforce on batch operations.
@@ -525,6 +607,235 @@ function chunk(items, size) {
525
607
  return chunks;
526
608
  }
527
609
 
610
+ const PUT_EVENTS_LIMIT = 10;
611
+ /**
612
+ * `Detail`, `Resources` and the entries themselves are payload carriers, so
613
+ * the INFO line carries only the endpoint id and how many entries were sent.
614
+ */
615
+ function summariseEntries$1({ EndpointId, Entries }) {
616
+ return { EndpointId, entryCount: Entries?.length ?? 0 };
617
+ }
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
+ function extractPutEventsFailures(results) {
624
+ return results.flatMap((result, chunkIndex) => extractChunkFailures(result, chunkIndex * PUT_EVENTS_LIMIT));
625
+ }
626
+ /**
627
+ * `PutEvents` reports a rejected entry by an error code on the result entry at
628
+ * the same position as the request entry.
629
+ *
630
+ * Copies only code and message out, never the request entry, so neither the
631
+ * error nor the warning can carry event detail.
632
+ */
633
+ function extractChunkFailures(result, offset) {
634
+ return (result.Entries ?? [])
635
+ .map(({ ErrorCode, ErrorMessage }, position) => ({
636
+ id: String(offset + position),
637
+ code: ErrorCode,
638
+ message: ErrorMessage,
639
+ }))
640
+ .filter(({ code }) => code !== undefined);
641
+ }
642
+ /**
643
+ * Wrapper around the AWS EventBridge client providing structured Powertools
644
+ * logging and X-Ray tracing by default.
645
+ *
646
+ * Where a method's input carries payloads, secret material or PII, the INFO
647
+ * log line omits them; the verbose levels (`POWERTOOLS_LOG_LEVEL=DEBUG` or
648
+ * `TRACE`) log full SDK inputs.
649
+ *
650
+ * Covers `putEvents` only. Named `EventBridgeService` for the event bus API;
651
+ * schedules live in `SchedulerService`.
652
+ */
653
+ class EventBridgeService {
654
+ client;
655
+ logger;
656
+ /**
657
+ * @param opts.logger - Optional Powertools logger. Defaults to `new Logger()`,
658
+ * which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
659
+ * @param opts.client - Optional pre-configured `EventBridgeClient`. When
660
+ * supplied, the wrapper does not apply X-Ray instrumentation.
661
+ */
662
+ constructor(opts) {
663
+ this.client = opts?.client ?? xray.captureAWSv3Client(new clientEventbridge.EventBridgeClient());
664
+ this.logger = opts?.logger ?? new logger.Logger();
665
+ }
666
+ /**
667
+ * Publish events to an event bus. The EventBridge API caps `PutEvents` at
668
+ * 10 entries per request, so this method auto-chunks the caller's `Entries`
669
+ * and sends one request per chunk, returning the array of outputs. The
670
+ * remaining request fields (such as `EndpointId`) are carried onto every
671
+ * chunk.
672
+ *
673
+ * Chunking is by count only. The 256 KB request size limit is not enforced
674
+ * here: a chunk that exceeds it fails at the SDK as a request-level error.
675
+ *
676
+ * Every chunk is sent before the outcome is judged. If EventBridge rejected
677
+ * any entry (it reports an error code on the result entry), a
678
+ * {@link BatchOperationError} is then thrown carrying the per-chunk results
679
+ * and the failed entries. For this method each failed entry's `id` is
680
+ * always set, to the entry's index in the caller's original `Entries` list
681
+ * across all chunks, as a string. Only `id`, `code` and `message` are
682
+ * copied out, so event detail never reaches the error.
683
+ *
684
+ * No retries are performed. Request-level SDK exceptions (throttling,
685
+ * access denied, oversize request) are not wrapped: they propagate
686
+ * unchanged and immediately, so earlier chunks may already have been
687
+ * published.
688
+ *
689
+ * At INFO level the log line includes only the endpoint id and the entry
690
+ * count, because `Detail`, `Resources` and the entries themselves are
691
+ * payload carriers.
692
+ *
693
+ * @param input - PutEventsCommandInput including Entries.
694
+ */
695
+ async putEvents(input) {
696
+ const entries = input.Entries ?? [];
697
+ this.logger.info('Putting EventBridge events', {
698
+ input: redactInput(this.logger, input, summariseEntries$1),
699
+ });
700
+ const results = [];
701
+ for (const batch of chunk(entries, PUT_EVENTS_LIMIT)) {
702
+ results.push(await this.client.send(new clientEventbridge.PutEventsCommand({ ...input, Entries: batch })));
703
+ }
704
+ return throwIfAny(this.logger, 'EventBridge putEvents', results, extractPutEventsFailures(results));
705
+ }
706
+ }
707
+
708
+ /**
709
+ * Thrown by `LambdaService.invoke` when a synchronous invocation reached the
710
+ * function but the function itself failed. Lambda reports that as an HTTP 200
711
+ * carrying a function error marker, so the SDK does not throw.
712
+ *
713
+ * `functionError` is the SDK's marker (`Handled` or `Unhandled`).
714
+ * `errorType` and `errorMessage` are parsed from the response payload when it
715
+ * has the usual `{ errorType, errorMessage }` JSON shape, otherwise undefined.
716
+ *
717
+ * Deliberately excludes the raw SDK output and the stack trace: either can
718
+ * contain the caller's payload or PII.
719
+ *
720
+ * Match on `name` rather than `instanceof` if both the CJS and ESM builds of
721
+ * this package may be loaded in one process.
722
+ */
723
+ class LambdaFunctionError extends Error {
724
+ functionName;
725
+ functionError;
726
+ name = 'LambdaFunctionError';
727
+ errorType;
728
+ errorMessage;
729
+ constructor(functionName, functionError, payload) {
730
+ super(`Lambda function ${functionName ?? '(unnamed)'} failed (${functionError})`);
731
+ this.functionName = functionName;
732
+ this.functionError = functionError;
733
+ this.errorType = payload.errorType;
734
+ this.errorMessage = payload.errorMessage;
735
+ }
736
+ }
737
+ /**
738
+ * Reads `errorType` and `errorMessage` out of a function error payload.
739
+ * Anything that is not a JSON object with string fields yields undefined for
740
+ * that field rather than failing, because the payload is whatever the invoked
741
+ * function (or runtime) chose to return.
742
+ */
743
+ function parseFunctionErrorPayload(payload) {
744
+ const empty = { errorType: undefined, errorMessage: undefined };
745
+ if (payload === undefined)
746
+ return empty;
747
+ let parsed;
748
+ try {
749
+ parsed = JSON.parse(new TextDecoder().decode(payload));
750
+ }
751
+ catch {
752
+ return empty;
753
+ }
754
+ if (typeof parsed !== 'object' || parsed === null)
755
+ return empty;
756
+ const { errorType, errorMessage } = parsed;
757
+ return {
758
+ errorType: typeof errorType === 'string' ? errorType : undefined,
759
+ errorMessage: typeof errorMessage === 'string' ? errorMessage : undefined,
760
+ };
761
+ }
762
+
763
+ /**
764
+ * `Invoke` inputs carry the invocation `Payload` and the base64 `ClientContext`
765
+ * handed to the function, both of which routinely contain caller data and PII.
766
+ * Everything else identifies the target or how to call it.
767
+ */
768
+ const INVOKE_SAFE_FIELDS = [
769
+ 'FunctionName',
770
+ 'InvocationType',
771
+ 'Qualifier',
772
+ 'LogType',
773
+ 'TenantId',
774
+ ];
775
+ /**
776
+ * Wrapper around the AWS Lambda client providing structured Powertools logging
777
+ * and X-Ray tracing by default.
778
+ *
779
+ * Where a method's input carries payloads, secret material or PII, the INFO
780
+ * log line omits them; the verbose levels (`POWERTOOLS_LOG_LEVEL=DEBUG` or
781
+ * `TRACE`) log full SDK inputs.
782
+ *
783
+ * Covers `invoke` only.
784
+ */
785
+ class LambdaService {
786
+ client;
787
+ logger;
788
+ /**
789
+ * @param opts.logger - Optional Powertools logger. Defaults to `new Logger()`,
790
+ * which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
791
+ * @param opts.client - Optional pre-configured `LambdaClient`. When
792
+ * supplied, the wrapper does not apply X-Ray instrumentation.
793
+ */
794
+ constructor(opts) {
795
+ this.client = opts?.client ?? xray.captureAWSv3Client(new clientLambda.LambdaClient());
796
+ this.logger = opts?.logger ?? new logger.Logger();
797
+ }
798
+ /**
799
+ * Invoke a Lambda function. The input is the SDK input unchanged and the
800
+ * output is the SDK output unchanged: `Payload` stays a `Uint8Array` you
801
+ * decode yourself. Choose synchronous, asynchronous or dry-run invocation
802
+ * with `InvocationType`; omitting it means synchronous (`RequestResponse`).
803
+ *
804
+ * Lambda answers HTTP 200 even when the invoked function threw, flagging it
805
+ * with `FunctionError` on the response. If that marker is present this
806
+ * method warns and throws a {@link LambdaFunctionError} carrying the
807
+ * function name, the marker, and the error type and message parsed from the
808
+ * payload when it has the usual JSON shape. The raw output and the stack
809
+ * trace are deliberately left off the error.
810
+ *
811
+ * The marker only appears on synchronous responses, so the check is
812
+ * unconditional: asynchronous (`Event`) and `DryRun` responses return
813
+ * without throwing. Failures of asynchronous invocations are therefore not
814
+ * observable here; they belong to dead-letter queues and destinations on
815
+ * the invoked function. No status code check is added; service-level
816
+ * errors such as throttling are thrown by the SDK and propagate unwrapped.
817
+ *
818
+ * At INFO level the log line includes only the function name, invocation
819
+ * type, qualifier, log type and tenant id. `Payload` and `ClientContext` are
820
+ * omitted, and responses are never logged.
821
+ *
822
+ * @param input - InvokeCommandInput including FunctionName.
823
+ */
824
+ async invoke(input) {
825
+ this.logger.info('Invoking Lambda function', {
826
+ input: redactInput(this.logger, input, INVOKE_SAFE_FIELDS),
827
+ });
828
+ const output = await this.client.send(new clientLambda.InvokeCommand(input));
829
+ if (output.FunctionError === undefined)
830
+ return output;
831
+ this.logger.warn('Lambda invoke function error', {
832
+ functionName: input.FunctionName,
833
+ functionError: output.FunctionError,
834
+ });
835
+ throw new LambdaFunctionError(input.FunctionName, output.FunctionError, parseFunctionErrorPayload(output.Payload));
836
+ }
837
+ }
838
+
528
839
  const DEFAULT_PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
529
840
  const DELETE_OBJECTS_BATCH_LIMIT = 1000;
530
841
  /**
@@ -717,6 +1028,12 @@ class S3Service {
717
1028
  * Delete multiple objects from S3, auto-chunking the request into batches
718
1029
  * of 1000 keys (the S3-enforced DeleteObjects limit). Returns one output
719
1030
  * per chunk.
1031
+ *
1032
+ * Every chunk is sent before the outcome is judged. If S3 reported a
1033
+ * per-key delete error, a {@link BatchOperationError} is then thrown
1034
+ * carrying the per-chunk results and the failed keys. Request-level SDK
1035
+ * exceptions (throttling, access denied) propagate unchanged and
1036
+ * immediately, so earlier chunks may already have been deleted.
720
1037
  */
721
1038
  async deleteObjects(bucket, keys) {
722
1039
  this.logger.info('Deleting S3 objects', {
@@ -732,13 +1049,20 @@ class S3Service {
732
1049
  Delete: { Objects: batch.map(Key => ({ Key })) },
733
1050
  })));
734
1051
  }
735
- return results;
1052
+ return throwIfAnyDeleteErrors(this.logger, 'S3 deleteObjects', results);
736
1053
  }
737
1054
  /**
738
1055
  * Delete every object in an **unversioned** bucket. Streams the listing
739
- * page-by-page and delegates each page's deletion to `deleteObjects`, so
740
- * peak memory stays bounded by one page (~1000 keys) regardless of bucket
741
- * size.
1056
+ * page-by-page and delegates each page's deletion to `deleteObjects`, so no
1057
+ * more than one page (~1000 keys) of SDK responses is held at a time. The
1058
+ * only thing that grows with the bucket is the list of deleted keys this
1059
+ * method returns.
1060
+ *
1061
+ * A page with per-key delete errors does not stop the run: every page is
1062
+ * attempted, then one {@link BatchOperationError} is thrown carrying every
1063
+ * failed key in `failed` and, per page, the keys that were deleted in
1064
+ * `results`. Request-level SDK exceptions propagate unchanged and
1065
+ * immediately, so earlier pages may already have been deleted.
742
1066
  *
743
1067
  * **Versioned buckets are out of scope.** This paginates `ListObjectsV2`,
744
1068
  * which reports only current object versions — never noncurrent versions or
@@ -749,20 +1073,39 @@ class S3Service {
749
1073
  * versioned bucket requires `ListObjectVersions` and per-version deletes;
750
1074
  * use `S3Client` directly for that.
751
1075
  *
752
- * @returns The keys this call issued deletes for.
1076
+ * @returns The keys that were deleted.
1077
+ * @throws {BatchOperationError} If S3 could not delete one or more keys.
753
1078
  */
754
1079
  async emptyBucket(bucket) {
755
1080
  this.logger.info('Emptying S3 bucket', { input: { bucket } });
756
1081
  const paginator = clientS3.paginateListObjectsV2({ client: this.client }, { Bucket: bucket });
757
- const deletedKeys = [];
1082
+ const pages = [];
1083
+ const failed = [];
758
1084
  for await (const page of paginator) {
759
1085
  const keys = (page.Contents ?? []).flatMap(o => (o.Key ? [o.Key] : []));
760
1086
  if (keys.length === 0)
761
1087
  continue;
1088
+ const outcome = await this.deletePage(bucket, keys);
1089
+ pages.push({ deletedKeys: outcome.deletedKeys });
1090
+ failed.push(...outcome.failed);
1091
+ }
1092
+ throwIfAny(this.logger, 'S3 emptyBucket', pages, failed);
1093
+ return pages.flatMap(page => page.deletedKeys);
1094
+ }
1095
+ async deletePage(bucket, keys) {
1096
+ try {
762
1097
  await this.deleteObjects(bucket, keys);
763
- deletedKeys.push(...keys);
1098
+ return { deletedKeys: keys, failed: [] };
1099
+ }
1100
+ catch (error) {
1101
+ if (!(error instanceof BatchOperationError))
1102
+ throw error;
1103
+ const failedKeys = new Set(error.failed.map(entry => entry.id));
1104
+ return {
1105
+ deletedKeys: keys.filter(key => !failedKeys.has(key)),
1106
+ failed: error.failed,
1107
+ };
764
1108
  }
765
- return deletedKeys;
766
1109
  }
767
1110
  }
768
1111
 
@@ -794,8 +1137,9 @@ function stripTargetInput(input) {
794
1137
  * `TRACE`) log full SDK inputs.
795
1138
  *
796
1139
  * Covers CRUD on schedules and their groups. Named `SchedulerService` (not
797
- * `EventBridgeSchedulerService`) so it doesn't collide with a future wrapper
798
- * over the separate EventBridge bus/rules API (`@aws-sdk/client-eventbridge`).
1140
+ * `EventBridgeSchedulerService`) so it doesn't collide with `EventBridgeService`,
1141
+ * the wrapper over the separate EventBridge bus/rules API
1142
+ * (`@aws-sdk/client-eventbridge`).
799
1143
  *
800
1144
  * `FlexibleTimeWindow` is required by `CreateSchedule` and is passed through
801
1145
  * untouched — the wrapper bakes in no default, so the caller must state their
@@ -1113,59 +1457,6 @@ class StepFunctionsService {
1113
1457
  }
1114
1458
  }
1115
1459
 
1116
- /**
1117
- * Thrown by the batch methods once every chunk has been sent and at least one
1118
- * entry was rejected.
1119
- *
1120
- * `results` holds the raw SDK output of every chunk, so the outputs of the
1121
- * entries that succeeded (message ids, sequence numbers) stay readable.
1122
- * `failed` is the normalised list of rejected entries across all chunks.
1123
- *
1124
- * Match on `name` rather than `instanceof` if both the CJS and ESM builds of
1125
- * this package may be loaded in one process.
1126
- */
1127
- class BatchOperationError extends Error {
1128
- results;
1129
- failed;
1130
- name = 'BatchOperationError';
1131
- constructor(results, failed) {
1132
- super(`Batch operation failed for ${failed.length} entries (${distinctCodes(failed).join(', ')})`);
1133
- this.results = results;
1134
- this.failed = failed;
1135
- }
1136
- }
1137
- /**
1138
- * SQS and SNS report rejected entries under `Failed` on an otherwise
1139
- * successful response, so a resolved chunk does not mean every entry was
1140
- * accepted. Returns `results` untouched when nothing failed; otherwise warns
1141
- * and throws a {@link BatchOperationError}.
1142
- *
1143
- * Only id, code and message are copied out — never the entry itself — so
1144
- * neither the error nor the warning can leak a payload.
1145
- */
1146
- function throwIfAnyFailed(logger, operation, results) {
1147
- const failed = results.flatMap(result => (result.Failed ?? []).map(({ Id, Code, Message }) => ({
1148
- id: Id,
1149
- code: Code,
1150
- message: Message,
1151
- })));
1152
- if (failed.length === 0)
1153
- return results;
1154
- logger.warn(`${operation} had rejected entries`, {
1155
- failedCount: failed.length,
1156
- codes: distinctCodes(failed),
1157
- });
1158
- throw new BatchOperationError(results, failed);
1159
- }
1160
- /**
1161
- * Distinct error codes in first-seen order, for the error message and the
1162
- * warning log line.
1163
- */
1164
- function distinctCodes(failed) {
1165
- const codes = failed.flatMap(entry => (entry.code === undefined ? [] : [entry.code]));
1166
- return [...new Set(codes)];
1167
- }
1168
-
1169
1460
  /**
1170
1461
  * Truncate a UTF-8 string to fit within `maxBytes` when encoded as UTF-8.
1171
1462
  *
@@ -1469,6 +1760,19 @@ class SQSService {
1469
1760
  }
1470
1761
 
1471
1762
  const GET_PARAMETERS_LIMIT = 10;
1763
+ /**
1764
+ * One failed entry per alias whose path SSM reported as invalid, so two
1765
+ * aliases sharing a missing path are both named.
1766
+ */
1767
+ function missingParameters(aliases, invalidPaths) {
1768
+ return Object.entries(aliases)
1769
+ .filter(([, path]) => invalidPaths.has(path))
1770
+ .map(([alias, path]) => ({
1771
+ id: path,
1772
+ code: 'ParameterNotFound',
1773
+ message: `Parameter not found for alias "${alias}"`,
1774
+ }));
1775
+ }
1472
1776
  /**
1473
1777
  * Fields safe to log at INFO level for `putParameter`. Omits `Value` (the
1474
1778
  * parameter content itself).
@@ -1519,6 +1823,9 @@ class SSMService {
1519
1823
  * @param name - The parameter name (or ARN).
1520
1824
  * @returns The parameter value, or `undefined` if the parameter has no
1521
1825
  * value set.
1826
+ * @throws When the parameter does not exist (the SDK's
1827
+ * `ParameterNotFound`). {@link SSMService.getParameters} instead returns
1828
+ * `undefined` for a missing parameter unless `required` is set.
1522
1829
  */
1523
1830
  async getParameter(name) {
1524
1831
  this.logger.info('Fetching SSM parameter', { input: { name } });
@@ -1543,16 +1850,27 @@ class SSMService {
1543
1850
  * the underlying parameter names and sends one request per chunk,
1544
1851
  * merging the results before building the alias-keyed return value.
1545
1852
  *
1853
+ * Unlike {@link SSMService.getParameter}, which throws when the parameter
1854
+ * does not exist, a missing parameter here maps to `undefined` — so a
1855
+ * typo'd path surfaces later as an undefined value. Pass
1856
+ * `{ required: true }` to fail fast instead: every chunk is still sent,
1857
+ * then a {@link BatchOperationError} is thrown whose `failed` entries
1858
+ * carry each missing path as `id`, the code `ParameterNotFound`, and the
1859
+ * alias in `message`. Request-level SDK exceptions are not wrapped.
1860
+ *
1546
1861
  * @param aliases - Record mapping each desired local alias to its SSM
1547
1862
  * parameter name (or ARN).
1863
+ * @param opts.required - Throw when any requested parameter does not
1864
+ * exist. Defaults to `false`.
1548
1865
  * @returns A record keyed by the same aliases, mapping each to the
1549
- * parameter's value, or `undefined` when the parameter is missing or has
1550
- * no value.
1866
+ * parameter's value, or `undefined` when the parameter is missing (unless
1867
+ * `required` is set) or has no value.
1551
1868
  */
1552
- async getParameters(aliases) {
1869
+ async getParameters(aliases, opts) {
1553
1870
  this.logger.info('Fetching SSM parameters', { input: { aliases } });
1554
1871
  const names = Object.values(aliases);
1555
1872
  const byPath = new Map();
1873
+ const invalidPaths = new Set();
1556
1874
  for (const batch of chunk(names, GET_PARAMETERS_LIMIT)) {
1557
1875
  const response = await this.client.send(new clientSsm.GetParametersCommand({
1558
1876
  Names: batch,
@@ -1562,6 +1880,12 @@ class SSMService {
1562
1880
  if (parameter.Name !== undefined)
1563
1881
  byPath.set(parameter.Name, parameter.Value);
1564
1882
  }
1883
+ for (const name of response.InvalidParameters ?? [])
1884
+ invalidPaths.add(name);
1885
+ }
1886
+ if (opts?.required) {
1887
+ // No per-chunk results: the SDK output of a failed lookup adds nothing
1888
+ throwIfAny(this.logger, 'SSM getParameters', [], missingParameters(aliases, invalidPaths));
1565
1889
  }
1566
1890
  const result = {};
1567
1891
  for (const alias of Object.keys(aliases)) {
@@ -1617,6 +1941,9 @@ exports.APIGatewayService = APIGatewayService;
1617
1941
  exports.APIGatewayV2Service = APIGatewayV2Service;
1618
1942
  exports.BatchOperationError = BatchOperationError;
1619
1943
  exports.DynamoDBService = DynamoDBService;
1944
+ exports.EventBridgeService = EventBridgeService;
1945
+ exports.LambdaFunctionError = LambdaFunctionError;
1946
+ exports.LambdaService = LambdaService;
1620
1947
  exports.S3Service = S3Service;
1621
1948
  exports.SNSService = SNSService;
1622
1949
  exports.SQSService = SQSService;
package/cjs/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aligent/aws-wrappers",
3
- "version": "0.5.7",
3
+ "version": "0.5.9",
4
4
  "description": "Opinionated AWS SDK wrappers with Powertools logging and X-Ray tracing",
5
5
  "engines": {
6
6
  "node": ">=18"
@@ -43,19 +43,21 @@
43
43
  "directory": "packages/aws-wrappers"
44
44
  },
45
45
  "dependencies": {
46
- "@aws-lambda-powertools/logger": "^2.33.1",
47
- "@aws-sdk/client-api-gateway": "^3.1127.0",
48
- "@aws-sdk/client-apigatewayv2": "^3.1127.0",
49
- "@aws-sdk/client-dynamodb": "^3.1127.0",
50
- "@aws-sdk/client-s3": "^3.1127.0",
51
- "@aws-sdk/client-scheduler": "^3.1127.0",
52
- "@aws-sdk/client-secrets-manager": "^3.1127.0",
53
- "@aws-sdk/client-sfn": "^3.1127.0",
54
- "@aws-sdk/client-sns": "^3.1127.0",
55
- "@aws-sdk/client-sqs": "^3.1127.0",
56
- "@aws-sdk/client-ssm": "^3.1127.0",
57
- "@aws-sdk/lib-dynamodb": "^3.1127.0",
58
- "@aws-sdk/s3-request-presigner": "^3.1127.0",
46
+ "@aws-lambda-powertools/logger": "^2.36.0",
47
+ "@aws-sdk/client-api-gateway": "^3.1160.0",
48
+ "@aws-sdk/client-apigatewayv2": "^3.1160.0",
49
+ "@aws-sdk/client-dynamodb": "^3.1160.0",
50
+ "@aws-sdk/client-eventbridge": "^3.1160.0",
51
+ "@aws-sdk/client-lambda": "^3.1160.0",
52
+ "@aws-sdk/client-s3": "^3.1160.0",
53
+ "@aws-sdk/client-scheduler": "^3.1160.0",
54
+ "@aws-sdk/client-secrets-manager": "^3.1160.0",
55
+ "@aws-sdk/client-sfn": "^3.1160.0",
56
+ "@aws-sdk/client-sns": "^3.1160.0",
57
+ "@aws-sdk/client-sqs": "^3.1160.0",
58
+ "@aws-sdk/client-ssm": "^3.1160.0",
59
+ "@aws-sdk/lib-dynamodb": "^3.1160.0",
60
+ "@aws-sdk/s3-request-presigner": "^3.1160.0",
59
61
  "aws-xray-sdk-core": "^3.12.0"
60
62
  },
61
63
  "author": "Aligent",
@@ -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;AA4CrC;;;;;;;;;;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"}