@aspan-corporation/ac-shared 1.2.7 → 1.2.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.
package/lib/index.js CHANGED
@@ -1172,7 +1172,7 @@ import { IdempotencyConfig } from "@aws-lambda-powertools/idempotency";
1172
1172
  import { DynamoDBPersistenceLayer } from "@aws-lambda-powertools/idempotency/dynamodb";
1173
1173
  import { Logger as Logger2 } from "@aws-lambda-powertools/logger";
1174
1174
  import { injectLambdaContext } from "@aws-lambda-powertools/logger/middleware";
1175
- import { Metrics } from "@aws-lambda-powertools/metrics";
1175
+ import { Metrics, MetricUnit } from "@aws-lambda-powertools/metrics";
1176
1176
  import { logMetrics } from "@aws-lambda-powertools/metrics/middleware";
1177
1177
  import { Tracer } from "@aws-lambda-powertools/tracer";
1178
1178
  import { captureLambdaHandler } from "@aws-lambda-powertools/tracer/middleware";
@@ -1421,7 +1421,7 @@ var http_error_handler_default = httpErrorHandlerMiddleware;
1421
1421
  import { randomUUID } from "node:crypto";
1422
1422
  var logger = new Logger2();
1423
1423
  var tracer = new Tracer();
1424
- var metrics = new Metrics();
1424
+ var metrics = new Metrics({ namespace: "aspan-corporation" });
1425
1425
  var withMiddlewares = (handler) => core_default(handler).use(injectLambdaContext(logger)).use(captureLambdaHandler(tracer)).use(logMetrics(metrics, { captureColdStartMetric: true })).use({
1426
1426
  before: async (request) => {
1427
1427
  if (!logger.getCorrelationId()) {
@@ -1433,10 +1433,11 @@ var withMiddlewares = (handler) => core_default(handler).use(injectLambdaContext
1433
1433
  request.context.metrics = metrics;
1434
1434
  }
1435
1435
  }).use({
1436
- onError: async ({ error, context }) => {
1437
- context.logger.error("Error handled by middleware", {
1436
+ onError: async ({ error, context: { logger: logger2, metrics: metrics2 } }) => {
1437
+ logger2.error("Error handled by middleware", {
1438
1438
  error
1439
1439
  });
1440
+ metrics2.addMetric("ErrorHandled", MetricUnit.Count, 1);
1440
1441
  }
1441
1442
  }).use(http_error_handler_default());
1442
1443
  var getPersistenceStore = () => {
package/lib/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/services/s3.ts", "../src/utils/index.ts", "../src/utils/normalizeErrorMessage.ts", "../src/utils/thumbsKey.ts", "../src/utils/helpers.ts", "../src/utils/processMeta.ts", "../src/services/dynamoDB.ts", "../src/services/ssm.ts", "../src/services/sqs.ts", "../src/services/sts.ts", "../src/services/location.ts", "../node_modules/@aws-lambda-powertools/batch/node_modules/@aws/lambda-invoke-store/dist-es/invoke-store.js", "../node_modules/@aws-lambda-powertools/batch/node_modules/@aws-lambda-powertools/commons/lib/esm/constants.js", "../node_modules/@aws-lambda-powertools/batch/node_modules/@aws-lambda-powertools/commons/lib/esm/envUtils.js", "../node_modules/@aws-lambda-powertools/batch/lib/esm/BatchProcessingStore.js", "../node_modules/@aws-lambda-powertools/batch/lib/esm/BasePartialProcessor.js", "../node_modules/@aws-lambda-powertools/batch/lib/esm/constants.js", "../node_modules/@aws-lambda-powertools/batch/lib/esm/errors.js", "../node_modules/@aws-lambda-powertools/batch/lib/esm/BasePartialBatchProcessor.js", "../node_modules/@aws-lambda-powertools/batch/lib/esm/BatchProcessor.js", "../node_modules/@aws-lambda-powertools/batch/lib/esm/processPartialResponse.js", "../src/lambda/index.ts", "../node_modules/@middy/core/index.js", "../node_modules/@middy/util/index.js", "../node_modules/@middy/http-error-handler/index.js"],
4
- "sourcesContent": ["import {\n GetObjectCommand,\n GetObjectCommandInput,\n HeadObjectCommand,\n HeadObjectCommandInput,\n ListObjectsV2Command,\n ListObjectsV2CommandInput,\n PutObjectCommand,\n PutObjectCommandInput,\n PutObjectCommandOutput,\n S3Client\n} from \"@aws-sdk/client-s3\";\nimport { AssumeRoleCommandOutput } from \"@aws-sdk/client-sts\";\nimport { Upload } from \"@aws-sdk/lib-storage\";\nimport assert from \"node:assert/strict\";\nimport { PassThrough } from \"node:stream\";\nimport { getObjectWithAssumeRoleCommandOutputAttribute } from \"../utils/index.js\";\nimport { getSignedUrl } from \"@aws-sdk/s3-request-presigner\";\nimport { Logger } from \"@aws-lambda-powertools/logger\";\n\nexport class S3Service {\n logger: Logger;\n client: S3Client;\n constructor({\n logger,\n client,\n assumeRoleCommandOutput,\n region\n }: {\n logger: Logger;\n client?: S3Client;\n assumeRoleCommandOutput?: AssumeRoleCommandOutput;\n region?: string;\n }) {\n this.logger = logger;\n\n if (client) {\n this.client = client;\n } else {\n assert(region, \"Region must be provided if client is not passed\");\n this.client = new S3Client({\n region,\n ...getObjectWithAssumeRoleCommandOutputAttribute(\n assumeRoleCommandOutput\n )\n });\n }\n }\n\n createS3UploadStream(putObjectCommandInput: PutObjectCommandInput) {\n this.logger.debug(\"upload stream started\", { putObjectCommandInput });\n\n const pass = new PassThrough();\n\n const parallelUploads = new Upload({\n client: this.client,\n params: {\n ...putObjectCommandInput,\n Body: pass\n }\n });\n\n const donePromise = parallelUploads\n .done()\n .then(() => this.logger.debug(\"upload stream finished\"))\n .catch((err) => {\n this.logger.error(\"upload stream error\", err);\n pass.destroy(err);\n });\n\n return { stream: pass, done: donePromise };\n }\n\n async createS3DownloadStream(getObjectCommandInput: GetObjectCommandInput) {\n this.logger.debug(\"download stream started\", { getObjectCommandInput });\n\n const item = await this.client.send(\n new GetObjectCommand(getObjectCommandInput)\n );\n\n this.logger.debug(\"download stream finished\");\n\n return item.Body;\n }\n\n async listObjectsV2(listObjectsV2CommandInput: ListObjectsV2CommandInput) {\n this.logger.debug(\"listObjectsV2\", { listObjectsV2CommandInput });\n return await this.client.send(\n new ListObjectsV2Command(listObjectsV2CommandInput)\n );\n }\n\n async getObject(\n getObjectCommandInput: GetObjectCommandInput\n ): Promise<Buffer> {\n this.logger.debug(\"getObject\", { getObjectCommandInput });\n\n const stream = await this.createS3DownloadStream(getObjectCommandInput);\n\n return Buffer.from(await stream.transformToByteArray());\n }\n\n async getSignedUrl(\n getObjectCommandInput: GetObjectCommandInput\n ): Promise<string> {\n this.logger.debug(\"getSignedUrl\", { getObjectCommandInput });\n\n const signedUrl = await getSignedUrl(\n this.client,\n new GetObjectCommand(getObjectCommandInput),\n { expiresIn: 3600 }\n );\n\n return signedUrl;\n }\n\n async putObject(\n putObjectCommandInput: PutObjectCommandInput\n ): Promise<PutObjectCommandOutput> {\n this.logger.debug(\"putObject\", { putObjectCommandInput });\n\n return await this.client.send(new PutObjectCommand(putObjectCommandInput));\n }\n\n async headObject(headObjectCommandInput: HeadObjectCommandInput) {\n this.logger.debug(\"headObject\", { headObjectCommandInput });\n return await this.client.send(\n new HeadObjectCommand(headObjectCommandInput)\n );\n }\n\n async checkIfObjectExists(\n headObjectCommandInput: HeadObjectCommandInput\n ): Promise<boolean> {\n this.logger.debug(\"checkIfObjectExists\", { headObjectCommandInput });\n\n try {\n await this.headObject(headObjectCommandInput);\n return true;\n } catch (error) {\n if (error.name === \"NotFound\") {\n return false;\n }\n throw error;\n }\n }\n}\n", "import assert from \"node:assert/strict\";\n\nexport const assertEnvVar = (envVar: string): string => {\n assert(process.env[envVar], `${envVar} is not set`);\n return process.env[envVar];\n};\n\nexport * from \"./normalizeErrorMessage.js\";\nexport * from \"./thumbsKey.js\";\nexport * from \"./helpers.js\";\nexport * from \"./processMeta.js\";\n", "export const normalizeErrorMessage = (error: unknown): string => {\n if (error instanceof Error) {\n return error.message;\n } else if (typeof error === \"string\") {\n return error;\n } else if (typeof error === \"object\" && error !== null) {\n return JSON.stringify(error);\n } else {\n return String(error);\n }\n};\n", "import { extname } from \"node:path\";\n\nexport const JPEG_EXTENSION = \"jpeg\";\nexport const JPG_EXTENSION = \"jpg\";\nexport const HEIC_EXTENSION = \"heic\";\nexport const MOV_EXTENSION = \"mov\";\nexport const THUMBS_EXTENSION = JPG_EXTENSION;\nexport const ENCODED_VIDEO_EXTENSION = \"mp4\";\nexport const ALLOWED_EXTENSIONS = [\n JPEG_EXTENSION,\n JPG_EXTENSION,\n HEIC_EXTENSION\n];\nexport const ALLOWED_VIDEO_EXTENSIONS = [MOV_EXTENSION];\n\nexport const THUMBNAIL_RESOLUTIONS = [\n [200, 200],\n [1180, 820]\n];\n\nexport const getThumbsKey = ({\n key,\n width,\n height\n}: {\n key: string;\n width: number;\n height: number;\n}) => {\n return `${key\n .split(\".\")\n .slice(0, -1)\n .join(\".\")}.${width}x${height}.${THUMBS_EXTENSION}`;\n};\n\nexport const getEncodedVideoKey = ({ key }: { key: string }) => {\n return `${key.split(\".\").slice(0, -1).join(\".\")}.${ENCODED_VIDEO_EXTENSION}`;\n};\n\nexport const getKeyExtension = (key: string) =>\n extname(key).slice(1).toLowerCase();\n\nexport const isAllowedExtension = (key: string) => {\n const ext = getKeyExtension(key);\n return ALLOWED_EXTENSIONS.includes(ext);\n};\n\nexport const isAllowedVideoExtension = (key: string) => {\n const ext = getKeyExtension(key);\n return ALLOWED_VIDEO_EXTENSIONS.includes(ext);\n};\n", "import { AssumeRoleCommandOutput } from \"@aws-sdk/client-sts\";\n\nexport const getObjectWithAssumeRoleCommandOutputAttribute = (\n assumeRoleCommandOutput?: AssumeRoleCommandOutput\n) =>\n assumeRoleCommandOutput\n ? {\n credentials: {\n accessKeyId: assumeRoleCommandOutput?.Credentials?.AccessKeyId,\n secretAccessKey:\n assumeRoleCommandOutput?.Credentials?.SecretAccessKey,\n sessionToken: assumeRoleCommandOutput?.Credentials?.SessionToken\n }\n }\n : {};\n\nexport const getObjectWithStackAttribute = (error: any) =>\n error && error instanceof Error ? { stack: error.stack } : {};\n", "import { DynamoDBService, LocationService } from \"../services/index.js\";\nimport type { SearchForPositionResult } from \"@aws-sdk/client-location\";\nimport assert from \"node:assert/strict\";\nimport { Logger } from \"@aws-lambda-powertools/logger\";\nimport { getKeyExtension } from \"./thumbsKey.js\";\n\ntype ExtractMetadataParams = {\n id: string;\n meta: Array<{ key: string; value: string }>;\n logger: Logger;\n locationService: LocationService;\n dynamoDBService: DynamoDBService;\n metaTableName: string;\n size: number;\n};\n\ntype Tag = { key: string; value: string };\n\n/**\n * 1. read <id>\n * 2. if <id> doesn't exist then use PutCommand\n * 3. if it does exist then match new tags and old tags\n * 4. add all old tags that are not present in new tags,\n *\n */\nexport const processMeta = async ({\n id,\n meta,\n metaTableName,\n size,\n logger,\n locationService,\n dynamoDBService\n}: ExtractMetadataParams) => {\n // expand location data\n const latitude = Number(meta.find((tag) => tag.key === \"latitude\")?.value);\n const longitude = Number(meta.find((tag) => tag.key === \"longitude\")?.value);\n\n let geoPositionResult: SearchForPositionResult | undefined;\n if (!Number.isNaN(longitude) && !Number.isNaN(latitude)) {\n try {\n const res = await locationService.searchPlaceIndexForPositionCommand({\n IndexName: \"TauPlaceIndex\",\n Position: [longitude, latitude]\n });\n\n if (res?.Results && res?.Results?.length > 0) {\n geoPositionResult = res?.Results[0];\n } else {\n throw Error(\"Can not resolve geo data\");\n }\n } catch (error) {\n logger.error(\"Error fetching geo data\", {\n message: error instanceof Error ? error.message : \"\"\n });\n }\n }\n\n const newTags = [\n ...meta,\n ...(meta.find((tag) => tag.key === \"dateCreated\")\n ? []\n : extractMetaFromKey(id)),\n { key: \"extension\", value: getKeyExtension(id) },\n { key: \"size\", value: String(size) },\n { key: \"sizeMb\", value: String(Math.round(size / 1024 ** 2)) },\n ...(geoPositionResult?.Place?.Label\n ? [{ key: \"label\", value: geoPositionResult?.Place?.Label }]\n : []),\n ...(geoPositionResult?.Place?.Country\n ? [{ key: \"country\", value: geoPositionResult?.Place?.Country }]\n : []),\n ...(geoPositionResult?.Place?.Region\n ? [{ key: \"region\", value: geoPositionResult?.Place?.Region }]\n : []),\n ...(geoPositionResult?.Place?.SubRegion\n ? [{ key: \"subRegion\", value: geoPositionResult?.Place?.SubRegion }]\n : []),\n ...(geoPositionResult?.Place?.Municipality\n ? [{ key: \"municipality\", value: geoPositionResult?.Place?.Municipality }]\n : []),\n ...(geoPositionResult?.Place?.Neighborhood\n ? [{ key: \"neighborhood\", value: geoPositionResult?.Place?.Neighborhood }]\n : []),\n ...(geoPositionResult?.Place?.PostalCode\n ? [{ key: \"postalCode\", value: geoPositionResult?.Place?.PostalCode }]\n : [])\n ].map((tag) => ({\n key: \"ac:tau:\" + tag.key,\n value: tag.value\n }));\n\n logger.debug(\"metaData\", { newTags });\n\n logger.debug(\"trying to read existing metadata\");\n const getResponse = await dynamoDBService.getCommand({\n TableName: metaTableName,\n Key: {\n id\n }\n });\n const oldTags: Tag[] = getResponse.Item?.tags;\n logger.debug(\"existing tags\", { getResponse });\n\n const reconciledTags = reconcileTags({ newTags, oldTags }, logger);\n logger.debug(\"result\", { reconciledTags });\n\n const updateResponse = await dynamoDBService.updateCommand({\n TableName: metaTableName,\n Key: {\n id\n },\n UpdateExpression: \"set tags = :tags\",\n ExpressionAttributeValues: {\n \":tags\": reconciledTags\n },\n ReturnValues: \"ALL_NEW\"\n });\n\n logger.debug(\"sent UpdateCommand\", { updateResponse });\n};\n\nconst reconcileTags = (\n { oldTags = [], newTags = [] }: { newTags: Tag[]; oldTags: Tag[] },\n logger: Logger\n) =>\n oldTags.reduce((acc, cur) => {\n if (acc.find((element) => element.key === cur.key)) {\n return acc;\n } else {\n logger.debug(\"added\", cur);\n\n return [...acc, cur];\n }\n }, newTags);\n\nconst SUBSTRING_ANSI_DATES_BEGIN_WITH = \"20\";\n\nconst extractMetaFromKey = (key: string | undefined | null): Array<Tag> => {\n if (!key) return [];\n\n let firstToken: string | undefined = undefined;\n try {\n const folder = key.split(\"/\").at(-2);\n assert(typeof folder === \"string\");\n firstToken = folder.split(\".\")[0];\n } catch (error) {}\n\n if (\n firstToken === undefined ||\n firstToken.length !== 8 ||\n !firstToken.startsWith(SUBSTRING_ANSI_DATES_BEGIN_WITH)\n )\n return [];\n\n const year = Number(firstToken.substring(0, 4));\n const month = Number(firstToken.substring(4, 6)) - 1;\n const day = Number(firstToken.substring(6));\n\n if (isNaN(year) || isNaN(month) || isNaN(day)) return [];\n\n // mon starts from 0\n // day starts from 1\n if (year < 2000 || month < 1 || month > 11 || day < 1 || day > 31) return [];\n\n const dateCreatedBin = new Date(year, month, day);\n\n return [\n { key: \"dateCreated\", value: dateCreatedBin.toISOString() },\n { key: \"yearCreated\", value: dateCreatedBin.getFullYear().toString() },\n { key: \"dayCreated\", value: dateCreatedBin.getDate().toString() },\n {\n key: \"monthCreated\",\n value: (dateCreatedBin.getMonth() + 1).toString()\n }\n ];\n};\n", "import { DynamoDBClient } from \"@aws-sdk/client-dynamodb\";\nimport { AssumeRoleCommandOutput } from \"@aws-sdk/client-sts\";\nimport {\n DynamoDBDocumentClient,\n GetCommand,\n GetCommandInput,\n GetCommandOutput,\n PutCommand,\n PutCommandInput,\n PutCommandOutput,\n QueryCommand,\n QueryCommandInput,\n QueryCommandOutput,\n UpdateCommand,\n UpdateCommandInput,\n UpdateCommandOutput\n} from \"@aws-sdk/lib-dynamodb\";\nimport assert from \"node:assert/strict\";\nimport { getObjectWithAssumeRoleCommandOutputAttribute } from \"../utils/index.js\";\nimport { Logger } from \"@aws-lambda-powertools/logger\";\n\nexport class DynamoDBService {\n logger: Logger;\n client: DynamoDBClient;\n documentClient: DynamoDBDocumentClient;\n\n constructor({\n logger,\n client,\n assumeRoleCommandOutput,\n region\n }: {\n logger: Logger;\n client?: DynamoDBClient;\n assumeRoleCommandOutput?: AssumeRoleCommandOutput;\n region?: string;\n }) {\n this.logger = logger;\n\n if (client) {\n this.client = client;\n } else {\n assert(region, \"Region must be provided if client is not passed\");\n this.client = new DynamoDBClient({\n region,\n ...getObjectWithAssumeRoleCommandOutputAttribute(\n assumeRoleCommandOutput\n )\n });\n }\n\n this.documentClient = DynamoDBDocumentClient.from(this.client);\n }\n\n async getCommand(\n getCommandInput: GetCommandInput\n ): Promise<GetCommandOutput> {\n return await this.documentClient.send(new GetCommand(getCommandInput));\n }\n\n async updateCommand(\n updateCommandInput: UpdateCommandInput\n ): Promise<UpdateCommandOutput> {\n return await this.documentClient.send(\n new UpdateCommand(updateCommandInput)\n );\n }\n\n async queryCommand(\n queryCommandInput: QueryCommandInput\n ): Promise<QueryCommandOutput> {\n return await this.documentClient.send(new QueryCommand(queryCommandInput));\n }\n\n async putCommand(\n putCommandInput: PutCommandInput\n ): Promise<PutCommandOutput> {\n return await this.documentClient.send(new PutCommand(putCommandInput));\n }\n\n async checkIfItemExists(\n checkInput: Pick<GetCommandInput, \"TableName\" | \"Key\">\n ): Promise<boolean> {\n const result = await this.getCommand(checkInput);\n\n return !!result.Item;\n }\n}\n", "import {\n GetParameterCommand,\n GetParameterCommandInput,\n GetParameterCommandOutput,\n PutParameterCommand,\n PutParameterCommandInput,\n PutParameterCommandOutput,\n SSMClient\n} from \"@aws-sdk/client-ssm\";\nimport { AssumeRoleCommandOutput } from \"@aws-sdk/client-sts\";\nimport assert from \"node:assert/strict\";\nimport { getObjectWithAssumeRoleCommandOutputAttribute } from \"../utils/index.js\";\nimport { Logger } from \"@aws-lambda-powertools/logger\";\n\nexport class SSMService {\n logger: Logger;\n client: SSMClient;\n\n constructor({\n logger,\n client,\n assumeRoleCommandOutput,\n region\n }: {\n logger: Logger;\n client?: SSMClient;\n assumeRoleCommandOutput?: AssumeRoleCommandOutput;\n region?: string;\n }) {\n this.logger = logger;\n\n if (client) {\n this.client = client;\n } else {\n assert(region, \"Region must be provided if client is not passed\");\n this.client = new SSMClient({\n region,\n ...getObjectWithAssumeRoleCommandOutputAttribute(\n assumeRoleCommandOutput\n )\n });\n }\n }\n\n async getParameter(\n params: GetParameterCommandInput\n ): Promise<GetParameterCommandOutput> {\n return await this.client.send(new GetParameterCommand(params));\n }\n\n async putParameter(\n params: PutParameterCommandInput\n ): Promise<PutParameterCommandOutput> {\n return await this.client.send(new PutParameterCommand(params));\n }\n}\n", "import {\n DeleteMessageCommand,\n DeleteMessageCommandInput,\n DeleteMessageCommandOutput,\n ReceiveMessageCommand,\n ReceiveMessageCommandInput,\n ReceiveMessageCommandOutput,\n SQSClient,\n SendMessageBatchCommand,\n SendMessageBatchCommandInput,\n SendMessageBatchCommandOutput,\n SendMessageCommand,\n SendMessageCommandInput,\n SendMessageCommandOutput\n} from \"@aws-sdk/client-sqs\";\nimport { AssumeRoleCommandOutput } from \"@aws-sdk/client-sts\";\nimport assert from \"node:assert/strict\";\nimport { getObjectWithAssumeRoleCommandOutputAttribute } from \"../utils/index.js\";\nimport { Logger } from \"@aws-lambda-powertools/logger\";\n\nexport class SQSService {\n logger: Logger;\n client: SQSClient;\n\n constructor({\n logger,\n client,\n assumeRoleCommandOutput,\n region\n }: {\n logger: Logger;\n client?: SQSClient;\n assumeRoleCommandOutput?: AssumeRoleCommandOutput;\n region?: string;\n }) {\n this.logger = logger;\n\n if (client) {\n this.client = client;\n } else {\n assert(region, \"Region must be provided if client is not passed\");\n this.client = new SQSClient({\n region,\n ...getObjectWithAssumeRoleCommandOutputAttribute(\n assumeRoleCommandOutput\n )\n });\n }\n }\n\n async sendMessage(\n params: SendMessageCommandInput\n ): Promise<SendMessageCommandOutput> {\n return await this.client.send(new SendMessageCommand(params));\n }\n\n async sendMessageBatch(\n params: SendMessageBatchCommandInput\n ): Promise<SendMessageBatchCommandOutput> {\n return await this.client.send(new SendMessageBatchCommand(params));\n }\n\n async receiveMessage(\n params: ReceiveMessageCommandInput\n ): Promise<ReceiveMessageCommandOutput> {\n return await this.client.send(new ReceiveMessageCommand(params));\n }\n\n async deleteMessage(\n params: DeleteMessageCommandInput\n ): Promise<DeleteMessageCommandOutput> {\n return await this.client.send(new DeleteMessageCommand(params));\n }\n}\n", "import {\n AssumeRoleCommand,\n AssumeRoleCommandInput,\n GetCallerIdentityCommand,\n STSClient\n} from \"@aws-sdk/client-sts\";\nimport assert from \"node:assert/strict\";\nimport { Logger } from \"@aws-lambda-powertools/logger\";\n\nexport class STSService {\n logger: Logger;\n client: STSClient;\n\n constructor({\n logger,\n region,\n client\n }: {\n logger: Logger;\n region?: string;\n client?: STSClient;\n }) {\n if (logger) {\n this.logger = logger;\n } else {\n this.logger = new Logger();\n this.logger.appendKeys({ scope: \"STSService\" });\n }\n\n if (client) {\n this.client = client;\n } else {\n assert(region, \"Region must be provided if client is not passed\");\n this.client = new STSClient({\n region\n });\n }\n }\n\n async getCallerIdentity() {\n this.logger.debug(\"getCallerIdentity\");\n\n return await this.client.send(new GetCallerIdentityCommand({}));\n }\n\n async assumeRole(assumeRoleCommandInput: AssumeRoleCommandInput) {\n this.logger.debug(\"assumeRole\", { assumeRoleCommandInput });\n\n return await this.client.send(\n new AssumeRoleCommand(assumeRoleCommandInput)\n );\n }\n}\n", "import {\n LocationClient,\n SearchPlaceIndexForPositionCommand,\n SearchPlaceIndexForPositionCommandInput,\n SearchPlaceIndexForPositionCommandOutput\n} from \"@aws-sdk/client-location\";\nimport { AssumeRoleCommandOutput } from \"@aws-sdk/client-sts\";\nimport assert from \"node:assert/strict\";\nimport { getObjectWithAssumeRoleCommandOutputAttribute } from \"../utils/index.js\";\nimport { Logger } from \"@aws-lambda-powertools/logger\";\n\nexport class LocationService {\n logger: Logger;\n client: LocationClient;\n\n constructor({\n logger,\n client,\n assumeRoleCommandOutput,\n region\n }: {\n logger: Logger;\n client?: LocationClient;\n assumeRoleCommandOutput?: AssumeRoleCommandOutput;\n region?: string;\n }) {\n this.logger = logger;\n\n if (client) {\n this.client = client;\n } else {\n assert(region, \"Region must be provided if client is not passed\");\n this.client = new LocationClient({\n region,\n ...getObjectWithAssumeRoleCommandOutputAttribute(\n assumeRoleCommandOutput\n )\n });\n }\n }\n\n async searchPlaceIndexForPositionCommand(\n searchPlaceIndexForPositionCommandInput: SearchPlaceIndexForPositionCommandInput\n ): Promise<SearchPlaceIndexForPositionCommandOutput> {\n return await this.client.send(\n new SearchPlaceIndexForPositionCommand(\n searchPlaceIndexForPositionCommandInput\n )\n );\n }\n}\n", "const PROTECTED_KEYS = {\n REQUEST_ID: Symbol.for(\"_AWS_LAMBDA_REQUEST_ID\"),\n X_RAY_TRACE_ID: Symbol.for(\"_AWS_LAMBDA_X_RAY_TRACE_ID\"),\n TENANT_ID: Symbol.for(\"_AWS_LAMBDA_TENANT_ID\"),\n};\nconst NO_GLOBAL_AWS_LAMBDA = [\"true\", \"1\"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA ?? \"\");\nif (!NO_GLOBAL_AWS_LAMBDA) {\n globalThis.awslambda = globalThis.awslambda || {};\n}\nclass InvokeStoreBase {\n static PROTECTED_KEYS = PROTECTED_KEYS;\n isProtectedKey(key) {\n return Object.values(PROTECTED_KEYS).includes(key);\n }\n getRequestId() {\n return this.get(PROTECTED_KEYS.REQUEST_ID) ?? \"-\";\n }\n getXRayTraceId() {\n return this.get(PROTECTED_KEYS.X_RAY_TRACE_ID);\n }\n getTenantId() {\n return this.get(PROTECTED_KEYS.TENANT_ID);\n }\n}\nclass InvokeStoreSingle extends InvokeStoreBase {\n currentContext;\n getContext() {\n return this.currentContext;\n }\n hasContext() {\n return this.currentContext !== undefined;\n }\n get(key) {\n return this.currentContext?.[key];\n }\n set(key, value) {\n if (this.isProtectedKey(key)) {\n throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`);\n }\n this.currentContext = this.currentContext || {};\n this.currentContext[key] = value;\n }\n run(context, fn) {\n this.currentContext = context;\n return fn();\n }\n}\nclass InvokeStoreMulti extends InvokeStoreBase {\n als;\n static async create() {\n const instance = new InvokeStoreMulti();\n const asyncHooks = await import('node:async_hooks');\n instance.als = new asyncHooks.AsyncLocalStorage();\n return instance;\n }\n getContext() {\n return this.als.getStore();\n }\n hasContext() {\n return this.als.getStore() !== undefined;\n }\n get(key) {\n return this.als.getStore()?.[key];\n }\n set(key, value) {\n if (this.isProtectedKey(key)) {\n throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`);\n }\n const store = this.als.getStore();\n if (!store) {\n throw new Error(\"No context available\");\n }\n store[key] = value;\n }\n run(context, fn) {\n return this.als.run(context, fn);\n }\n}\nvar InvokeStore;\n(function (InvokeStore) {\n let instance = null;\n async function getInstanceAsync() {\n if (!instance) {\n instance = (async () => {\n const isMulti = \"AWS_LAMBDA_MAX_CONCURRENCY\" in process.env;\n const newInstance = isMulti\n ? await InvokeStoreMulti.create()\n : new InvokeStoreSingle();\n if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda?.InvokeStore) {\n return globalThis.awslambda.InvokeStore;\n }\n else if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda) {\n globalThis.awslambda.InvokeStore = newInstance;\n return newInstance;\n }\n else {\n return newInstance;\n }\n })();\n }\n return instance;\n }\n InvokeStore.getInstanceAsync = getInstanceAsync;\n InvokeStore._testing = process.env.AWS_LAMBDA_BENCHMARK_MODE === \"1\"\n ? {\n reset: () => {\n instance = null;\n if (globalThis.awslambda?.InvokeStore) {\n delete globalThis.awslambda.InvokeStore;\n }\n globalThis.awslambda = {};\n },\n }\n : undefined;\n})(InvokeStore || (InvokeStore = {}));\n\nexport { InvokeStore, InvokeStoreBase };\n", "const AWS_LAMBDA_MAX_CONCURRENCY = 'AWS_LAMBDA_MAX_CONCURRENCY';\nconst POWERTOOLS_DEV_ENV_VAR = 'POWERTOOLS_DEV';\nconst POWERTOOLS_SERVICE_NAME_ENV_VAR = 'POWERTOOLS_SERVICE_NAME';\nconst XRAY_TRACE_ID_ENV_VAR = '_X_AMZN_TRACE_ID';\nexport { AWS_LAMBDA_MAX_CONCURRENCY, POWERTOOLS_DEV_ENV_VAR, POWERTOOLS_SERVICE_NAME_ENV_VAR, XRAY_TRACE_ID_ENV_VAR, };\n", "import '@aws/lambda-invoke-store';\nimport { AWS_LAMBDA_MAX_CONCURRENCY, POWERTOOLS_DEV_ENV_VAR, POWERTOOLS_SERVICE_NAME_ENV_VAR, XRAY_TRACE_ID_ENV_VAR, } from './constants.js';\n/**\n * Get a string from the environment variables.\n *\n * @example\n * ```ts\n * import { getStringFromEnv } from '@aws-lambda-powertools/commons/utils/env';\n *\n * const myEnvVar = getStringFromEnv({\n * key: 'MY_ENV_VAR',\n * errorMessage: 'MY_ENV_VAR is required for this function',\n * });\n * ```\n *\n * By default, the value is trimmed and always required.\n *\n * You can also provide a default value, which will be returned if the environment variable is not set instead of throwing an error.\n *\n * @example\n * ```ts\n * import { getStringFromEnv } from '@aws-lambda-powertools/commons/utils/env';\n *\n * const myEnvVar = getStringFromEnv({\n * key: 'MY_ENV_VAR',\n * defaultValue: 'defaultValue',\n * });\n * ```\n *\n * @param options - The options for getting the string.\n * @param options.key - The key of the environment variable.\n * @param options.defaultValue - Optional default value to return if the environment variable is not set.\n * @param options.errorMessage - Optional error message to throw if the environment variable is not set and no default value is provided. Defaults to `\"Environment variable <key> is required\"`.\n */\nconst getStringFromEnv = ({ key, defaultValue, errorMessage, }) => {\n const value = process.env[key];\n if (value === undefined) {\n if (defaultValue !== undefined) {\n return defaultValue;\n }\n if (errorMessage) {\n throw new Error(errorMessage);\n }\n throw new Error(`Environment variable ${key} is required`);\n }\n return value.trim();\n};\n/**\n * Get a number from the environment variables.\n *\n * @example\n * ```ts\n * import { getNumberFromEnv } from '@aws-lambda-powertools/commons/utils/env';\n *\n * const myEnvVar = getNumberFromEnv({\n * key: 'MY_ENV_VAR',\n * errorMessage: 'MY_ENV_VAR is required for this function',\n * });\n * ```\n *\n * By default, the value is trimmed before being converted to a number and always required.\n *\n * You can also provide a default value, which will be returned if the environment variable is not set instead of throwing an error.\n *\n * @example\n * ```ts\n * import { getNumberFromEnv } from '@aws-lambda-powertools/commons/utils/env';\n *\n * const myEnvVar = getNumberFromEnv({\n * key: 'MY_ENV_VAR',\n * defaultValue: 42,\n * });\n * ```\n *\n * @param options - The options for getting the number.\n * @param options.key - The key of the environment variable.\n * @param options.defaultValue - The default value to return if the environment variable is not set.\n * @param options.errorMessage - Optional error message to throw if the environment variable is not set and no default value is provided. Defaults to `\"Environment variable <key> is required\"`.\n */\nconst getNumberFromEnv = ({ key, defaultValue, errorMessage, }) => {\n const value = getStringFromEnv({\n key,\n defaultValue: String(defaultValue),\n errorMessage,\n });\n const parsedValue = Number(value);\n if (Number.isNaN(parsedValue)) {\n throw new TypeError(`Environment variable ${key} must be a number`);\n }\n return parsedValue;\n};\nconst truthyValues = new Set(['1', 'y', 'yes', 't', 'true', 'on']);\nconst falsyValues = new Set(['0', 'n', 'no', 'f', 'false', 'off']);\n/**\n * Get a boolean from the environment variables.\n *\n * @example\n * ```ts\n * import { getBooleanFromEnv } from '@aws-lambda-powertools/commons/utils/env';\n *\n * const myEnvVar = getBooleanFromEnv({\n * key: 'MY_ENV_VAR',\n * errorMessage: 'MY_ENV_VAR is required for this function',\n * });\n * ```\n *\n * By default, the value is trimmed before being converted to a boolean and always required.\n *\n * You can also provide a default value, which will be returned if the environment variable is not set instead of throwing an error.\n *\n * @example\n * ```ts\n * import { getBooleanFromEnv } from '@aws-lambda-powertools/commons/utils/env';\n *\n * const myEnvVar = getBooleanFromEnv({\n * key: 'MY_ENV_VAR',\n * defaultValue: true,\n * });\n * ```\n *\n * By default, the value is parsed as a boolean. You can also provide an option to extend the parsing of the boolean value to include common string representations.\n *\n * @example\n * ```ts\n * import { getBooleanFromEnv } from '@aws-lambda-powertools/commons/utils/env';\n *\n * const myEnvVar = getBooleanFromEnv({\n * key: 'MY_ENV_VAR',\n * defaultValue: true,\n * extendedParsing: true,\n * });\n * ```\n *\n * The following values are considered `true`:\n * - `\"true\"`\n * - `\"1\"`\n * - `\"yes\"`\n * - `\"on\"`\n * - `\"y\"`\n *\n * The following values are considered `false`:\n * - `\"false\"`\n * - `\"0\"`\n * - `\"no\"`\n * - `\"off\"`\n * - `\"n\"`\n *\n * @param options - The options for getting the boolean.\n * @param options.key - The key of the environment variable.\n * @param options.defaultValue - The default value to return if the environment variable is not set.\n * @param options.errorMessage - Optional error message to throw if the environment variable is not set and no default value is provided. Defaults to `\"Environment variable <key> is required\"`.\n * @param options.extendedParsing - Whether to extend the parsing of the boolean value to include common string representations like `'1'`, `'y'`, `'yes'`, `'t'`, `'true'`, `'on'` for `true` and `'0'`, `'n'`, `'no'`, `'f'`, `'false'`, `'off'` for `false`.\n */\nconst getBooleanFromEnv = ({ key, defaultValue, errorMessage, extendedParsing, }) => {\n const value = getStringFromEnv({\n key,\n defaultValue: String(defaultValue),\n errorMessage,\n });\n const parsedValue = value.toLowerCase();\n if (extendedParsing) {\n if (truthyValues.has(parsedValue)) {\n return true;\n }\n if (falsyValues.has(parsedValue)) {\n return false;\n }\n }\n if (parsedValue !== 'true' && parsedValue !== 'false') {\n throw new Error(`Environment variable ${key} must be a boolean`);\n }\n return parsedValue === 'true';\n};\n/**\n * Check if the current invocation is running in a development environment.\n *\n * This is determined by the `POWERTOOLS_DEV` environment variable.\n *\n * @example\n * ```ts\n * import { isDevMode } from '@aws-lambda-powertools/commons/utils/env';\n *\n * const isDev = isDevMode();\n * ```\n */\nconst isDevMode = () => {\n try {\n return getBooleanFromEnv({\n key: POWERTOOLS_DEV_ENV_VAR,\n extendedParsing: true,\n });\n }\n catch {\n return false;\n }\n};\n/**\n * Get the service name from the environment variables.\n *\n * This is determined by the `POWERTOOLS_SERVICE_NAME` environment variable.\n *\n * @example\n * ```ts\n * import { getServiceName } from '@aws-lambda-powertools/commons/utils/env';\n *\n * const serviceName = getServiceName();\n * ```\n */\nconst getServiceName = () => {\n return getStringFromEnv({\n key: POWERTOOLS_SERVICE_NAME_ENV_VAR,\n defaultValue: '',\n });\n};\n/**\n * Get the AWS X-Ray Trace data from the lambda RIC async context or the `_X_AMZN_TRACE_ID` environment variable.\n *\n * Checks the async context first and if that returns undefined, falls back to the environment variable\n *\n * The method parses the value and returns an object with the key-value pairs.\n */\nconst getXrayTraceDataFromEnv = () => {\n const xRayTraceEnv = globalThis.awslambda?.InvokeStore?.getXRayTraceId() ??\n getStringFromEnv({\n key: XRAY_TRACE_ID_ENV_VAR,\n defaultValue: '',\n });\n if (xRayTraceEnv === '') {\n return undefined;\n }\n if (!xRayTraceEnv.includes('=')) {\n return {\n Root: xRayTraceEnv,\n };\n }\n const xRayTraceData = {};\n for (const field of xRayTraceEnv.split(';')) {\n const [key, value] = field.split('=');\n xRayTraceData[key] = value;\n }\n return xRayTraceData;\n};\n/**\n * Determine if the current invocation is part of a sampled X-Ray trace.\n *\n * The AWS X-Ray Trace data is available in either the RIC async context or the `_X_AMZN_TRACE_ID` environment variable has this format:\n * `Root=1-5759e988-bd862e3fe1be46a994272793;Parent=557abcec3ee5a047;Sampled=1`,\n *\n * Checks the async context first and if that returns undefined, falls back to the environment variable\n */\nconst isRequestXRaySampled = () => {\n const xRayTraceData = getXrayTraceDataFromEnv();\n return xRayTraceData?.Sampled === '1';\n};\nconst shouldUseInvokeStore = () => {\n const res = getStringFromEnv({\n key: AWS_LAMBDA_MAX_CONCURRENCY,\n defaultValue: '',\n });\n return res !== '';\n};\n/**\n * AWS X-Ray Trace id from the lambda RIC async context or the `_X_AMZN_TRACE_ID` environment variable.\n *\n * Checks the async context first and if that returns undefined, falls back to the environment variable\n *\n * The AWS X-Ray Trace data has this format:\n * `Root=1-5759e988-bd862e3fe1be46a994272793;Parent=557abcec3ee5a047;Sampled=1`,\n *\n * The actual Trace ID is: `1-5759e988-bd862e3fe1be46a994272793`.\n */\nconst getXRayTraceIdFromEnv = () => {\n const xRayTraceData = getXrayTraceDataFromEnv();\n return xRayTraceData?.Root;\n};\nexport { getStringFromEnv, getNumberFromEnv, getBooleanFromEnv, isDevMode, getServiceName, getXrayTraceDataFromEnv, isRequestXRaySampled, getXRayTraceIdFromEnv, shouldUseInvokeStore, };\n", "import '@aws/lambda-invoke-store';\nimport { shouldUseInvokeStore } from '@aws-lambda-powertools/commons/utils/env';\n/**\n * Manages storage of batch processing state with automatic context detection.\n *\n * This class abstracts the storage mechanism for batch processing state,\n * automatically choosing between InvokeStore (when in Lambda context) and\n * fallback instance variables (when outside Lambda context). The decision is\n * made at runtime on every method call to support Lambda's concurrent execution\n * isolation.\n */\nclass BatchProcessingStore {\n #recordsKey = Symbol('powertools.batch.records');\n #handlerKey = Symbol('powertools.batch.handler');\n #optionsKey = Symbol('powertools.batch.options');\n #failureMessagesKey = Symbol('powertools.batch.failureMessages');\n #successMessagesKey = Symbol('powertools.batch.successMessages');\n #batchResponseKey = Symbol('powertools.batch.batchResponse');\n #errorsKey = Symbol('powertools.batch.errors');\n #fallbackRecords = [];\n #fallbackHandler = () => { };\n #fallbackOptions;\n #fallbackFailureMessages = [];\n #fallbackSuccessMessages = [];\n #fallbackBatchResponse = {\n batchItemFailures: [],\n };\n #fallbackErrors = [];\n getRecords() {\n if (!shouldUseInvokeStore()) {\n return this.#fallbackRecords;\n }\n if (globalThis.awslambda?.InvokeStore === undefined) {\n throw new Error('InvokeStore is not available');\n }\n const store = globalThis.awslambda.InvokeStore;\n return store.get(this.#recordsKey) ?? [];\n }\n setRecords(records) {\n if (!shouldUseInvokeStore()) {\n this.#fallbackRecords = records;\n return;\n }\n if (globalThis.awslambda?.InvokeStore === undefined) {\n throw new Error('InvokeStore is not available');\n }\n const store = globalThis.awslambda.InvokeStore;\n store.set(this.#recordsKey, records);\n }\n getHandler() {\n if (!shouldUseInvokeStore()) {\n return this.#fallbackHandler;\n }\n return (globalThis.awslambda?.InvokeStore?.get(this.#handlerKey) ?? (() => { }));\n }\n setHandler(handler) {\n if (!shouldUseInvokeStore()) {\n this.#fallbackHandler = handler;\n return;\n }\n globalThis.awslambda?.InvokeStore?.set(this.#handlerKey, handler);\n }\n getOptions() {\n if (!shouldUseInvokeStore()) {\n return this.#fallbackOptions;\n }\n return globalThis.awslambda?.InvokeStore?.get(this.#optionsKey);\n }\n setOptions(options) {\n if (!shouldUseInvokeStore()) {\n this.#fallbackOptions = options;\n return;\n }\n globalThis.awslambda?.InvokeStore?.set(this.#optionsKey, options);\n }\n getFailureMessages() {\n if (!shouldUseInvokeStore()) {\n return this.#fallbackFailureMessages;\n }\n return (globalThis.awslambda?.InvokeStore?.get(this.#failureMessagesKey) ?? []);\n }\n setFailureMessages(messages) {\n if (!shouldUseInvokeStore()) {\n this.#fallbackFailureMessages = messages;\n return;\n }\n globalThis.awslambda?.InvokeStore?.set(this.#failureMessagesKey, messages);\n }\n getSuccessMessages() {\n if (!shouldUseInvokeStore()) {\n return this.#fallbackSuccessMessages;\n }\n return (globalThis.awslambda?.InvokeStore?.get(this.#successMessagesKey) ?? []);\n }\n setSuccessMessages(messages) {\n if (!shouldUseInvokeStore()) {\n this.#fallbackSuccessMessages = messages;\n return;\n }\n globalThis.awslambda?.InvokeStore?.set(this.#successMessagesKey, messages);\n }\n getBatchResponse() {\n if (!shouldUseInvokeStore()) {\n return this.#fallbackBatchResponse;\n }\n return (globalThis.awslambda?.InvokeStore?.get(this.#batchResponseKey) ?? { batchItemFailures: [] });\n }\n setBatchResponse(response) {\n if (!shouldUseInvokeStore()) {\n this.#fallbackBatchResponse = response;\n return;\n }\n globalThis.awslambda?.InvokeStore?.set(this.#batchResponseKey, response);\n }\n getErrors() {\n if (!shouldUseInvokeStore()) {\n return this.#fallbackErrors;\n }\n return (globalThis.awslambda?.InvokeStore?.get(this.#errorsKey) ?? []);\n }\n setErrors(errors) {\n if (!shouldUseInvokeStore()) {\n this.#fallbackErrors = errors;\n return;\n }\n globalThis.awslambda?.InvokeStore?.set(this.#errorsKey, errors);\n }\n}\nexport { BatchProcessingStore };\n", "import { BatchProcessingStore } from './BatchProcessingStore.js';\n/**\n * Abstract class for batch processors.\n *\n * This class provides a common interface for processing records in a batch.\n *\n * Batch processors implementing this class should provide implementations for\n * a number of abstract methods that are specific to the type of processor or the\n * type of records being processed.\n *\n * The class comes with a few helper methods and hooks that can be used to prepare\n * the processor before processing records, clean up after processing records, and\n * handle records that succeed or fail processing.\n */\nclass BasePartialProcessor {\n /**\n * Store for managing invocation-specific state\n */\n #store = new BatchProcessingStore();\n get errors() {\n return this.#store.getErrors();\n }\n set errors(errors) {\n this.#store.setErrors(errors);\n }\n get failureMessages() {\n return this.#store.getFailureMessages();\n }\n set failureMessages(messages) {\n this.#store.setFailureMessages(messages);\n }\n get handler() {\n return this.#store.getHandler();\n }\n set handler(handler) {\n this.#store.setHandler(handler);\n }\n get options() {\n return this.#store.getOptions();\n }\n set options(options) {\n this.#store.setOptions(options);\n }\n get records() {\n return this.#store.getRecords();\n }\n set records(records) {\n this.#store.setRecords(records);\n }\n get successMessages() {\n return this.#store.getSuccessMessages();\n }\n set successMessages(messages) {\n this.#store.setSuccessMessages(messages);\n }\n get batchResponse() {\n return this.#store.getBatchResponse();\n }\n set batchResponse(response) {\n this.#store.setBatchResponse(response);\n }\n /**\n * Method to handle a record that failed processing\n *\n * This method should be called when a record fails processing so that\n * the processor can keep track of the error and the record that failed.\n *\n * @param record - Record that failed processing\n * @param error - Error that was thrown\n */\n failureHandler(record, error) {\n const entry = ['fail', error.message, record];\n this.errors.push(error);\n this.failureMessages.push(record);\n return entry;\n }\n /**\n * Process all records with an asynchronous handler\n *\n * Once called, the processor will create an array of promises to process each record\n * and wait for all of them to settle before returning the results.\n *\n * Before and after processing, the processor will call the prepare and clean methods respectively.\n */\n async process() {\n this.prepare();\n // Default to `true` if `processInParallel` is not specified.\n const processInParallel = this.options?.processInParallel ?? true;\n const processedRecords = processInParallel\n ? await this.#processRecordsInParallel()\n : await this.#processRecordsSequentially();\n this.clean();\n return processedRecords;\n }\n /**\n * Orchestrate the processing of a batch of records synchronously\n * and sequentially.\n *\n * The method is responsible for calling the prepare method before\n * processing the records and the clean method after processing the records.\n *\n * In the middle, the method will iterate over the records and call the\n * processRecordSync method for each record.\n *\n * @returns List of processed records\n */\n processSync() {\n /**\n * If this is an async processor, user should have called process instead,\n * so we call the method early to throw the error early thus failing fast.\n */\n if (this.constructor.name === 'BatchProcessor') {\n this.processRecordSync(this.records[0]);\n }\n this.prepare();\n const processedRecords = [];\n for (const record of this.records) {\n processedRecords.push(this.processRecordSync(record));\n }\n this.clean();\n return processedRecords;\n }\n /**\n * Set up the processor with the records and the handler\n *\n * This method should be called before processing the records to\n * bind the records and the handler for a specific invocation to\n * the processor.\n *\n * We use a separate method to do this rather than the constructor\n * to allow for reusing the processor instance across multiple invocations\n * by instantiating the processor outside the Lambda function handler.\n *\n * @param records - Array of records to be processed\n * @param handler - CallableFunction to process each record from the batch\n * @param options - Options to be used during processing (optional)\n */\n register(records, handler, options) {\n this.records = records;\n this.handler = handler;\n if (options) {\n this.options = options;\n }\n return this;\n }\n /**\n * Method to handle a record that succeeded processing\n *\n * This method should be called when a record succeeds processing so that\n * the processor can keep track of the result and the record that succeeded.\n *\n * @param record - Record that succeeded processing\n * @param result - Result from record handler\n */\n successHandler(record, result) {\n const entry = ['success', result, record];\n this.successMessages.push(record);\n return entry;\n }\n /**\n * Processes records in parallel using `Promise.all`.\n */\n #processRecordsInParallel() {\n return Promise.all(this.records.map((record) => this.processRecord(record)));\n }\n /**\n * Processes records sequentially, ensuring that each record is processed one after the other.\n */\n async #processRecordsSequentially() {\n const processedRecords = [];\n for (const record of this.records) {\n processedRecords.push(await this.processRecord(record));\n }\n return processedRecords;\n }\n}\nexport { BasePartialProcessor };\n", "/**\n * Enum of supported event types for the utility\n */\nconst EventType = {\n SQS: 'SQS',\n KinesisDataStreams: 'KinesisDataStreams',\n DynamoDBStreams: 'DynamoDBStreams',\n};\n/**\n * Enum of supported schema vendors for the utility\n */\nconst SchemaVendor = {\n Zod: 'zod',\n};\n/**\n * Default response for the partial batch processor\n */\nconst DEFAULT_RESPONSE = {\n batchItemFailures: [],\n};\n/**\n * Mapping of event types to their respective data classes\n */\nconst DATA_CLASS_MAPPING = {\n [EventType.SQS]: (record) => record,\n [EventType.KinesisDataStreams]: (record) => record,\n [EventType.DynamoDBStreams]: (record) => record,\n};\nexport { EventType, SchemaVendor, DEFAULT_RESPONSE, DATA_CLASS_MAPPING };\n", "import { EventType } from './constants.js';\n/**\n * Base error thrown by the Batch Processing utility\n */\nclass BatchProcessingError extends Error {\n constructor(message) {\n super(message);\n this.name = 'BatchProcessingError';\n }\n}\n/**\n * Error thrown by the Batch Processing utility when all batch records failed to be processed\n */\nclass FullBatchFailureError extends BatchProcessingError {\n recordErrors;\n constructor(childErrors) {\n super('All records failed processing. See individual errors below.');\n this.recordErrors = childErrors;\n this.name = 'FullBatchFailureError';\n }\n}\n/**\n * Error thrown by the Batch Processing utility when a SQS FIFO queue is short-circuited.\n * This happens when a record fails processing and the remaining records are not processed\n * to avoid out-of-order delivery.\n */\nclass SqsFifoShortCircuitError extends BatchProcessingError {\n constructor() {\n super('A previous record failed processing. The remaining records were not processed to avoid out-of-order delivery.');\n this.name = 'SqsFifoShortCircuitError';\n }\n}\n/**\n * Error thrown by the Batch Processing utility when a previous record from\n * SQS FIFO queue message group fails processing.\n */\nclass SqsFifoMessageGroupShortCircuitError extends BatchProcessingError {\n constructor() {\n super('A previous record from this message group failed processing');\n this.name = 'SqsFifoMessageGroupShortCircuitError';\n }\n}\n/**\n * Error thrown by the Batch Processing utility when a partial processor receives an unexpected\n * batch type.\n */\nclass UnexpectedBatchTypeError extends BatchProcessingError {\n constructor() {\n super(`Unexpected batch type. Possible values are: ${Object.values(EventType).join(', ')}`);\n this.name = 'UnexpectedBatchTypeError';\n }\n}\n/**\n * Error thrown by the Batch Processing utility when a record fails to be parsed.\n */\nclass ParsingError extends BatchProcessingError {\n constructor(message) {\n super(message);\n this.name = 'ParsingError';\n }\n}\nexport { BatchProcessingError, FullBatchFailureError, SqsFifoShortCircuitError, SqsFifoMessageGroupShortCircuitError, UnexpectedBatchTypeError, ParsingError, };\n", "import { getStringFromEnv } from '@aws-lambda-powertools/commons/utils/env';\nimport { BasePartialProcessor } from './BasePartialProcessor.js';\nimport { DATA_CLASS_MAPPING, DEFAULT_RESPONSE, EventType, } from './constants.js';\nimport { FullBatchFailureError } from './errors.js';\n/**\n * Base abstract class for processing batch records with partial failure handling\n *\n * This class extends the {@link BasePartialProcessor} class and adds additional\n * functionality to handle batch processing. Specifically, it provides methods\n * to collect failed records and build the partial failure response.\n */\nclass BasePartialBatchProcessor extends BasePartialProcessor {\n /**\n * Mapping of event types to their respective failure collectors\n *\n * Each service expects a different format for partial failure reporting,\n * this mapping ensures that the correct format is used for each event type.\n */\n COLLECTOR_MAPPING;\n /**\n * Type of event that the processor is handling\n */\n eventType;\n /**\n * A logger instance to be used for logging debug, warning, and error messages.\n *\n * When no logger is provided, we'll only log warnings and errors using the global `console` object.\n */\n logger;\n /**\n * The configuration options for the parser integration\n */\n parserConfig;\n /**\n * Initializes base batch processing class\n *\n * @param eventType The type of event to process (SQS, Kinesis, DynamoDB)\n */\n constructor(eventType, parserConfig) {\n super();\n this.eventType = eventType;\n this.batchResponse = DEFAULT_RESPONSE;\n this.COLLECTOR_MAPPING = {\n [EventType.SQS]: () => this.collectSqsFailures(),\n [EventType.KinesisDataStreams]: () => this.collectKinesisFailures(),\n [EventType.DynamoDBStreams]: () => this.collectDynamoDBFailures(),\n };\n this.parserConfig = parserConfig;\n const alcLogLevel = getStringFromEnv({\n key: 'AWS_LAMBDA_LOG_LEVEL',\n defaultValue: '',\n });\n this.logger = parserConfig?.logger ?? {\n debug: alcLogLevel === 'DEBUG' ? console.debug : () => undefined,\n error: console.error,\n warn: console.warn,\n };\n }\n /**\n * Clean up logic to be run after processing a batch\n *\n * If the entire batch failed this method will throw a {@link FullBatchFailureError | `FullBatchFailureError`} with the list of\n * errors that occurred during processing, unless the `throwOnFullBatchFailure` option is set to `false`.\n *\n * Otherwise, it will build the partial failure response based on the event type.\n */\n clean() {\n if (!this.hasMessagesToReport()) {\n return;\n }\n if (this.options?.throwOnFullBatchFailure !== false &&\n this.entireBatchFailed()) {\n throw new FullBatchFailureError(this.errors);\n }\n const messages = this.getMessagesToReport();\n this.batchResponse = { batchItemFailures: messages };\n }\n /**\n * Collect the identifiers of failed items for a DynamoDB stream\n *\n * The failures are collected based on the sequence number of the record\n * and formatted as a list of objects with the key `itemIdentifier` as\n * expected by the service.\n */\n collectDynamoDBFailures() {\n const failures = [];\n for (const msg of this.failureMessages) {\n const msgId = msg.dynamodb?.SequenceNumber;\n /* v8 ignore else -- @preserve */\n if (msgId) {\n failures.push({ itemIdentifier: msgId });\n }\n }\n return failures;\n }\n /**\n * Collect identifiers of failed items for a Kinesis batch\n *\n * The failures are collected based on the sequence number of the record\n * and formatted as a list of objects with the key `itemIdentifier` as\n * expected by the service.\n */\n collectKinesisFailures() {\n const failures = [];\n for (const msg of this.failureMessages) {\n const msgId = msg.kinesis.sequenceNumber;\n failures.push({ itemIdentifier: msgId });\n }\n return failures;\n }\n /**\n * Collect identifiers of failed items for an SQS batch\n *\n * The failures are collected based on the message ID of the record\n * and formatted as a list of objects with the key `itemIdentifier` as\n * expected by the service.\n */\n collectSqsFailures() {\n const failures = [];\n for (const msg of this.failureMessages) {\n const msgId = msg.messageId;\n failures.push({ itemIdentifier: msgId });\n }\n return failures;\n }\n /**\n * Determine if the entire batch failed\n *\n * If the number of errors is equal to the number of records, then the\n * entire batch failed and this method will return `true`.\n */\n entireBatchFailed() {\n return this.errors.length === this.records.length;\n }\n /**\n * Collect identifiers for failed batch items\n *\n * The method will call the appropriate collector based on the event type\n * and return the list of failed items.\n */\n getMessagesToReport() {\n return this.COLLECTOR_MAPPING[this.eventType]();\n }\n /**\n * Determine if there are any failed records to report\n *\n * If there are no failed records, then the batch was successful\n * and this method will return `false`.\n */\n hasMessagesToReport() {\n return this.failureMessages.length !== 0;\n }\n /**\n * Set up the processor with the initial state ready for processing\n */\n prepare() {\n this.successMessages = [];\n this.failureMessages = [];\n this.errors = [];\n this.batchResponse = DEFAULT_RESPONSE;\n }\n /**\n * Get the response from the batch processing\n */\n response() {\n return this.batchResponse;\n }\n /**\n * Forward a record to the appropriate batch type\n *\n * Based on the event type that the processor was initialized with, this method\n * will cast the record to the appropriate batch type handler.\n *\n * @param record The record to be processed\n * @param eventType The type of event to process\n */\n toBatchType(record, eventType) {\n return DATA_CLASS_MAPPING[eventType](record);\n }\n}\nexport { BasePartialBatchProcessor };\n", "import { BasePartialBatchProcessor } from './BasePartialBatchProcessor.js';\nimport { BatchProcessingError } from './errors.js';\n/**\n * Process records in a batch asynchronously and handle partial failure cases.\n *\n * The batch processor supports processing records coming from Amazon SQS,\n * Amazon Kinesis Data Streams, and Amazon DynamoDB Streams.\n *\n * Items are processed asynchronously and in parallel.\n *\n * **Process batch triggered by SQS**\n *\n * @example\n * ```typescript\n * import {\n * BatchProcessor,\n * EventType,\n * processPartialResponse,\n * } from '@aws-lambda-powertools/batch';\n * import type { SQSRecord, SQSHandler } from 'aws-lambda';\n *\n * const processor = new BatchProcessor(EventType.SQS);\n *\n * const recordHandler = async (record: SQSRecord): Promise<void> => {\n * const payload = JSON.parse(record.body);\n * };\n *\n * export const handler: SQSHandler = async (event, context) =>\n * processPartialResponse(event, recordHandler, processor, {\n * context,\n * });\n * ```\n *\n * **Process batch triggered by Kinesis Data Streams**\n *\n * @example\n * ```typescript\n * import {\n * BatchProcessor,\n * EventType,\n * processPartialResponse,\n * } from '@aws-lambda-powertools/batch';\n * import type { KinesisStreamHandler, KinesisStreamRecord } from 'aws-lambda';\n *\n * const processor = new BatchProcessor(EventType.KinesisDataStreams);\n *\n * const recordHandler = async (record: KinesisStreamRecord): Promise<void> => {\n * const payload = JSON.parse(record.kinesis.data);\n * };\n *\n * export const handler: KinesisStreamHandler = async (event, context) =>\n * processPartialResponse(event, recordHandler, processor, {\n * context,\n * });\n * ```\n *\n * **Process batch triggered by DynamoDB Streams**\n *\n * @example\n * ```typescript\n * import {\n * BatchProcessor,\n * EventType,\n * processPartialResponse,\n * } from '@aws-lambda-powertools/batch';\n * import type { DynamoDBRecord, DynamoDBStreamHandler } from 'aws-lambda';\n *\n * const processor = new BatchProcessor(EventType.DynamoDBStreams);\n *\n * const recordHandler = async (record: DynamoDBRecord): Promise<void> => {\n * const payload = record.dynamodb.NewImage.Message.S;\n * };\n *\n * export const handler: DynamoDBStreamHandler = async (event, context) =>\n * processPartialResponse(event, recordHandler, processor, {\n * context,\n * });\n * ```\n *\n * **Process batch with schema validation**\n *\n * @example\n * ```typescript\n * import {\n * BatchProcessor,\n * EventType,\n * processPartialResponse,\n * } from '@aws-lambda-powertools/batch';\n * import { parser } from '@aws-lambda-powertools/batch/parser';\n * import { SqsRecordSchema } from '@aws-lambda-powertools/parser/schemas';\n * import type { SQSHandler } from 'aws-lambda';\n * import { z } from 'zod';\n *\n * const myItemSchema = z.object({ name: z.string(), age: z.number() });\n *\n * const processor = new BatchProcessor(EventType.SQS, {\n * parser,\n * schema: SqsRecordSchema.extend({\n * body: myItemSchema,\n * }),\n * });\n *\n * const recordHandler = async (record) => {\n * // record is now fully typed and validated\n * console.log(record.body.name, record.body.age);\n * };\n *\n * export const handler: SQSHandler = async (event, context) =>\n * processPartialResponse(event, recordHandler, processor, {\n * context,\n * });\n * ```\n *\n * **Process batch with inner schema validation**\n *\n * @example\n * ```typescript\n * import {\n * BatchProcessor,\n * EventType,\n * processPartialResponse,\n * } from '@aws-lambda-powertools/batch';\n * import { parser } from '@aws-lambda-powertools/batch/parser';\n * import type { SQSHandler } from 'aws-lambda';\n * import { z } from 'zod';\n *\n * const myItemSchema = z.object({ name: z.string(), age: z.number() });\n *\n * const processor = new BatchProcessor(EventType.SQS, {\n * parser,\n * innerSchema: myItemSchema,\n * transformer: 'json'\n * });\n *\n * const recordHandler = async (record) => {\n * // record is now fully typed and validated\n * console.log(record.body.name, record.body.age);\n * };\n *\n * export const handler: SQSHandler = async (event, context) =>\n * processPartialResponse(event, recordHandler, processor, {\n * context,\n * });\n * ```\n *\n * Note: If `innerSchema` is used with DynamoDB streams, the schema will be applied to both the NewImage and the OldImage by default. If you want to have separate schema for both, you will need to extend the schema and use the full schema for parsing.\n *\n * @param eventType - The type of event to process (SQS, Kinesis, DynamoDB)\n */\nclass BatchProcessor extends BasePartialBatchProcessor {\n /**\n * Handle a record asynchronously with the instance handler provided.\n *\n * This method implements the abstract method from the parent class,\n * and orchestrates the processing of a single record.\n *\n * First, it converts the record to the appropriate type for the batch processor.\n * Then, it calls the handler function with the record data and context.\n *\n * If the handler function completes successfully, the method returns a success response.\n * Otherwise, it returns a failure response with the error that occurred during processing.\n *\n * @param record - The record to be processed\n */\n async processRecord(record) {\n try {\n const recordToProcess = this.parserConfig?.parser\n ? await this.parserConfig.parser(record, this.eventType, this.logger, this.parserConfig)\n : record;\n const data = this.toBatchType(recordToProcess, this.eventType);\n const result = await this.handler(data, this.options?.context);\n return this.successHandler(record, result);\n }\n catch (error) {\n return this.failureHandler(record, error);\n }\n }\n /**\n * @throws {BatchProcessingError} This method is not implemented for synchronous processing.\n *\n * @param _record - The record to be processed\n */\n processRecordSync(_record) {\n throw new BatchProcessingError('Not implemented. Use asyncProcess() instead.');\n }\n}\nexport { BatchProcessor };\n", "import { UnexpectedBatchTypeError } from './errors.js';\n/**\n * Higher level function to process a batch of records asynchronously\n * and handle partial failure cases.\n *\n * This function is intended to be used within asynchronous Lambda handlers\n * and together with a batch processor that implements the {@link BasePartialBatchProcessor}\n * interface.\n *\n * It accepts a batch of records, a record handler function, a batch processor,\n * and an optional set of options to configure the batch processing.\n *\n * By default, the function will process the batch of records asynchronously\n * and in parallel. If you need to process the records synchronously, you can\n * use the {@link processPartialResponseSync} function instead.\n *\n * @example\n * ```typescript\n * import {\n * BatchProcessor,\n * EventType,\n * processPartialResponse,\n * } from '@aws-lambda-powertools/batch';\n * import type { KinesisStreamHandler, KinesisStreamRecord } from 'aws-lambda';\n *\n * const processor = new BatchProcessor(EventType.KinesisDataStreams);\n *\n * const recordHandler = async (record: KinesisStreamRecord): Promise<void> => {\n * const payload = JSON.parse(record.kinesis.data);\n * };\n *\n * export const handler: KinesisStreamHandler = async (event, context) =>\n * processPartialResponse(event, recordHandler, processor, {\n * context,\n * });\n * ```\n *\n * By default, if the entire batch fails, the function will throw an error.\n * If you want to prevent this behavior, you can set the `throwOnFullBatchFailure` to `false`\n *\n * @example\n * ```typescript\n * import {\n * BatchProcessor,\n * EventType,\n * processPartialResponse,\n * } from '@aws-lambda-powertools/batch';\n * import type { KinesisStreamHandler, KinesisStreamRecord } from 'aws-lambda';\n *\n * const processor = new BatchProcessor(EventType.KinesisDataStreams);\n *\n * const recordHandler = async (record: KinesisStreamRecord): Promise<void> => {\n * const payload = JSON.parse(record.kinesis.data);\n * };\n *\n * export const handler: KinesisStreamHandler = async (event, context) =>\n * processPartialResponse(event, recordHandler, processor, {\n * context,\n * throwOnFullBatchFailure: false\n * });\n * ```\n *\n * @param event The event object containing the batch of records\n * @param recordHandler Async function to process each record from the batch\n * @param processor Batch processor instance to handle the batch processing\n * @param options Batch processing options, see {{@link BatchProcessingOptions}}\n */\nconst processPartialResponse = async (event, recordHandler, processor, options) => {\n if (!event.Records || !Array.isArray(event.Records)) {\n throw new UnexpectedBatchTypeError();\n }\n processor.register(event.Records, recordHandler, options);\n await processor.process();\n return processor.response();\n};\nexport { processPartialResponse };\n", "import {\n BatchProcessor,\n EventType,\n processPartialResponse\n} from \"@aws-lambda-powertools/batch\";\nimport { IdempotencyConfig } from \"@aws-lambda-powertools/idempotency\";\nimport { DynamoDBPersistenceLayer } from \"@aws-lambda-powertools/idempotency/dynamodb\";\nimport { Logger } from \"@aws-lambda-powertools/logger\";\nimport { injectLambdaContext } from \"@aws-lambda-powertools/logger/middleware\";\nimport { Metrics } from \"@aws-lambda-powertools/metrics\";\nimport { logMetrics } from \"@aws-lambda-powertools/metrics/middleware\";\nimport { Tracer } from \"@aws-lambda-powertools/tracer\";\nimport { captureLambdaHandler } from \"@aws-lambda-powertools/tracer/middleware\";\nimport middy from \"@middy/core\";\nimport httpErrorHandler from \"@middy/http-error-handler\";\nimport type { Handler, SQSHandler } from \"aws-lambda\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n DynamoDBService,\n LocationService,\n S3Service,\n SQSService,\n SSMService,\n STSService\n} from \"../services/index.js\";\nimport { assertEnvVar } from \"../utils/index.js\";\n\nexport const logger = new Logger();\n\nexport const tracer = new Tracer();\n\nexport const metrics = new Metrics();\n\nexport const withMiddlewares = (handler: Handler) =>\n middy(handler)\n .use(injectLambdaContext(logger))\n .use(captureLambdaHandler(tracer))\n .use(logMetrics(metrics, { captureColdStartMetric: true }))\n .use({\n before: async (request) => {\n if (!logger.getCorrelationId()) {\n logger.setCorrelationId(request.context.awsRequestId || randomUUID());\n }\n logger.logEventIfEnabled(request.event);\n\n request.context.logger = logger;\n request.context.tracer = tracer;\n request.context.metrics = metrics;\n }\n })\n .use({\n onError: async ({ error, context }) => {\n context.logger.error(\"Error handled by middleware\", {\n error\n });\n }\n })\n .use(httpErrorHandler());\n\nexport const getPersistenceStore = () => {\n return new DynamoDBPersistenceLayer({\n tableName: assertEnvVar(\"AC_IDEMPOTENCY_TABLE_NAME\")\n });\n};\n\nexport const getIdempotencyConfig = (eventKeyJmesPath: string) => {\n return new IdempotencyConfig({\n eventKeyJmesPath\n });\n};\n\nexport const SQS_IDEMPOTENCY_OPTIONS = {\n persistenceStore: getPersistenceStore(),\n config: getIdempotencyConfig(\"messageId\")\n};\n\nexport type AcServices = {\n dynamoDBService?: DynamoDBService;\n locationService?: LocationService;\n s3Service?: S3Service;\n sqsService?: SQSService;\n ssmService?: SSMService;\n stsService?: STSService;\n sourceS3Service?: S3Service;\n destinationS3Service?: S3Service;\n};\n\ndeclare module \"aws-lambda\" {\n interface Context {\n logger: Logger;\n tracer: Tracer;\n metrics: Metrics;\n\n acServices?: AcServices;\n }\n}\n\nexport const getPartialResponseHandler = (handler: SQSHandler) => {\n const processor = new BatchProcessor(EventType.SQS);\n return async (event: any, context: any) =>\n processPartialResponse(event, handler, processor, {\n context\n });\n};\n", "/* global awslambda */ import { Readable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport { setTimeout } from 'node:timers/promises';\nconst defaultLambdaHandler = ()=>{};\nconst defaultPlugin = {\n timeoutEarlyInMillis: 5,\n timeoutEarlyResponse: ()=>{\n throw new Error('Timeout');\n },\n streamifyResponse: false // Deprecate need for this when AWS provides a flag for when it's looking for it\n};\nconst middy = (lambdaHandler = defaultLambdaHandler, plugin = {})=>{\n // Allow base handler to be set using .handler()\n if (typeof lambdaHandler !== 'function') {\n plugin = lambdaHandler;\n lambdaHandler = defaultLambdaHandler;\n }\n plugin = {\n ...defaultPlugin,\n ...plugin\n };\n plugin.timeoutEarly = plugin.timeoutEarlyInMillis > 0;\n plugin.beforePrefetch?.();\n const beforeMiddlewares = [];\n const afterMiddlewares = [];\n const onErrorMiddlewares = [];\n const middyHandler = (event = {}, context = {})=>{\n plugin.requestStart?.();\n const request = {\n event,\n context,\n response: undefined,\n error: undefined,\n internal: plugin.internal ?? {}\n };\n return runRequest(request, [\n ...beforeMiddlewares\n ], lambdaHandler, [\n ...afterMiddlewares\n ], [\n ...onErrorMiddlewares\n ], plugin);\n };\n const middy = plugin.streamifyResponse ? awslambda.streamifyResponse(async (event, responseStream, context)=>{\n const handlerResponse = await middyHandler(event, context);\n let handlerBody = handlerResponse;\n if (handlerResponse.statusCode) {\n handlerBody = handlerResponse.body ?? '';\n responseStream = awslambda.HttpResponseStream.from(responseStream, handlerResponse);\n }\n // Source @datastream/core (MIT)\n let handlerStream;\n if (handlerBody._readableState) {\n handlerStream = handlerBody;\n } else if (typeof handlerBody === 'string') {\n function* iterator(input) {\n const size = 16384 // 16 * 1024 // Node.js default\n ;\n let position = 0;\n const length = input.length;\n while(position < length){\n yield input.substring(position, position + size);\n position += size;\n }\n }\n handlerStream = Readable.from(iterator(handlerBody));\n }\n if (!handlerStream) {\n throw new Error('handler response not a ReadableStream');\n }\n await pipeline(handlerStream, responseStream);\n }) : middyHandler;\n middy.use = (middlewares)=>{\n if (!Array.isArray(middlewares)) {\n middlewares = [\n middlewares\n ];\n }\n for (const middleware of middlewares){\n const { before, after, onError } = middleware;\n if (!before && !after && !onError) {\n throw new Error('Middleware must be an object containing at least one key among \"before\", \"after\", \"onError\"');\n }\n if (before) middy.before(before);\n if (after) middy.after(after);\n if (onError) middy.onError(onError);\n }\n return middy;\n };\n // Inline Middlewares\n middy.before = (beforeMiddleware)=>{\n beforeMiddlewares.push(beforeMiddleware);\n return middy;\n };\n middy.after = (afterMiddleware)=>{\n afterMiddlewares.unshift(afterMiddleware);\n return middy;\n };\n middy.onError = (onErrorMiddleware)=>{\n onErrorMiddlewares.unshift(onErrorMiddleware);\n return middy;\n };\n middy.handler = (replaceLambdaHandler)=>{\n lambdaHandler = replaceLambdaHandler;\n return middy;\n };\n return middy;\n};\nconst runRequest = async (request, beforeMiddlewares, lambdaHandler, afterMiddlewares, onErrorMiddlewares, plugin)=>{\n let timeoutAbort;\n const timeoutEarly = plugin.timeoutEarly && request.context.getRemainingTimeInMillis // disable when AWS context missing (tests, containers)\n ;\n try {\n await runMiddlewares(request, beforeMiddlewares, plugin);\n // Check if before stack hasn't exit early\n if (typeof request.response === 'undefined') {\n plugin.beforeHandler?.();\n const handlerAbort = new AbortController();\n if (timeoutEarly) timeoutAbort = new AbortController();\n request.response = await Promise.race([\n lambdaHandler(request.event, request.context, {\n signal: handlerAbort.signal\n }),\n timeoutEarly ? setTimeout(request.context.getRemainingTimeInMillis() - plugin.timeoutEarlyInMillis, undefined, {\n signal: timeoutAbort.signal\n }).then(()=>{\n handlerAbort.abort();\n return plugin.timeoutEarlyResponse();\n }) : Promise.race([])\n ]);\n timeoutAbort?.abort() // lambdaHandler may not be a promise\n ;\n plugin.afterHandler?.();\n await runMiddlewares(request, afterMiddlewares, plugin);\n }\n } catch (e) {\n timeoutAbort?.abort() // timeout should be aborted on errors\n ;\n // Reset response changes made by after stack before error thrown\n request.response = undefined;\n request.error = e;\n try {\n await runMiddlewares(request, onErrorMiddlewares, plugin);\n } catch (e) {\n // Save error that wasn't handled\n e.originalError = request.error;\n request.error = e;\n throw request.error;\n }\n // Catch if onError stack hasn't handled the error\n if (typeof request.response === 'undefined') throw request.error;\n } finally{\n await plugin.requestEnd?.(request);\n }\n return request.response;\n};\nconst runMiddlewares = async (request, middlewares, plugin)=>{\n for (const nextMiddleware of middlewares){\n plugin.beforeMiddleware?.(nextMiddleware.name);\n const res = await nextMiddleware(request);\n plugin.afterMiddleware?.(nextMiddleware.name);\n // short circuit chaining and respond early\n if (typeof res !== 'undefined') {\n request.response = res;\n return;\n }\n }\n};\nexport default middy;\n\n", "export const createPrefetchClient = (options) => {\n\tconst { awsClientOptions } = options;\n\tconst client = new options.AwsClient(awsClientOptions);\n\n\t// AWS XRay\n\tif (options.awsClientCapture) {\n\t\tif (options.disablePrefetch) {\n\t\t\treturn options.awsClientCapture(client);\n\t\t}\n\t\tconsole.warn(\"Unable to apply X-Ray outside of handler invocation scope.\");\n\t}\n\n\treturn client;\n};\n\nexport const createClient = async (options, request) => {\n\tlet awsClientCredentials = {};\n\n\t// Role Credentials\n\tif (options.awsClientAssumeRole) {\n\t\tif (!request) {\n\t\t\tthrow new Error(\"Request required when assuming role\", {\n\t\t\t\tcause: { package: \"@middy/util\" },\n\t\t\t});\n\t\t}\n\t\tawsClientCredentials = await getInternal(\n\t\t\t{ credentials: options.awsClientAssumeRole },\n\t\t\trequest,\n\t\t);\n\t}\n\n\tawsClientCredentials = {\n\t\t...awsClientCredentials,\n\t\t...options.awsClientOptions,\n\t};\n\n\treturn createPrefetchClient({\n\t\t...options,\n\t\tawsClientOptions: awsClientCredentials,\n\t});\n};\n\nexport const canPrefetch = (options = {}) => {\n\treturn !options.awsClientAssumeRole && !options.disablePrefetch;\n};\n\n// Internal Context\nexport const getInternal = async (variables, request) => {\n\tif (!variables || !request) return {};\n\tlet keys = [];\n\tlet values = [];\n\tif (variables === true) {\n\t\tkeys = values = Object.keys(request.internal);\n\t} else if (typeof variables === \"string\") {\n\t\tkeys = values = [variables];\n\t} else if (Array.isArray(variables)) {\n\t\tkeys = values = variables;\n\t} else if (typeof variables === \"object\") {\n\t\tkeys = Object.keys(variables);\n\t\tvalues = Object.values(variables);\n\t}\n\tconst promises = [];\n\tfor (const internalKey of values) {\n\t\t// 'internal.key.sub_value' -> { [key]: internal.key.sub_value }\n\t\tconst pathOptionKey = internalKey.split(\".\");\n\t\tconst rootOptionKey = pathOptionKey.shift();\n\t\tlet valuePromise = request.internal[rootOptionKey];\n\t\tif (!isPromise(valuePromise)) {\n\t\t\tvaluePromise = Promise.resolve(valuePromise);\n\t\t}\n\t\tpromises.push(\n\t\t\tvaluePromise.then((value) =>\n\t\t\t\tpathOptionKey.reduce((p, c) => p?.[c], value),\n\t\t\t),\n\t\t);\n\t}\n\t// ensure promise has resolved by the time it's needed\n\t// If one of the promises throws it will bubble up to @middy/core\n\tvalues = await Promise.allSettled(promises);\n\tconst errors = values\n\t\t.filter((res) => res.status === \"rejected\")\n\t\t.map((res) => res.reason);\n\tif (errors.length) {\n\t\tthrow new Error(\"Failed to resolve internal values\", {\n\t\t\tcause: { package: \"@middy/util\", data: errors },\n\t\t});\n\t}\n\tconst obj = {};\n\tfor (let i = keys.length; i--; ) {\n\t\tobj[sanitizeKey(keys[i])] = values[i].value;\n\t}\n\treturn obj;\n};\n\nconst isPromise = (promise) => typeof promise?.then === \"function\";\n\nconst sanitizeKeyPrefixLeadingNumber = /^([0-9])/;\nconst sanitizeKeyRemoveDisallowedChar = /[^a-zA-Z0-9]+/g;\nexport const sanitizeKey = (key) => {\n\treturn key\n\t\t.replace(sanitizeKeyPrefixLeadingNumber, \"_$1\")\n\t\t.replace(sanitizeKeyRemoveDisallowedChar, \"_\");\n};\n\n// fetch Cache\nconst cache = {}; // key: { value:{fetchKey:Promise}, expiry }\nexport const processCache = (\n\toptions,\n\tmiddlewareFetch = () => undefined,\n\trequest = {},\n) => {\n\tlet { cacheKey, cacheKeyExpiry, cacheExpiry } = options;\n\tcacheExpiry = cacheKeyExpiry?.[cacheKey] ?? cacheExpiry;\n\tconst now = Date.now();\n\tif (cacheExpiry) {\n\t\tconst cached = getCache(cacheKey);\n\t\tconst unexpired = cached.expiry && (cacheExpiry < 0 || cached.expiry > now);\n\n\t\tif (unexpired) {\n\t\t\tif (cached.modified) {\n\t\t\t\tconst value = middlewareFetch(request, cached.value);\n\t\t\t\tObject.assign(cached.value, value);\n\t\t\t\tcache[cacheKey] = { value: cached.value, expiry: cached.expiry };\n\t\t\t\treturn cache[cacheKey];\n\t\t\t}\n\t\t\treturn { ...cached, cache: true };\n\t\t}\n\t}\n\tconst value = middlewareFetch(request);\n\t// secrets-manager can override to unix timestamp\n\tconst expiry = cacheExpiry > 86400000 ? cacheExpiry : now + cacheExpiry;\n\tconst duration = cacheExpiry > 86400000 ? cacheExpiry - now : cacheExpiry;\n\tif (cacheExpiry) {\n\t\tconst refresh =\n\t\t\tduration > 0\n\t\t\t\t? setTimeout(\n\t\t\t\t\t\t() => processCache(options, middlewareFetch, request),\n\t\t\t\t\t\tduration,\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\t\tcache[cacheKey] = { value, expiry, refresh };\n\t}\n\treturn { value, expiry };\n};\n\nexport const catchInvalidSignatureException = (e, client, command) => {\n\tif (e.__type === \"InvalidSignatureException\") {\n\t\treturn client.send(command);\n\t}\n\tthrow e;\n};\n\nexport const getCache = (key) => {\n\tif (!cache[key]) return {};\n\treturn cache[key];\n};\n\n// Used to remove parts of a cache\nexport const modifyCache = (cacheKey, value) => {\n\tif (!cache[cacheKey]) return;\n\tclearTimeout(cache[cacheKey]?.refresh);\n\tcache[cacheKey] = { ...cache[cacheKey], value, modified: true };\n};\n\nexport const clearCache = (inputKeys = null) => {\n\tlet keys = inputKeys;\n\tkeys ??= Object.keys(cache);\n\tif (!Array.isArray(keys)) {\n\t\tkeys = [keys];\n\t}\n\tfor (const cacheKey of keys) {\n\t\tclearTimeout(cache[cacheKey]?.refresh);\n\t\tcache[cacheKey] = undefined;\n\t}\n};\n\nexport const jsonSafeParse = (text, reviver) => {\n\tif (typeof text !== \"string\") return text;\n\tconst firstChar = text[0];\n\tif (firstChar !== \"{\" && firstChar !== \"[\" && firstChar !== '\"') return text;\n\ttry {\n\t\treturn JSON.parse(text, reviver);\n\t} catch (_e) {}\n\n\treturn text;\n};\n\nexport const jsonSafeStringify = (value, replacer, space) => {\n\ttry {\n\t\treturn JSON.stringify(value, replacer, space);\n\t} catch (_e) {}\n\n\treturn value;\n};\n\nexport const normalizeHttpResponse = (request) => {\n\tlet { response } = request;\n\tif (typeof response === \"undefined\") {\n\t\tresponse = {};\n\t} else if (\n\t\ttypeof response?.statusCode === \"undefined\" &&\n\t\ttypeof response?.body === \"undefined\" &&\n\t\ttypeof response?.headers === \"undefined\"\n\t) {\n\t\tresponse = { statusCode: 200, body: response };\n\t}\n\tresponse.statusCode ??= 500;\n\tresponse.headers ??= {};\n\trequest.response = response;\n\treturn response;\n};\n\nconst createErrorRegexp = /[^a-zA-Z]/g;\nexport class HttpError extends Error {\n\tconstructor(code, optionalMessage, optionalOptions = {}) {\n\t\tlet message = optionalMessage;\n\t\tlet options = optionalOptions;\n\t\tif (message && typeof message !== \"string\") {\n\t\t\toptions = message;\n\t\t\tmessage = undefined;\n\t\t}\n\t\tmessage ??= httpErrorCodes[code];\n\t\tsuper(message, options);\n\n\t\tconst name = httpErrorCodes[code].replace(createErrorRegexp, \"\");\n\t\tthis.name = name.substr(-5) !== \"Error\" ? `${name}Error` : name;\n\n\t\tthis.status = this.statusCode = code; // setting `status` for backwards compatibility w/ `http-errors`\n\t\tthis.expose = options.expose ?? code < 500;\n\t}\n}\n\nexport const createError = (code, message, properties = {}) => {\n\treturn new HttpError(code, message, properties);\n};\n\nconst httpErrorCodes = {\n\t100: \"Continue\",\n\t101: \"Switching Protocols\",\n\t102: \"Processing\",\n\t103: \"Early Hints\",\n\t200: \"OK\",\n\t201: \"Created\",\n\t202: \"Accepted\",\n\t203: \"Non-Authoritative Information\",\n\t204: \"No Content\",\n\t205: \"Reset Content\",\n\t206: \"Partial Content\",\n\t207: \"Multi-Status\",\n\t208: \"Already Reported\",\n\t226: \"IM Used\",\n\t300: \"Multiple Choices\",\n\t301: \"Moved Permanently\",\n\t302: \"Found\",\n\t303: \"See Other\",\n\t304: \"Not Modified\",\n\t305: \"Use Proxy\",\n\t306: \"(Unused)\",\n\t307: \"Temporary Redirect\",\n\t308: \"Permanent Redirect\",\n\t400: \"Bad Request\",\n\t401: \"Unauthorized\",\n\t402: \"Payment Required\",\n\t403: \"Forbidden\",\n\t404: \"Not Found\",\n\t405: \"Method Not Allowed\",\n\t406: \"Not Acceptable\",\n\t407: \"Proxy Authentication Required\",\n\t408: \"Request Timeout\",\n\t409: \"Conflict\",\n\t410: \"Gone\",\n\t411: \"Length Required\",\n\t412: \"Precondition Failed\",\n\t413: \"Payload Too Large\",\n\t414: \"URI Too Long\",\n\t415: \"Unsupported Media Type\",\n\t416: \"Range Not Satisfiable\",\n\t417: \"Expectation Failed\",\n\t418: \"I'm a teapot\",\n\t421: \"Misdirected Request\",\n\t422: \"Unprocessable Entity\",\n\t423: \"Locked\",\n\t424: \"Failed Dependency\",\n\t425: \"Unordered Collection\",\n\t426: \"Upgrade Required\",\n\t428: \"Precondition Required\",\n\t429: \"Too Many Requests\",\n\t431: \"Request Header Fields Too Large\",\n\t451: \"Unavailable For Legal Reasons\",\n\t500: \"Internal Server Error\",\n\t501: \"Not Implemented\",\n\t502: \"Bad Gateway\",\n\t503: \"Service Unavailable\",\n\t504: \"Gateway Timeout\",\n\t505: \"HTTP Version Not Supported\",\n\t506: \"Variant Also Negotiates\",\n\t507: \"Insufficient Storage\",\n\t508: \"Loop Detected\",\n\t509: \"Bandwidth Limit Exceeded\",\n\t510: \"Not Extended\",\n\t511: \"Network Authentication Required\",\n};\n", "import { jsonSafeParse, normalizeHttpResponse } from \"@middy/util\";\n\nconst defaults = {\n\tlogger: console.error, // TODO v7 change to pass in request\n\tfallbackMessage: undefined,\n};\n\nconst httpErrorHandlerMiddleware = (opts = {}) => {\n\tconst options = { ...defaults, ...opts };\n\n\tconst httpErrorHandlerMiddlewareOnError = async (request) => {\n\t\tif (request.response !== undefined) return;\n\t\tif (typeof options.logger === \"function\") {\n\t\t\toptions.logger(request.error);\n\t\t}\n\n\t\t// Set default expose value, only passes in when there is an override\n\t\tif (request.error.statusCode && request.error.expose === undefined) {\n\t\t\trequest.error.expose = request.error.statusCode < 500;\n\t\t}\n\n\t\t// Non-http error OR expose set to false\n\t\tif (!request.error.expose || !request.error.statusCode) {\n\t\t\trequest.error = {\n\t\t\t\tstatusCode: 500,\n\t\t\t\tmessage: options.fallbackMessage,\n\t\t\t\texpose: true,\n\t\t\t};\n\t\t}\n\n\t\tif (request.error.expose) {\n\t\t\tnormalizeHttpResponse(request);\n\t\t\tconst { statusCode, message, headers } = request.error;\n\n\t\t\trequest.response = {\n\t\t\t\t...request.response,\n\t\t\t\tstatusCode,\n\t\t\t\theaders: {\n\t\t\t\t\t...request.response.headers,\n\t\t\t\t\t...headers,\n\t\t\t\t},\n\t\t\t};\n\n\t\t\tif (message) {\n\t\t\t\tconst headerContentType =\n\t\t\t\t\ttypeof jsonSafeParse(message) === \"string\"\n\t\t\t\t\t\t? \"text/plain\"\n\t\t\t\t\t\t: \"application/json\";\n\t\t\t\trequest.response.body = message;\n\t\t\t\trequest.response.headers[\"Content-Type\"] = headerContentType;\n\t\t\t}\n\t\t}\n\t};\n\n\treturn {\n\t\tonError: httpErrorHandlerMiddlewareOnError,\n\t};\n};\nexport default httpErrorHandlerMiddleware;\n"],
5
- "mappings": ";AAAA;AAAA,EACE;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAGA;AAAA,OACK;AAEP,SAAS,cAAc;AACvB,OAAOA,aAAY;AACnB,SAAS,mBAAmB;;;ACf5B,OAAOC,aAAY;;;ACAZ,IAAM,wBAAwB,CAAC,UAA2B;AAC/D,MAAI,iBAAiB,OAAO;AAC1B,WAAO,MAAM;AAAA,EACf,WAAW,OAAO,UAAU,UAAU;AACpC,WAAO;AAAA,EACT,WAAW,OAAO,UAAU,YAAY,UAAU,MAAM;AACtD,WAAO,KAAK,UAAU,KAAK;AAAA,EAC7B,OAAO;AACL,WAAO,OAAO,KAAK;AAAA,EACrB;AACF;;;ACVA,SAAS,eAAe;AAEjB,IAAM,iBAAiB;AACvB,IAAM,gBAAgB;AACtB,IAAM,iBAAiB;AACvB,IAAM,gBAAgB;AACtB,IAAM,mBAAmB;AACzB,IAAM,0BAA0B;AAChC,IAAM,qBAAqB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AACF;AACO,IAAM,2BAA2B,CAAC,aAAa;AAE/C,IAAM,wBAAwB;AAAA,EACnC,CAAC,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ACH;AAEO,IAAM,uBAAuB,CAAC,qBAA6B;AAChE,SAAO,IAAI,kBAAkB;AAAA,IAC3B;AAAA,EACF,CAAC;AACH;AAEO,IAAM,0BAA0B;AAAA,EACrC,kBAAkB,oBAAoB;AAAA,EACtC,QAAQ,qBAAqB,WAAW;AAC1C;AAuBO,IAAM,4BAA4B,CAAC,YAAwB;AAChE,QAAM,YAAY,IAAI,eAAe,UAAU,GAAG;AAClD,SAAO,OAAO,OAAY,YACxB,uBAAuB,OAAO,SAAS,WAAW;AAAA,IAChD;AAAA,EACF,CAAC;AACL;",
6
- "names": ["assert", "assert", "logger", "assert", "logger", "assert", "assert", "logger", "assert", "assert", "logger", "assert", "assert", "logger", "assert", "assert", "logger", "assert", "logger", "assert", "InvokeStore", "Logger", "setTimeout", "middy", "e", "Logger"]
4
+ "sourcesContent": ["import {\n GetObjectCommand,\n GetObjectCommandInput,\n HeadObjectCommand,\n HeadObjectCommandInput,\n ListObjectsV2Command,\n ListObjectsV2CommandInput,\n PutObjectCommand,\n PutObjectCommandInput,\n PutObjectCommandOutput,\n S3Client\n} from \"@aws-sdk/client-s3\";\nimport { AssumeRoleCommandOutput } from \"@aws-sdk/client-sts\";\nimport { Upload } from \"@aws-sdk/lib-storage\";\nimport assert from \"node:assert/strict\";\nimport { PassThrough } from \"node:stream\";\nimport { getObjectWithAssumeRoleCommandOutputAttribute } from \"../utils/index.js\";\nimport { getSignedUrl } from \"@aws-sdk/s3-request-presigner\";\nimport { Logger } from \"@aws-lambda-powertools/logger\";\n\nexport class S3Service {\n logger: Logger;\n client: S3Client;\n constructor({\n logger,\n client,\n assumeRoleCommandOutput,\n region\n }: {\n logger: Logger;\n client?: S3Client;\n assumeRoleCommandOutput?: AssumeRoleCommandOutput;\n region?: string;\n }) {\n this.logger = logger;\n\n if (client) {\n this.client = client;\n } else {\n assert(region, \"Region must be provided if client is not passed\");\n this.client = new S3Client({\n region,\n ...getObjectWithAssumeRoleCommandOutputAttribute(\n assumeRoleCommandOutput\n )\n });\n }\n }\n\n createS3UploadStream(putObjectCommandInput: PutObjectCommandInput) {\n this.logger.debug(\"upload stream started\", { putObjectCommandInput });\n\n const pass = new PassThrough();\n\n const parallelUploads = new Upload({\n client: this.client,\n params: {\n ...putObjectCommandInput,\n Body: pass\n }\n });\n\n const donePromise = parallelUploads\n .done()\n .then(() => this.logger.debug(\"upload stream finished\"))\n .catch((err) => {\n this.logger.error(\"upload stream error\", err);\n pass.destroy(err);\n });\n\n return { stream: pass, done: donePromise };\n }\n\n async createS3DownloadStream(getObjectCommandInput: GetObjectCommandInput) {\n this.logger.debug(\"download stream started\", { getObjectCommandInput });\n\n const item = await this.client.send(\n new GetObjectCommand(getObjectCommandInput)\n );\n\n this.logger.debug(\"download stream finished\");\n\n return item.Body;\n }\n\n async listObjectsV2(listObjectsV2CommandInput: ListObjectsV2CommandInput) {\n this.logger.debug(\"listObjectsV2\", { listObjectsV2CommandInput });\n return await this.client.send(\n new ListObjectsV2Command(listObjectsV2CommandInput)\n );\n }\n\n async getObject(\n getObjectCommandInput: GetObjectCommandInput\n ): Promise<Buffer> {\n this.logger.debug(\"getObject\", { getObjectCommandInput });\n\n const stream = await this.createS3DownloadStream(getObjectCommandInput);\n\n return Buffer.from(await stream.transformToByteArray());\n }\n\n async getSignedUrl(\n getObjectCommandInput: GetObjectCommandInput\n ): Promise<string> {\n this.logger.debug(\"getSignedUrl\", { getObjectCommandInput });\n\n const signedUrl = await getSignedUrl(\n this.client,\n new GetObjectCommand(getObjectCommandInput),\n { expiresIn: 3600 }\n );\n\n return signedUrl;\n }\n\n async putObject(\n putObjectCommandInput: PutObjectCommandInput\n ): Promise<PutObjectCommandOutput> {\n this.logger.debug(\"putObject\", { putObjectCommandInput });\n\n return await this.client.send(new PutObjectCommand(putObjectCommandInput));\n }\n\n async headObject(headObjectCommandInput: HeadObjectCommandInput) {\n this.logger.debug(\"headObject\", { headObjectCommandInput });\n return await this.client.send(\n new HeadObjectCommand(headObjectCommandInput)\n );\n }\n\n async checkIfObjectExists(\n headObjectCommandInput: HeadObjectCommandInput\n ): Promise<boolean> {\n this.logger.debug(\"checkIfObjectExists\", { headObjectCommandInput });\n\n try {\n await this.headObject(headObjectCommandInput);\n return true;\n } catch (error) {\n if (error.name === \"NotFound\") {\n return false;\n }\n throw error;\n }\n }\n}\n", "import assert from \"node:assert/strict\";\n\nexport const assertEnvVar = (envVar: string): string => {\n assert(process.env[envVar], `${envVar} is not set`);\n return process.env[envVar];\n};\n\nexport * from \"./normalizeErrorMessage.js\";\nexport * from \"./thumbsKey.js\";\nexport * from \"./helpers.js\";\nexport * from \"./processMeta.js\";\n", "export const normalizeErrorMessage = (error: unknown): string => {\n if (error instanceof Error) {\n return error.message;\n } else if (typeof error === \"string\") {\n return error;\n } else if (typeof error === \"object\" && error !== null) {\n return JSON.stringify(error);\n } else {\n return String(error);\n }\n};\n", "import { extname } from \"node:path\";\n\nexport const JPEG_EXTENSION = \"jpeg\";\nexport const JPG_EXTENSION = \"jpg\";\nexport const HEIC_EXTENSION = \"heic\";\nexport const MOV_EXTENSION = \"mov\";\nexport const THUMBS_EXTENSION = JPG_EXTENSION;\nexport const ENCODED_VIDEO_EXTENSION = \"mp4\";\nexport const ALLOWED_EXTENSIONS = [\n JPEG_EXTENSION,\n JPG_EXTENSION,\n HEIC_EXTENSION\n];\nexport const ALLOWED_VIDEO_EXTENSIONS = [MOV_EXTENSION];\n\nexport const THUMBNAIL_RESOLUTIONS = [\n [200, 200],\n [1180, 820]\n];\n\nexport const getThumbsKey = ({\n key,\n width,\n height\n}: {\n key: string;\n width: number;\n height: number;\n}) => {\n return `${key\n .split(\".\")\n .slice(0, -1)\n .join(\".\")}.${width}x${height}.${THUMBS_EXTENSION}`;\n};\n\nexport const getEncodedVideoKey = ({ key }: { key: string }) => {\n return `${key.split(\".\").slice(0, -1).join(\".\")}.${ENCODED_VIDEO_EXTENSION}`;\n};\n\nexport const getKeyExtension = (key: string) =>\n extname(key).slice(1).toLowerCase();\n\nexport const isAllowedExtension = (key: string) => {\n const ext = getKeyExtension(key);\n return ALLOWED_EXTENSIONS.includes(ext);\n};\n\nexport const isAllowedVideoExtension = (key: string) => {\n const ext = getKeyExtension(key);\n return ALLOWED_VIDEO_EXTENSIONS.includes(ext);\n};\n", "import { AssumeRoleCommandOutput } from \"@aws-sdk/client-sts\";\n\nexport const getObjectWithAssumeRoleCommandOutputAttribute = (\n assumeRoleCommandOutput?: AssumeRoleCommandOutput\n) =>\n assumeRoleCommandOutput\n ? {\n credentials: {\n accessKeyId: assumeRoleCommandOutput?.Credentials?.AccessKeyId,\n secretAccessKey:\n assumeRoleCommandOutput?.Credentials?.SecretAccessKey,\n sessionToken: assumeRoleCommandOutput?.Credentials?.SessionToken\n }\n }\n : {};\n\nexport const getObjectWithStackAttribute = (error: any) =>\n error && error instanceof Error ? { stack: error.stack } : {};\n", "import { DynamoDBService, LocationService } from \"../services/index.js\";\nimport type { SearchForPositionResult } from \"@aws-sdk/client-location\";\nimport assert from \"node:assert/strict\";\nimport { Logger } from \"@aws-lambda-powertools/logger\";\nimport { getKeyExtension } from \"./thumbsKey.js\";\n\ntype ExtractMetadataParams = {\n id: string;\n meta: Array<{ key: string; value: string }>;\n logger: Logger;\n locationService: LocationService;\n dynamoDBService: DynamoDBService;\n metaTableName: string;\n size: number;\n};\n\ntype Tag = { key: string; value: string };\n\n/**\n * 1. read <id>\n * 2. if <id> doesn't exist then use PutCommand\n * 3. if it does exist then match new tags and old tags\n * 4. add all old tags that are not present in new tags,\n *\n */\nexport const processMeta = async ({\n id,\n meta,\n metaTableName,\n size,\n logger,\n locationService,\n dynamoDBService\n}: ExtractMetadataParams) => {\n // expand location data\n const latitude = Number(meta.find((tag) => tag.key === \"latitude\")?.value);\n const longitude = Number(meta.find((tag) => tag.key === \"longitude\")?.value);\n\n let geoPositionResult: SearchForPositionResult | undefined;\n if (!Number.isNaN(longitude) && !Number.isNaN(latitude)) {\n try {\n const res = await locationService.searchPlaceIndexForPositionCommand({\n IndexName: \"TauPlaceIndex\",\n Position: [longitude, latitude]\n });\n\n if (res?.Results && res?.Results?.length > 0) {\n geoPositionResult = res?.Results[0];\n } else {\n throw Error(\"Can not resolve geo data\");\n }\n } catch (error) {\n logger.error(\"Error fetching geo data\", {\n message: error instanceof Error ? error.message : \"\"\n });\n }\n }\n\n const newTags = [\n ...meta,\n ...(meta.find((tag) => tag.key === \"dateCreated\")\n ? []\n : extractMetaFromKey(id)),\n { key: \"extension\", value: getKeyExtension(id) },\n { key: \"size\", value: String(size) },\n { key: \"sizeMb\", value: String(Math.round(size / 1024 ** 2)) },\n ...(geoPositionResult?.Place?.Label\n ? [{ key: \"label\", value: geoPositionResult?.Place?.Label }]\n : []),\n ...(geoPositionResult?.Place?.Country\n ? [{ key: \"country\", value: geoPositionResult?.Place?.Country }]\n : []),\n ...(geoPositionResult?.Place?.Region\n ? [{ key: \"region\", value: geoPositionResult?.Place?.Region }]\n : []),\n ...(geoPositionResult?.Place?.SubRegion\n ? [{ key: \"subRegion\", value: geoPositionResult?.Place?.SubRegion }]\n : []),\n ...(geoPositionResult?.Place?.Municipality\n ? [{ key: \"municipality\", value: geoPositionResult?.Place?.Municipality }]\n : []),\n ...(geoPositionResult?.Place?.Neighborhood\n ? [{ key: \"neighborhood\", value: geoPositionResult?.Place?.Neighborhood }]\n : []),\n ...(geoPositionResult?.Place?.PostalCode\n ? [{ key: \"postalCode\", value: geoPositionResult?.Place?.PostalCode }]\n : [])\n ].map((tag) => ({\n key: \"ac:tau:\" + tag.key,\n value: tag.value\n }));\n\n logger.debug(\"metaData\", { newTags });\n\n logger.debug(\"trying to read existing metadata\");\n const getResponse = await dynamoDBService.getCommand({\n TableName: metaTableName,\n Key: {\n id\n }\n });\n const oldTags: Tag[] = getResponse.Item?.tags;\n logger.debug(\"existing tags\", { getResponse });\n\n const reconciledTags = reconcileTags({ newTags, oldTags }, logger);\n logger.debug(\"result\", { reconciledTags });\n\n const updateResponse = await dynamoDBService.updateCommand({\n TableName: metaTableName,\n Key: {\n id\n },\n UpdateExpression: \"set tags = :tags\",\n ExpressionAttributeValues: {\n \":tags\": reconciledTags\n },\n ReturnValues: \"ALL_NEW\"\n });\n\n logger.debug(\"sent UpdateCommand\", { updateResponse });\n};\n\nconst reconcileTags = (\n { oldTags = [], newTags = [] }: { newTags: Tag[]; oldTags: Tag[] },\n logger: Logger\n) =>\n oldTags.reduce((acc, cur) => {\n if (acc.find((element) => element.key === cur.key)) {\n return acc;\n } else {\n logger.debug(\"added\", cur);\n\n return [...acc, cur];\n }\n }, newTags);\n\nconst SUBSTRING_ANSI_DATES_BEGIN_WITH = \"20\";\n\nconst extractMetaFromKey = (key: string | undefined | null): Array<Tag> => {\n if (!key) return [];\n\n let firstToken: string | undefined = undefined;\n try {\n const folder = key.split(\"/\").at(-2);\n assert(typeof folder === \"string\");\n firstToken = folder.split(\".\")[0];\n } catch (error) {}\n\n if (\n firstToken === undefined ||\n firstToken.length !== 8 ||\n !firstToken.startsWith(SUBSTRING_ANSI_DATES_BEGIN_WITH)\n )\n return [];\n\n const year = Number(firstToken.substring(0, 4));\n const month = Number(firstToken.substring(4, 6)) - 1;\n const day = Number(firstToken.substring(6));\n\n if (isNaN(year) || isNaN(month) || isNaN(day)) return [];\n\n // mon starts from 0\n // day starts from 1\n if (year < 2000 || month < 1 || month > 11 || day < 1 || day > 31) return [];\n\n const dateCreatedBin = new Date(year, month, day);\n\n return [\n { key: \"dateCreated\", value: dateCreatedBin.toISOString() },\n { key: \"yearCreated\", value: dateCreatedBin.getFullYear().toString() },\n { key: \"dayCreated\", value: dateCreatedBin.getDate().toString() },\n {\n key: \"monthCreated\",\n value: (dateCreatedBin.getMonth() + 1).toString()\n }\n ];\n};\n", "import { DynamoDBClient } from \"@aws-sdk/client-dynamodb\";\nimport { AssumeRoleCommandOutput } from \"@aws-sdk/client-sts\";\nimport {\n DynamoDBDocumentClient,\n GetCommand,\n GetCommandInput,\n GetCommandOutput,\n PutCommand,\n PutCommandInput,\n PutCommandOutput,\n QueryCommand,\n QueryCommandInput,\n QueryCommandOutput,\n UpdateCommand,\n UpdateCommandInput,\n UpdateCommandOutput\n} from \"@aws-sdk/lib-dynamodb\";\nimport assert from \"node:assert/strict\";\nimport { getObjectWithAssumeRoleCommandOutputAttribute } from \"../utils/index.js\";\nimport { Logger } from \"@aws-lambda-powertools/logger\";\n\nexport class DynamoDBService {\n logger: Logger;\n client: DynamoDBClient;\n documentClient: DynamoDBDocumentClient;\n\n constructor({\n logger,\n client,\n assumeRoleCommandOutput,\n region\n }: {\n logger: Logger;\n client?: DynamoDBClient;\n assumeRoleCommandOutput?: AssumeRoleCommandOutput;\n region?: string;\n }) {\n this.logger = logger;\n\n if (client) {\n this.client = client;\n } else {\n assert(region, \"Region must be provided if client is not passed\");\n this.client = new DynamoDBClient({\n region,\n ...getObjectWithAssumeRoleCommandOutputAttribute(\n assumeRoleCommandOutput\n )\n });\n }\n\n this.documentClient = DynamoDBDocumentClient.from(this.client);\n }\n\n async getCommand(\n getCommandInput: GetCommandInput\n ): Promise<GetCommandOutput> {\n return await this.documentClient.send(new GetCommand(getCommandInput));\n }\n\n async updateCommand(\n updateCommandInput: UpdateCommandInput\n ): Promise<UpdateCommandOutput> {\n return await this.documentClient.send(\n new UpdateCommand(updateCommandInput)\n );\n }\n\n async queryCommand(\n queryCommandInput: QueryCommandInput\n ): Promise<QueryCommandOutput> {\n return await this.documentClient.send(new QueryCommand(queryCommandInput));\n }\n\n async putCommand(\n putCommandInput: PutCommandInput\n ): Promise<PutCommandOutput> {\n return await this.documentClient.send(new PutCommand(putCommandInput));\n }\n\n async checkIfItemExists(\n checkInput: Pick<GetCommandInput, \"TableName\" | \"Key\">\n ): Promise<boolean> {\n const result = await this.getCommand(checkInput);\n\n return !!result.Item;\n }\n}\n", "import {\n GetParameterCommand,\n GetParameterCommandInput,\n GetParameterCommandOutput,\n PutParameterCommand,\n PutParameterCommandInput,\n PutParameterCommandOutput,\n SSMClient\n} from \"@aws-sdk/client-ssm\";\nimport { AssumeRoleCommandOutput } from \"@aws-sdk/client-sts\";\nimport assert from \"node:assert/strict\";\nimport { getObjectWithAssumeRoleCommandOutputAttribute } from \"../utils/index.js\";\nimport { Logger } from \"@aws-lambda-powertools/logger\";\n\nexport class SSMService {\n logger: Logger;\n client: SSMClient;\n\n constructor({\n logger,\n client,\n assumeRoleCommandOutput,\n region\n }: {\n logger: Logger;\n client?: SSMClient;\n assumeRoleCommandOutput?: AssumeRoleCommandOutput;\n region?: string;\n }) {\n this.logger = logger;\n\n if (client) {\n this.client = client;\n } else {\n assert(region, \"Region must be provided if client is not passed\");\n this.client = new SSMClient({\n region,\n ...getObjectWithAssumeRoleCommandOutputAttribute(\n assumeRoleCommandOutput\n )\n });\n }\n }\n\n async getParameter(\n params: GetParameterCommandInput\n ): Promise<GetParameterCommandOutput> {\n return await this.client.send(new GetParameterCommand(params));\n }\n\n async putParameter(\n params: PutParameterCommandInput\n ): Promise<PutParameterCommandOutput> {\n return await this.client.send(new PutParameterCommand(params));\n }\n}\n", "import {\n DeleteMessageCommand,\n DeleteMessageCommandInput,\n DeleteMessageCommandOutput,\n ReceiveMessageCommand,\n ReceiveMessageCommandInput,\n ReceiveMessageCommandOutput,\n SQSClient,\n SendMessageBatchCommand,\n SendMessageBatchCommandInput,\n SendMessageBatchCommandOutput,\n SendMessageCommand,\n SendMessageCommandInput,\n SendMessageCommandOutput\n} from \"@aws-sdk/client-sqs\";\nimport { AssumeRoleCommandOutput } from \"@aws-sdk/client-sts\";\nimport assert from \"node:assert/strict\";\nimport { getObjectWithAssumeRoleCommandOutputAttribute } from \"../utils/index.js\";\nimport { Logger } from \"@aws-lambda-powertools/logger\";\n\nexport class SQSService {\n logger: Logger;\n client: SQSClient;\n\n constructor({\n logger,\n client,\n assumeRoleCommandOutput,\n region\n }: {\n logger: Logger;\n client?: SQSClient;\n assumeRoleCommandOutput?: AssumeRoleCommandOutput;\n region?: string;\n }) {\n this.logger = logger;\n\n if (client) {\n this.client = client;\n } else {\n assert(region, \"Region must be provided if client is not passed\");\n this.client = new SQSClient({\n region,\n ...getObjectWithAssumeRoleCommandOutputAttribute(\n assumeRoleCommandOutput\n )\n });\n }\n }\n\n async sendMessage(\n params: SendMessageCommandInput\n ): Promise<SendMessageCommandOutput> {\n return await this.client.send(new SendMessageCommand(params));\n }\n\n async sendMessageBatch(\n params: SendMessageBatchCommandInput\n ): Promise<SendMessageBatchCommandOutput> {\n return await this.client.send(new SendMessageBatchCommand(params));\n }\n\n async receiveMessage(\n params: ReceiveMessageCommandInput\n ): Promise<ReceiveMessageCommandOutput> {\n return await this.client.send(new ReceiveMessageCommand(params));\n }\n\n async deleteMessage(\n params: DeleteMessageCommandInput\n ): Promise<DeleteMessageCommandOutput> {\n return await this.client.send(new DeleteMessageCommand(params));\n }\n}\n", "import {\n AssumeRoleCommand,\n AssumeRoleCommandInput,\n GetCallerIdentityCommand,\n STSClient\n} from \"@aws-sdk/client-sts\";\nimport assert from \"node:assert/strict\";\nimport { Logger } from \"@aws-lambda-powertools/logger\";\n\nexport class STSService {\n logger: Logger;\n client: STSClient;\n\n constructor({\n logger,\n region,\n client\n }: {\n logger: Logger;\n region?: string;\n client?: STSClient;\n }) {\n if (logger) {\n this.logger = logger;\n } else {\n this.logger = new Logger();\n this.logger.appendKeys({ scope: \"STSService\" });\n }\n\n if (client) {\n this.client = client;\n } else {\n assert(region, \"Region must be provided if client is not passed\");\n this.client = new STSClient({\n region\n });\n }\n }\n\n async getCallerIdentity() {\n this.logger.debug(\"getCallerIdentity\");\n\n return await this.client.send(new GetCallerIdentityCommand({}));\n }\n\n async assumeRole(assumeRoleCommandInput: AssumeRoleCommandInput) {\n this.logger.debug(\"assumeRole\", { assumeRoleCommandInput });\n\n return await this.client.send(\n new AssumeRoleCommand(assumeRoleCommandInput)\n );\n }\n}\n", "import {\n LocationClient,\n SearchPlaceIndexForPositionCommand,\n SearchPlaceIndexForPositionCommandInput,\n SearchPlaceIndexForPositionCommandOutput\n} from \"@aws-sdk/client-location\";\nimport { AssumeRoleCommandOutput } from \"@aws-sdk/client-sts\";\nimport assert from \"node:assert/strict\";\nimport { getObjectWithAssumeRoleCommandOutputAttribute } from \"../utils/index.js\";\nimport { Logger } from \"@aws-lambda-powertools/logger\";\n\nexport class LocationService {\n logger: Logger;\n client: LocationClient;\n\n constructor({\n logger,\n client,\n assumeRoleCommandOutput,\n region\n }: {\n logger: Logger;\n client?: LocationClient;\n assumeRoleCommandOutput?: AssumeRoleCommandOutput;\n region?: string;\n }) {\n this.logger = logger;\n\n if (client) {\n this.client = client;\n } else {\n assert(region, \"Region must be provided if client is not passed\");\n this.client = new LocationClient({\n region,\n ...getObjectWithAssumeRoleCommandOutputAttribute(\n assumeRoleCommandOutput\n )\n });\n }\n }\n\n async searchPlaceIndexForPositionCommand(\n searchPlaceIndexForPositionCommandInput: SearchPlaceIndexForPositionCommandInput\n ): Promise<SearchPlaceIndexForPositionCommandOutput> {\n return await this.client.send(\n new SearchPlaceIndexForPositionCommand(\n searchPlaceIndexForPositionCommandInput\n )\n );\n }\n}\n", "const PROTECTED_KEYS = {\n REQUEST_ID: Symbol.for(\"_AWS_LAMBDA_REQUEST_ID\"),\n X_RAY_TRACE_ID: Symbol.for(\"_AWS_LAMBDA_X_RAY_TRACE_ID\"),\n TENANT_ID: Symbol.for(\"_AWS_LAMBDA_TENANT_ID\"),\n};\nconst NO_GLOBAL_AWS_LAMBDA = [\"true\", \"1\"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA ?? \"\");\nif (!NO_GLOBAL_AWS_LAMBDA) {\n globalThis.awslambda = globalThis.awslambda || {};\n}\nclass InvokeStoreBase {\n static PROTECTED_KEYS = PROTECTED_KEYS;\n isProtectedKey(key) {\n return Object.values(PROTECTED_KEYS).includes(key);\n }\n getRequestId() {\n return this.get(PROTECTED_KEYS.REQUEST_ID) ?? \"-\";\n }\n getXRayTraceId() {\n return this.get(PROTECTED_KEYS.X_RAY_TRACE_ID);\n }\n getTenantId() {\n return this.get(PROTECTED_KEYS.TENANT_ID);\n }\n}\nclass InvokeStoreSingle extends InvokeStoreBase {\n currentContext;\n getContext() {\n return this.currentContext;\n }\n hasContext() {\n return this.currentContext !== undefined;\n }\n get(key) {\n return this.currentContext?.[key];\n }\n set(key, value) {\n if (this.isProtectedKey(key)) {\n throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`);\n }\n this.currentContext = this.currentContext || {};\n this.currentContext[key] = value;\n }\n run(context, fn) {\n this.currentContext = context;\n return fn();\n }\n}\nclass InvokeStoreMulti extends InvokeStoreBase {\n als;\n static async create() {\n const instance = new InvokeStoreMulti();\n const asyncHooks = await import('node:async_hooks');\n instance.als = new asyncHooks.AsyncLocalStorage();\n return instance;\n }\n getContext() {\n return this.als.getStore();\n }\n hasContext() {\n return this.als.getStore() !== undefined;\n }\n get(key) {\n return this.als.getStore()?.[key];\n }\n set(key, value) {\n if (this.isProtectedKey(key)) {\n throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`);\n }\n const store = this.als.getStore();\n if (!store) {\n throw new Error(\"No context available\");\n }\n store[key] = value;\n }\n run(context, fn) {\n return this.als.run(context, fn);\n }\n}\nvar InvokeStore;\n(function (InvokeStore) {\n let instance = null;\n async function getInstanceAsync() {\n if (!instance) {\n instance = (async () => {\n const isMulti = \"AWS_LAMBDA_MAX_CONCURRENCY\" in process.env;\n const newInstance = isMulti\n ? await InvokeStoreMulti.create()\n : new InvokeStoreSingle();\n if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda?.InvokeStore) {\n return globalThis.awslambda.InvokeStore;\n }\n else if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda) {\n globalThis.awslambda.InvokeStore = newInstance;\n return newInstance;\n }\n else {\n return newInstance;\n }\n })();\n }\n return instance;\n }\n InvokeStore.getInstanceAsync = getInstanceAsync;\n InvokeStore._testing = process.env.AWS_LAMBDA_BENCHMARK_MODE === \"1\"\n ? {\n reset: () => {\n instance = null;\n if (globalThis.awslambda?.InvokeStore) {\n delete globalThis.awslambda.InvokeStore;\n }\n globalThis.awslambda = {};\n },\n }\n : undefined;\n})(InvokeStore || (InvokeStore = {}));\n\nexport { InvokeStore, InvokeStoreBase };\n", "const AWS_LAMBDA_MAX_CONCURRENCY = 'AWS_LAMBDA_MAX_CONCURRENCY';\nconst POWERTOOLS_DEV_ENV_VAR = 'POWERTOOLS_DEV';\nconst POWERTOOLS_SERVICE_NAME_ENV_VAR = 'POWERTOOLS_SERVICE_NAME';\nconst XRAY_TRACE_ID_ENV_VAR = '_X_AMZN_TRACE_ID';\nexport { AWS_LAMBDA_MAX_CONCURRENCY, POWERTOOLS_DEV_ENV_VAR, POWERTOOLS_SERVICE_NAME_ENV_VAR, XRAY_TRACE_ID_ENV_VAR, };\n", "import '@aws/lambda-invoke-store';\nimport { AWS_LAMBDA_MAX_CONCURRENCY, POWERTOOLS_DEV_ENV_VAR, POWERTOOLS_SERVICE_NAME_ENV_VAR, XRAY_TRACE_ID_ENV_VAR, } from './constants.js';\n/**\n * Get a string from the environment variables.\n *\n * @example\n * ```ts\n * import { getStringFromEnv } from '@aws-lambda-powertools/commons/utils/env';\n *\n * const myEnvVar = getStringFromEnv({\n * key: 'MY_ENV_VAR',\n * errorMessage: 'MY_ENV_VAR is required for this function',\n * });\n * ```\n *\n * By default, the value is trimmed and always required.\n *\n * You can also provide a default value, which will be returned if the environment variable is not set instead of throwing an error.\n *\n * @example\n * ```ts\n * import { getStringFromEnv } from '@aws-lambda-powertools/commons/utils/env';\n *\n * const myEnvVar = getStringFromEnv({\n * key: 'MY_ENV_VAR',\n * defaultValue: 'defaultValue',\n * });\n * ```\n *\n * @param options - The options for getting the string.\n * @param options.key - The key of the environment variable.\n * @param options.defaultValue - Optional default value to return if the environment variable is not set.\n * @param options.errorMessage - Optional error message to throw if the environment variable is not set and no default value is provided. Defaults to `\"Environment variable <key> is required\"`.\n */\nconst getStringFromEnv = ({ key, defaultValue, errorMessage, }) => {\n const value = process.env[key];\n if (value === undefined) {\n if (defaultValue !== undefined) {\n return defaultValue;\n }\n if (errorMessage) {\n throw new Error(errorMessage);\n }\n throw new Error(`Environment variable ${key} is required`);\n }\n return value.trim();\n};\n/**\n * Get a number from the environment variables.\n *\n * @example\n * ```ts\n * import { getNumberFromEnv } from '@aws-lambda-powertools/commons/utils/env';\n *\n * const myEnvVar = getNumberFromEnv({\n * key: 'MY_ENV_VAR',\n * errorMessage: 'MY_ENV_VAR is required for this function',\n * });\n * ```\n *\n * By default, the value is trimmed before being converted to a number and always required.\n *\n * You can also provide a default value, which will be returned if the environment variable is not set instead of throwing an error.\n *\n * @example\n * ```ts\n * import { getNumberFromEnv } from '@aws-lambda-powertools/commons/utils/env';\n *\n * const myEnvVar = getNumberFromEnv({\n * key: 'MY_ENV_VAR',\n * defaultValue: 42,\n * });\n * ```\n *\n * @param options - The options for getting the number.\n * @param options.key - The key of the environment variable.\n * @param options.defaultValue - The default value to return if the environment variable is not set.\n * @param options.errorMessage - Optional error message to throw if the environment variable is not set and no default value is provided. Defaults to `\"Environment variable <key> is required\"`.\n */\nconst getNumberFromEnv = ({ key, defaultValue, errorMessage, }) => {\n const value = getStringFromEnv({\n key,\n defaultValue: String(defaultValue),\n errorMessage,\n });\n const parsedValue = Number(value);\n if (Number.isNaN(parsedValue)) {\n throw new TypeError(`Environment variable ${key} must be a number`);\n }\n return parsedValue;\n};\nconst truthyValues = new Set(['1', 'y', 'yes', 't', 'true', 'on']);\nconst falsyValues = new Set(['0', 'n', 'no', 'f', 'false', 'off']);\n/**\n * Get a boolean from the environment variables.\n *\n * @example\n * ```ts\n * import { getBooleanFromEnv } from '@aws-lambda-powertools/commons/utils/env';\n *\n * const myEnvVar = getBooleanFromEnv({\n * key: 'MY_ENV_VAR',\n * errorMessage: 'MY_ENV_VAR is required for this function',\n * });\n * ```\n *\n * By default, the value is trimmed before being converted to a boolean and always required.\n *\n * You can also provide a default value, which will be returned if the environment variable is not set instead of throwing an error.\n *\n * @example\n * ```ts\n * import { getBooleanFromEnv } from '@aws-lambda-powertools/commons/utils/env';\n *\n * const myEnvVar = getBooleanFromEnv({\n * key: 'MY_ENV_VAR',\n * defaultValue: true,\n * });\n * ```\n *\n * By default, the value is parsed as a boolean. You can also provide an option to extend the parsing of the boolean value to include common string representations.\n *\n * @example\n * ```ts\n * import { getBooleanFromEnv } from '@aws-lambda-powertools/commons/utils/env';\n *\n * const myEnvVar = getBooleanFromEnv({\n * key: 'MY_ENV_VAR',\n * defaultValue: true,\n * extendedParsing: true,\n * });\n * ```\n *\n * The following values are considered `true`:\n * - `\"true\"`\n * - `\"1\"`\n * - `\"yes\"`\n * - `\"on\"`\n * - `\"y\"`\n *\n * The following values are considered `false`:\n * - `\"false\"`\n * - `\"0\"`\n * - `\"no\"`\n * - `\"off\"`\n * - `\"n\"`\n *\n * @param options - The options for getting the boolean.\n * @param options.key - The key of the environment variable.\n * @param options.defaultValue - The default value to return if the environment variable is not set.\n * @param options.errorMessage - Optional error message to throw if the environment variable is not set and no default value is provided. Defaults to `\"Environment variable <key> is required\"`.\n * @param options.extendedParsing - Whether to extend the parsing of the boolean value to include common string representations like `'1'`, `'y'`, `'yes'`, `'t'`, `'true'`, `'on'` for `true` and `'0'`, `'n'`, `'no'`, `'f'`, `'false'`, `'off'` for `false`.\n */\nconst getBooleanFromEnv = ({ key, defaultValue, errorMessage, extendedParsing, }) => {\n const value = getStringFromEnv({\n key,\n defaultValue: String(defaultValue),\n errorMessage,\n });\n const parsedValue = value.toLowerCase();\n if (extendedParsing) {\n if (truthyValues.has(parsedValue)) {\n return true;\n }\n if (falsyValues.has(parsedValue)) {\n return false;\n }\n }\n if (parsedValue !== 'true' && parsedValue !== 'false') {\n throw new Error(`Environment variable ${key} must be a boolean`);\n }\n return parsedValue === 'true';\n};\n/**\n * Check if the current invocation is running in a development environment.\n *\n * This is determined by the `POWERTOOLS_DEV` environment variable.\n *\n * @example\n * ```ts\n * import { isDevMode } from '@aws-lambda-powertools/commons/utils/env';\n *\n * const isDev = isDevMode();\n * ```\n */\nconst isDevMode = () => {\n try {\n return getBooleanFromEnv({\n key: POWERTOOLS_DEV_ENV_VAR,\n extendedParsing: true,\n });\n }\n catch {\n return false;\n }\n};\n/**\n * Get the service name from the environment variables.\n *\n * This is determined by the `POWERTOOLS_SERVICE_NAME` environment variable.\n *\n * @example\n * ```ts\n * import { getServiceName } from '@aws-lambda-powertools/commons/utils/env';\n *\n * const serviceName = getServiceName();\n * ```\n */\nconst getServiceName = () => {\n return getStringFromEnv({\n key: POWERTOOLS_SERVICE_NAME_ENV_VAR,\n defaultValue: '',\n });\n};\n/**\n * Get the AWS X-Ray Trace data from the lambda RIC async context or the `_X_AMZN_TRACE_ID` environment variable.\n *\n * Checks the async context first and if that returns undefined, falls back to the environment variable\n *\n * The method parses the value and returns an object with the key-value pairs.\n */\nconst getXrayTraceDataFromEnv = () => {\n const xRayTraceEnv = globalThis.awslambda?.InvokeStore?.getXRayTraceId() ??\n getStringFromEnv({\n key: XRAY_TRACE_ID_ENV_VAR,\n defaultValue: '',\n });\n if (xRayTraceEnv === '') {\n return undefined;\n }\n if (!xRayTraceEnv.includes('=')) {\n return {\n Root: xRayTraceEnv,\n };\n }\n const xRayTraceData = {};\n for (const field of xRayTraceEnv.split(';')) {\n const [key, value] = field.split('=');\n xRayTraceData[key] = value;\n }\n return xRayTraceData;\n};\n/**\n * Determine if the current invocation is part of a sampled X-Ray trace.\n *\n * The AWS X-Ray Trace data is available in either the RIC async context or the `_X_AMZN_TRACE_ID` environment variable has this format:\n * `Root=1-5759e988-bd862e3fe1be46a994272793;Parent=557abcec3ee5a047;Sampled=1`,\n *\n * Checks the async context first and if that returns undefined, falls back to the environment variable\n */\nconst isRequestXRaySampled = () => {\n const xRayTraceData = getXrayTraceDataFromEnv();\n return xRayTraceData?.Sampled === '1';\n};\nconst shouldUseInvokeStore = () => {\n const res = getStringFromEnv({\n key: AWS_LAMBDA_MAX_CONCURRENCY,\n defaultValue: '',\n });\n return res !== '';\n};\n/**\n * AWS X-Ray Trace id from the lambda RIC async context or the `_X_AMZN_TRACE_ID` environment variable.\n *\n * Checks the async context first and if that returns undefined, falls back to the environment variable\n *\n * The AWS X-Ray Trace data has this format:\n * `Root=1-5759e988-bd862e3fe1be46a994272793;Parent=557abcec3ee5a047;Sampled=1`,\n *\n * The actual Trace ID is: `1-5759e988-bd862e3fe1be46a994272793`.\n */\nconst getXRayTraceIdFromEnv = () => {\n const xRayTraceData = getXrayTraceDataFromEnv();\n return xRayTraceData?.Root;\n};\nexport { getStringFromEnv, getNumberFromEnv, getBooleanFromEnv, isDevMode, getServiceName, getXrayTraceDataFromEnv, isRequestXRaySampled, getXRayTraceIdFromEnv, shouldUseInvokeStore, };\n", "import '@aws/lambda-invoke-store';\nimport { shouldUseInvokeStore } from '@aws-lambda-powertools/commons/utils/env';\n/**\n * Manages storage of batch processing state with automatic context detection.\n *\n * This class abstracts the storage mechanism for batch processing state,\n * automatically choosing between InvokeStore (when in Lambda context) and\n * fallback instance variables (when outside Lambda context). The decision is\n * made at runtime on every method call to support Lambda's concurrent execution\n * isolation.\n */\nclass BatchProcessingStore {\n #recordsKey = Symbol('powertools.batch.records');\n #handlerKey = Symbol('powertools.batch.handler');\n #optionsKey = Symbol('powertools.batch.options');\n #failureMessagesKey = Symbol('powertools.batch.failureMessages');\n #successMessagesKey = Symbol('powertools.batch.successMessages');\n #batchResponseKey = Symbol('powertools.batch.batchResponse');\n #errorsKey = Symbol('powertools.batch.errors');\n #fallbackRecords = [];\n #fallbackHandler = () => { };\n #fallbackOptions;\n #fallbackFailureMessages = [];\n #fallbackSuccessMessages = [];\n #fallbackBatchResponse = {\n batchItemFailures: [],\n };\n #fallbackErrors = [];\n getRecords() {\n if (!shouldUseInvokeStore()) {\n return this.#fallbackRecords;\n }\n if (globalThis.awslambda?.InvokeStore === undefined) {\n throw new Error('InvokeStore is not available');\n }\n const store = globalThis.awslambda.InvokeStore;\n return store.get(this.#recordsKey) ?? [];\n }\n setRecords(records) {\n if (!shouldUseInvokeStore()) {\n this.#fallbackRecords = records;\n return;\n }\n if (globalThis.awslambda?.InvokeStore === undefined) {\n throw new Error('InvokeStore is not available');\n }\n const store = globalThis.awslambda.InvokeStore;\n store.set(this.#recordsKey, records);\n }\n getHandler() {\n if (!shouldUseInvokeStore()) {\n return this.#fallbackHandler;\n }\n return (globalThis.awslambda?.InvokeStore?.get(this.#handlerKey) ?? (() => { }));\n }\n setHandler(handler) {\n if (!shouldUseInvokeStore()) {\n this.#fallbackHandler = handler;\n return;\n }\n globalThis.awslambda?.InvokeStore?.set(this.#handlerKey, handler);\n }\n getOptions() {\n if (!shouldUseInvokeStore()) {\n return this.#fallbackOptions;\n }\n return globalThis.awslambda?.InvokeStore?.get(this.#optionsKey);\n }\n setOptions(options) {\n if (!shouldUseInvokeStore()) {\n this.#fallbackOptions = options;\n return;\n }\n globalThis.awslambda?.InvokeStore?.set(this.#optionsKey, options);\n }\n getFailureMessages() {\n if (!shouldUseInvokeStore()) {\n return this.#fallbackFailureMessages;\n }\n return (globalThis.awslambda?.InvokeStore?.get(this.#failureMessagesKey) ?? []);\n }\n setFailureMessages(messages) {\n if (!shouldUseInvokeStore()) {\n this.#fallbackFailureMessages = messages;\n return;\n }\n globalThis.awslambda?.InvokeStore?.set(this.#failureMessagesKey, messages);\n }\n getSuccessMessages() {\n if (!shouldUseInvokeStore()) {\n return this.#fallbackSuccessMessages;\n }\n return (globalThis.awslambda?.InvokeStore?.get(this.#successMessagesKey) ?? []);\n }\n setSuccessMessages(messages) {\n if (!shouldUseInvokeStore()) {\n this.#fallbackSuccessMessages = messages;\n return;\n }\n globalThis.awslambda?.InvokeStore?.set(this.#successMessagesKey, messages);\n }\n getBatchResponse() {\n if (!shouldUseInvokeStore()) {\n return this.#fallbackBatchResponse;\n }\n return (globalThis.awslambda?.InvokeStore?.get(this.#batchResponseKey) ?? { batchItemFailures: [] });\n }\n setBatchResponse(response) {\n if (!shouldUseInvokeStore()) {\n this.#fallbackBatchResponse = response;\n return;\n }\n globalThis.awslambda?.InvokeStore?.set(this.#batchResponseKey, response);\n }\n getErrors() {\n if (!shouldUseInvokeStore()) {\n return this.#fallbackErrors;\n }\n return (globalThis.awslambda?.InvokeStore?.get(this.#errorsKey) ?? []);\n }\n setErrors(errors) {\n if (!shouldUseInvokeStore()) {\n this.#fallbackErrors = errors;\n return;\n }\n globalThis.awslambda?.InvokeStore?.set(this.#errorsKey, errors);\n }\n}\nexport { BatchProcessingStore };\n", "import { BatchProcessingStore } from './BatchProcessingStore.js';\n/**\n * Abstract class for batch processors.\n *\n * This class provides a common interface for processing records in a batch.\n *\n * Batch processors implementing this class should provide implementations for\n * a number of abstract methods that are specific to the type of processor or the\n * type of records being processed.\n *\n * The class comes with a few helper methods and hooks that can be used to prepare\n * the processor before processing records, clean up after processing records, and\n * handle records that succeed or fail processing.\n */\nclass BasePartialProcessor {\n /**\n * Store for managing invocation-specific state\n */\n #store = new BatchProcessingStore();\n get errors() {\n return this.#store.getErrors();\n }\n set errors(errors) {\n this.#store.setErrors(errors);\n }\n get failureMessages() {\n return this.#store.getFailureMessages();\n }\n set failureMessages(messages) {\n this.#store.setFailureMessages(messages);\n }\n get handler() {\n return this.#store.getHandler();\n }\n set handler(handler) {\n this.#store.setHandler(handler);\n }\n get options() {\n return this.#store.getOptions();\n }\n set options(options) {\n this.#store.setOptions(options);\n }\n get records() {\n return this.#store.getRecords();\n }\n set records(records) {\n this.#store.setRecords(records);\n }\n get successMessages() {\n return this.#store.getSuccessMessages();\n }\n set successMessages(messages) {\n this.#store.setSuccessMessages(messages);\n }\n get batchResponse() {\n return this.#store.getBatchResponse();\n }\n set batchResponse(response) {\n this.#store.setBatchResponse(response);\n }\n /**\n * Method to handle a record that failed processing\n *\n * This method should be called when a record fails processing so that\n * the processor can keep track of the error and the record that failed.\n *\n * @param record - Record that failed processing\n * @param error - Error that was thrown\n */\n failureHandler(record, error) {\n const entry = ['fail', error.message, record];\n this.errors.push(error);\n this.failureMessages.push(record);\n return entry;\n }\n /**\n * Process all records with an asynchronous handler\n *\n * Once called, the processor will create an array of promises to process each record\n * and wait for all of them to settle before returning the results.\n *\n * Before and after processing, the processor will call the prepare and clean methods respectively.\n */\n async process() {\n this.prepare();\n // Default to `true` if `processInParallel` is not specified.\n const processInParallel = this.options?.processInParallel ?? true;\n const processedRecords = processInParallel\n ? await this.#processRecordsInParallel()\n : await this.#processRecordsSequentially();\n this.clean();\n return processedRecords;\n }\n /**\n * Orchestrate the processing of a batch of records synchronously\n * and sequentially.\n *\n * The method is responsible for calling the prepare method before\n * processing the records and the clean method after processing the records.\n *\n * In the middle, the method will iterate over the records and call the\n * processRecordSync method for each record.\n *\n * @returns List of processed records\n */\n processSync() {\n /**\n * If this is an async processor, user should have called process instead,\n * so we call the method early to throw the error early thus failing fast.\n */\n if (this.constructor.name === 'BatchProcessor') {\n this.processRecordSync(this.records[0]);\n }\n this.prepare();\n const processedRecords = [];\n for (const record of this.records) {\n processedRecords.push(this.processRecordSync(record));\n }\n this.clean();\n return processedRecords;\n }\n /**\n * Set up the processor with the records and the handler\n *\n * This method should be called before processing the records to\n * bind the records and the handler for a specific invocation to\n * the processor.\n *\n * We use a separate method to do this rather than the constructor\n * to allow for reusing the processor instance across multiple invocations\n * by instantiating the processor outside the Lambda function handler.\n *\n * @param records - Array of records to be processed\n * @param handler - CallableFunction to process each record from the batch\n * @param options - Options to be used during processing (optional)\n */\n register(records, handler, options) {\n this.records = records;\n this.handler = handler;\n if (options) {\n this.options = options;\n }\n return this;\n }\n /**\n * Method to handle a record that succeeded processing\n *\n * This method should be called when a record succeeds processing so that\n * the processor can keep track of the result and the record that succeeded.\n *\n * @param record - Record that succeeded processing\n * @param result - Result from record handler\n */\n successHandler(record, result) {\n const entry = ['success', result, record];\n this.successMessages.push(record);\n return entry;\n }\n /**\n * Processes records in parallel using `Promise.all`.\n */\n #processRecordsInParallel() {\n return Promise.all(this.records.map((record) => this.processRecord(record)));\n }\n /**\n * Processes records sequentially, ensuring that each record is processed one after the other.\n */\n async #processRecordsSequentially() {\n const processedRecords = [];\n for (const record of this.records) {\n processedRecords.push(await this.processRecord(record));\n }\n return processedRecords;\n }\n}\nexport { BasePartialProcessor };\n", "/**\n * Enum of supported event types for the utility\n */\nconst EventType = {\n SQS: 'SQS',\n KinesisDataStreams: 'KinesisDataStreams',\n DynamoDBStreams: 'DynamoDBStreams',\n};\n/**\n * Enum of supported schema vendors for the utility\n */\nconst SchemaVendor = {\n Zod: 'zod',\n};\n/**\n * Default response for the partial batch processor\n */\nconst DEFAULT_RESPONSE = {\n batchItemFailures: [],\n};\n/**\n * Mapping of event types to their respective data classes\n */\nconst DATA_CLASS_MAPPING = {\n [EventType.SQS]: (record) => record,\n [EventType.KinesisDataStreams]: (record) => record,\n [EventType.DynamoDBStreams]: (record) => record,\n};\nexport { EventType, SchemaVendor, DEFAULT_RESPONSE, DATA_CLASS_MAPPING };\n", "import { EventType } from './constants.js';\n/**\n * Base error thrown by the Batch Processing utility\n */\nclass BatchProcessingError extends Error {\n constructor(message) {\n super(message);\n this.name = 'BatchProcessingError';\n }\n}\n/**\n * Error thrown by the Batch Processing utility when all batch records failed to be processed\n */\nclass FullBatchFailureError extends BatchProcessingError {\n recordErrors;\n constructor(childErrors) {\n super('All records failed processing. See individual errors below.');\n this.recordErrors = childErrors;\n this.name = 'FullBatchFailureError';\n }\n}\n/**\n * Error thrown by the Batch Processing utility when a SQS FIFO queue is short-circuited.\n * This happens when a record fails processing and the remaining records are not processed\n * to avoid out-of-order delivery.\n */\nclass SqsFifoShortCircuitError extends BatchProcessingError {\n constructor() {\n super('A previous record failed processing. The remaining records were not processed to avoid out-of-order delivery.');\n this.name = 'SqsFifoShortCircuitError';\n }\n}\n/**\n * Error thrown by the Batch Processing utility when a previous record from\n * SQS FIFO queue message group fails processing.\n */\nclass SqsFifoMessageGroupShortCircuitError extends BatchProcessingError {\n constructor() {\n super('A previous record from this message group failed processing');\n this.name = 'SqsFifoMessageGroupShortCircuitError';\n }\n}\n/**\n * Error thrown by the Batch Processing utility when a partial processor receives an unexpected\n * batch type.\n */\nclass UnexpectedBatchTypeError extends BatchProcessingError {\n constructor() {\n super(`Unexpected batch type. Possible values are: ${Object.values(EventType).join(', ')}`);\n this.name = 'UnexpectedBatchTypeError';\n }\n}\n/**\n * Error thrown by the Batch Processing utility when a record fails to be parsed.\n */\nclass ParsingError extends BatchProcessingError {\n constructor(message) {\n super(message);\n this.name = 'ParsingError';\n }\n}\nexport { BatchProcessingError, FullBatchFailureError, SqsFifoShortCircuitError, SqsFifoMessageGroupShortCircuitError, UnexpectedBatchTypeError, ParsingError, };\n", "import { getStringFromEnv } from '@aws-lambda-powertools/commons/utils/env';\nimport { BasePartialProcessor } from './BasePartialProcessor.js';\nimport { DATA_CLASS_MAPPING, DEFAULT_RESPONSE, EventType, } from './constants.js';\nimport { FullBatchFailureError } from './errors.js';\n/**\n * Base abstract class for processing batch records with partial failure handling\n *\n * This class extends the {@link BasePartialProcessor} class and adds additional\n * functionality to handle batch processing. Specifically, it provides methods\n * to collect failed records and build the partial failure response.\n */\nclass BasePartialBatchProcessor extends BasePartialProcessor {\n /**\n * Mapping of event types to their respective failure collectors\n *\n * Each service expects a different format for partial failure reporting,\n * this mapping ensures that the correct format is used for each event type.\n */\n COLLECTOR_MAPPING;\n /**\n * Type of event that the processor is handling\n */\n eventType;\n /**\n * A logger instance to be used for logging debug, warning, and error messages.\n *\n * When no logger is provided, we'll only log warnings and errors using the global `console` object.\n */\n logger;\n /**\n * The configuration options for the parser integration\n */\n parserConfig;\n /**\n * Initializes base batch processing class\n *\n * @param eventType The type of event to process (SQS, Kinesis, DynamoDB)\n */\n constructor(eventType, parserConfig) {\n super();\n this.eventType = eventType;\n this.batchResponse = DEFAULT_RESPONSE;\n this.COLLECTOR_MAPPING = {\n [EventType.SQS]: () => this.collectSqsFailures(),\n [EventType.KinesisDataStreams]: () => this.collectKinesisFailures(),\n [EventType.DynamoDBStreams]: () => this.collectDynamoDBFailures(),\n };\n this.parserConfig = parserConfig;\n const alcLogLevel = getStringFromEnv({\n key: 'AWS_LAMBDA_LOG_LEVEL',\n defaultValue: '',\n });\n this.logger = parserConfig?.logger ?? {\n debug: alcLogLevel === 'DEBUG' ? console.debug : () => undefined,\n error: console.error,\n warn: console.warn,\n };\n }\n /**\n * Clean up logic to be run after processing a batch\n *\n * If the entire batch failed this method will throw a {@link FullBatchFailureError | `FullBatchFailureError`} with the list of\n * errors that occurred during processing, unless the `throwOnFullBatchFailure` option is set to `false`.\n *\n * Otherwise, it will build the partial failure response based on the event type.\n */\n clean() {\n if (!this.hasMessagesToReport()) {\n return;\n }\n if (this.options?.throwOnFullBatchFailure !== false &&\n this.entireBatchFailed()) {\n throw new FullBatchFailureError(this.errors);\n }\n const messages = this.getMessagesToReport();\n this.batchResponse = { batchItemFailures: messages };\n }\n /**\n * Collect the identifiers of failed items for a DynamoDB stream\n *\n * The failures are collected based on the sequence number of the record\n * and formatted as a list of objects with the key `itemIdentifier` as\n * expected by the service.\n */\n collectDynamoDBFailures() {\n const failures = [];\n for (const msg of this.failureMessages) {\n const msgId = msg.dynamodb?.SequenceNumber;\n /* v8 ignore else -- @preserve */\n if (msgId) {\n failures.push({ itemIdentifier: msgId });\n }\n }\n return failures;\n }\n /**\n * Collect identifiers of failed items for a Kinesis batch\n *\n * The failures are collected based on the sequence number of the record\n * and formatted as a list of objects with the key `itemIdentifier` as\n * expected by the service.\n */\n collectKinesisFailures() {\n const failures = [];\n for (const msg of this.failureMessages) {\n const msgId = msg.kinesis.sequenceNumber;\n failures.push({ itemIdentifier: msgId });\n }\n return failures;\n }\n /**\n * Collect identifiers of failed items for an SQS batch\n *\n * The failures are collected based on the message ID of the record\n * and formatted as a list of objects with the key `itemIdentifier` as\n * expected by the service.\n */\n collectSqsFailures() {\n const failures = [];\n for (const msg of this.failureMessages) {\n const msgId = msg.messageId;\n failures.push({ itemIdentifier: msgId });\n }\n return failures;\n }\n /**\n * Determine if the entire batch failed\n *\n * If the number of errors is equal to the number of records, then the\n * entire batch failed and this method will return `true`.\n */\n entireBatchFailed() {\n return this.errors.length === this.records.length;\n }\n /**\n * Collect identifiers for failed batch items\n *\n * The method will call the appropriate collector based on the event type\n * and return the list of failed items.\n */\n getMessagesToReport() {\n return this.COLLECTOR_MAPPING[this.eventType]();\n }\n /**\n * Determine if there are any failed records to report\n *\n * If there are no failed records, then the batch was successful\n * and this method will return `false`.\n */\n hasMessagesToReport() {\n return this.failureMessages.length !== 0;\n }\n /**\n * Set up the processor with the initial state ready for processing\n */\n prepare() {\n this.successMessages = [];\n this.failureMessages = [];\n this.errors = [];\n this.batchResponse = DEFAULT_RESPONSE;\n }\n /**\n * Get the response from the batch processing\n */\n response() {\n return this.batchResponse;\n }\n /**\n * Forward a record to the appropriate batch type\n *\n * Based on the event type that the processor was initialized with, this method\n * will cast the record to the appropriate batch type handler.\n *\n * @param record The record to be processed\n * @param eventType The type of event to process\n */\n toBatchType(record, eventType) {\n return DATA_CLASS_MAPPING[eventType](record);\n }\n}\nexport { BasePartialBatchProcessor };\n", "import { BasePartialBatchProcessor } from './BasePartialBatchProcessor.js';\nimport { BatchProcessingError } from './errors.js';\n/**\n * Process records in a batch asynchronously and handle partial failure cases.\n *\n * The batch processor supports processing records coming from Amazon SQS,\n * Amazon Kinesis Data Streams, and Amazon DynamoDB Streams.\n *\n * Items are processed asynchronously and in parallel.\n *\n * **Process batch triggered by SQS**\n *\n * @example\n * ```typescript\n * import {\n * BatchProcessor,\n * EventType,\n * processPartialResponse,\n * } from '@aws-lambda-powertools/batch';\n * import type { SQSRecord, SQSHandler } from 'aws-lambda';\n *\n * const processor = new BatchProcessor(EventType.SQS);\n *\n * const recordHandler = async (record: SQSRecord): Promise<void> => {\n * const payload = JSON.parse(record.body);\n * };\n *\n * export const handler: SQSHandler = async (event, context) =>\n * processPartialResponse(event, recordHandler, processor, {\n * context,\n * });\n * ```\n *\n * **Process batch triggered by Kinesis Data Streams**\n *\n * @example\n * ```typescript\n * import {\n * BatchProcessor,\n * EventType,\n * processPartialResponse,\n * } from '@aws-lambda-powertools/batch';\n * import type { KinesisStreamHandler, KinesisStreamRecord } from 'aws-lambda';\n *\n * const processor = new BatchProcessor(EventType.KinesisDataStreams);\n *\n * const recordHandler = async (record: KinesisStreamRecord): Promise<void> => {\n * const payload = JSON.parse(record.kinesis.data);\n * };\n *\n * export const handler: KinesisStreamHandler = async (event, context) =>\n * processPartialResponse(event, recordHandler, processor, {\n * context,\n * });\n * ```\n *\n * **Process batch triggered by DynamoDB Streams**\n *\n * @example\n * ```typescript\n * import {\n * BatchProcessor,\n * EventType,\n * processPartialResponse,\n * } from '@aws-lambda-powertools/batch';\n * import type { DynamoDBRecord, DynamoDBStreamHandler } from 'aws-lambda';\n *\n * const processor = new BatchProcessor(EventType.DynamoDBStreams);\n *\n * const recordHandler = async (record: DynamoDBRecord): Promise<void> => {\n * const payload = record.dynamodb.NewImage.Message.S;\n * };\n *\n * export const handler: DynamoDBStreamHandler = async (event, context) =>\n * processPartialResponse(event, recordHandler, processor, {\n * context,\n * });\n * ```\n *\n * **Process batch with schema validation**\n *\n * @example\n * ```typescript\n * import {\n * BatchProcessor,\n * EventType,\n * processPartialResponse,\n * } from '@aws-lambda-powertools/batch';\n * import { parser } from '@aws-lambda-powertools/batch/parser';\n * import { SqsRecordSchema } from '@aws-lambda-powertools/parser/schemas';\n * import type { SQSHandler } from 'aws-lambda';\n * import { z } from 'zod';\n *\n * const myItemSchema = z.object({ name: z.string(), age: z.number() });\n *\n * const processor = new BatchProcessor(EventType.SQS, {\n * parser,\n * schema: SqsRecordSchema.extend({\n * body: myItemSchema,\n * }),\n * });\n *\n * const recordHandler = async (record) => {\n * // record is now fully typed and validated\n * console.log(record.body.name, record.body.age);\n * };\n *\n * export const handler: SQSHandler = async (event, context) =>\n * processPartialResponse(event, recordHandler, processor, {\n * context,\n * });\n * ```\n *\n * **Process batch with inner schema validation**\n *\n * @example\n * ```typescript\n * import {\n * BatchProcessor,\n * EventType,\n * processPartialResponse,\n * } from '@aws-lambda-powertools/batch';\n * import { parser } from '@aws-lambda-powertools/batch/parser';\n * import type { SQSHandler } from 'aws-lambda';\n * import { z } from 'zod';\n *\n * const myItemSchema = z.object({ name: z.string(), age: z.number() });\n *\n * const processor = new BatchProcessor(EventType.SQS, {\n * parser,\n * innerSchema: myItemSchema,\n * transformer: 'json'\n * });\n *\n * const recordHandler = async (record) => {\n * // record is now fully typed and validated\n * console.log(record.body.name, record.body.age);\n * };\n *\n * export const handler: SQSHandler = async (event, context) =>\n * processPartialResponse(event, recordHandler, processor, {\n * context,\n * });\n * ```\n *\n * Note: If `innerSchema` is used with DynamoDB streams, the schema will be applied to both the NewImage and the OldImage by default. If you want to have separate schema for both, you will need to extend the schema and use the full schema for parsing.\n *\n * @param eventType - The type of event to process (SQS, Kinesis, DynamoDB)\n */\nclass BatchProcessor extends BasePartialBatchProcessor {\n /**\n * Handle a record asynchronously with the instance handler provided.\n *\n * This method implements the abstract method from the parent class,\n * and orchestrates the processing of a single record.\n *\n * First, it converts the record to the appropriate type for the batch processor.\n * Then, it calls the handler function with the record data and context.\n *\n * If the handler function completes successfully, the method returns a success response.\n * Otherwise, it returns a failure response with the error that occurred during processing.\n *\n * @param record - The record to be processed\n */\n async processRecord(record) {\n try {\n const recordToProcess = this.parserConfig?.parser\n ? await this.parserConfig.parser(record, this.eventType, this.logger, this.parserConfig)\n : record;\n const data = this.toBatchType(recordToProcess, this.eventType);\n const result = await this.handler(data, this.options?.context);\n return this.successHandler(record, result);\n }\n catch (error) {\n return this.failureHandler(record, error);\n }\n }\n /**\n * @throws {BatchProcessingError} This method is not implemented for synchronous processing.\n *\n * @param _record - The record to be processed\n */\n processRecordSync(_record) {\n throw new BatchProcessingError('Not implemented. Use asyncProcess() instead.');\n }\n}\nexport { BatchProcessor };\n", "import { UnexpectedBatchTypeError } from './errors.js';\n/**\n * Higher level function to process a batch of records asynchronously\n * and handle partial failure cases.\n *\n * This function is intended to be used within asynchronous Lambda handlers\n * and together with a batch processor that implements the {@link BasePartialBatchProcessor}\n * interface.\n *\n * It accepts a batch of records, a record handler function, a batch processor,\n * and an optional set of options to configure the batch processing.\n *\n * By default, the function will process the batch of records asynchronously\n * and in parallel. If you need to process the records synchronously, you can\n * use the {@link processPartialResponseSync} function instead.\n *\n * @example\n * ```typescript\n * import {\n * BatchProcessor,\n * EventType,\n * processPartialResponse,\n * } from '@aws-lambda-powertools/batch';\n * import type { KinesisStreamHandler, KinesisStreamRecord } from 'aws-lambda';\n *\n * const processor = new BatchProcessor(EventType.KinesisDataStreams);\n *\n * const recordHandler = async (record: KinesisStreamRecord): Promise<void> => {\n * const payload = JSON.parse(record.kinesis.data);\n * };\n *\n * export const handler: KinesisStreamHandler = async (event, context) =>\n * processPartialResponse(event, recordHandler, processor, {\n * context,\n * });\n * ```\n *\n * By default, if the entire batch fails, the function will throw an error.\n * If you want to prevent this behavior, you can set the `throwOnFullBatchFailure` to `false`\n *\n * @example\n * ```typescript\n * import {\n * BatchProcessor,\n * EventType,\n * processPartialResponse,\n * } from '@aws-lambda-powertools/batch';\n * import type { KinesisStreamHandler, KinesisStreamRecord } from 'aws-lambda';\n *\n * const processor = new BatchProcessor(EventType.KinesisDataStreams);\n *\n * const recordHandler = async (record: KinesisStreamRecord): Promise<void> => {\n * const payload = JSON.parse(record.kinesis.data);\n * };\n *\n * export const handler: KinesisStreamHandler = async (event, context) =>\n * processPartialResponse(event, recordHandler, processor, {\n * context,\n * throwOnFullBatchFailure: false\n * });\n * ```\n *\n * @param event The event object containing the batch of records\n * @param recordHandler Async function to process each record from the batch\n * @param processor Batch processor instance to handle the batch processing\n * @param options Batch processing options, see {{@link BatchProcessingOptions}}\n */\nconst processPartialResponse = async (event, recordHandler, processor, options) => {\n if (!event.Records || !Array.isArray(event.Records)) {\n throw new UnexpectedBatchTypeError();\n }\n processor.register(event.Records, recordHandler, options);\n await processor.process();\n return processor.response();\n};\nexport { processPartialResponse };\n", "import {\n BatchProcessor,\n EventType,\n processPartialResponse\n} from \"@aws-lambda-powertools/batch\";\nimport { IdempotencyConfig } from \"@aws-lambda-powertools/idempotency\";\nimport { DynamoDBPersistenceLayer } from \"@aws-lambda-powertools/idempotency/dynamodb\";\nimport { Logger } from \"@aws-lambda-powertools/logger\";\nimport { injectLambdaContext } from \"@aws-lambda-powertools/logger/middleware\";\nimport { Metrics, MetricUnit } from \"@aws-lambda-powertools/metrics\";\nimport { logMetrics } from \"@aws-lambda-powertools/metrics/middleware\";\nimport { Tracer } from \"@aws-lambda-powertools/tracer\";\nimport { captureLambdaHandler } from \"@aws-lambda-powertools/tracer/middleware\";\nimport middy from \"@middy/core\";\nimport httpErrorHandler from \"@middy/http-error-handler\";\nimport type { Handler, SQSHandler } from \"aws-lambda\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n DynamoDBService,\n LocationService,\n S3Service,\n SQSService,\n SSMService,\n STSService\n} from \"../services/index.js\";\nimport { assertEnvVar } from \"../utils/index.js\";\n\nexport const logger = new Logger();\nexport type { Logger } from \"@aws-lambda-powertools/logger\";\nexport const tracer = new Tracer();\n\nexport const metrics = new Metrics({ namespace: \"aspan-corporation\" });\n\nexport const withMiddlewares = (handler: Handler) =>\n middy(handler)\n .use(injectLambdaContext(logger))\n .use(captureLambdaHandler(tracer))\n .use(logMetrics(metrics, { captureColdStartMetric: true }))\n .use({\n before: async (request) => {\n if (!logger.getCorrelationId()) {\n logger.setCorrelationId(request.context.awsRequestId || randomUUID());\n }\n logger.logEventIfEnabled(request.event);\n\n request.context.logger = logger;\n request.context.tracer = tracer;\n request.context.metrics = metrics;\n }\n })\n .use({\n onError: async ({ error, context: { logger, metrics } }) => {\n logger.error(\"Error handled by middleware\", {\n error\n });\n\n metrics.addMetric(\"ErrorHandled\", MetricUnit.Count, 1);\n }\n })\n .use(httpErrorHandler());\n\nexport const getPersistenceStore = () => {\n return new DynamoDBPersistenceLayer({\n tableName: assertEnvVar(\"AC_IDEMPOTENCY_TABLE_NAME\")\n });\n};\n\nexport const getIdempotencyConfig = (eventKeyJmesPath: string) => {\n return new IdempotencyConfig({\n eventKeyJmesPath\n });\n};\n\nexport const SQS_IDEMPOTENCY_OPTIONS = {\n persistenceStore: getPersistenceStore(),\n config: getIdempotencyConfig(\"messageId\")\n};\n\nexport type AcServices = {\n dynamoDBService?: DynamoDBService;\n locationService?: LocationService;\n s3Service?: S3Service;\n sqsService?: SQSService;\n ssmService?: SSMService;\n stsService?: STSService;\n sourceS3Service?: S3Service;\n destinationS3Service?: S3Service;\n};\n\ndeclare module \"aws-lambda\" {\n interface Context {\n logger: Logger;\n tracer: Tracer;\n metrics: Metrics;\n\n acServices?: AcServices;\n }\n}\n\nexport const getPartialResponseHandler = (handler: SQSHandler) => {\n const processor = new BatchProcessor(EventType.SQS);\n return async (event: any, context: any) =>\n processPartialResponse(event, handler, processor, {\n context\n });\n};\n", "/* global awslambda */ import { Readable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport { setTimeout } from 'node:timers/promises';\nconst defaultLambdaHandler = ()=>{};\nconst defaultPlugin = {\n timeoutEarlyInMillis: 5,\n timeoutEarlyResponse: ()=>{\n throw new Error('Timeout');\n },\n streamifyResponse: false // Deprecate need for this when AWS provides a flag for when it's looking for it\n};\nconst middy = (lambdaHandler = defaultLambdaHandler, plugin = {})=>{\n // Allow base handler to be set using .handler()\n if (typeof lambdaHandler !== 'function') {\n plugin = lambdaHandler;\n lambdaHandler = defaultLambdaHandler;\n }\n plugin = {\n ...defaultPlugin,\n ...plugin\n };\n plugin.timeoutEarly = plugin.timeoutEarlyInMillis > 0;\n plugin.beforePrefetch?.();\n const beforeMiddlewares = [];\n const afterMiddlewares = [];\n const onErrorMiddlewares = [];\n const middyHandler = (event = {}, context = {})=>{\n plugin.requestStart?.();\n const request = {\n event,\n context,\n response: undefined,\n error: undefined,\n internal: plugin.internal ?? {}\n };\n return runRequest(request, [\n ...beforeMiddlewares\n ], lambdaHandler, [\n ...afterMiddlewares\n ], [\n ...onErrorMiddlewares\n ], plugin);\n };\n const middy = plugin.streamifyResponse ? awslambda.streamifyResponse(async (event, responseStream, context)=>{\n const handlerResponse = await middyHandler(event, context);\n let handlerBody = handlerResponse;\n if (handlerResponse.statusCode) {\n handlerBody = handlerResponse.body ?? '';\n responseStream = awslambda.HttpResponseStream.from(responseStream, handlerResponse);\n }\n // Source @datastream/core (MIT)\n let handlerStream;\n if (handlerBody._readableState) {\n handlerStream = handlerBody;\n } else if (typeof handlerBody === 'string') {\n function* iterator(input) {\n const size = 16384 // 16 * 1024 // Node.js default\n ;\n let position = 0;\n const length = input.length;\n while(position < length){\n yield input.substring(position, position + size);\n position += size;\n }\n }\n handlerStream = Readable.from(iterator(handlerBody));\n }\n if (!handlerStream) {\n throw new Error('handler response not a ReadableStream');\n }\n await pipeline(handlerStream, responseStream);\n }) : middyHandler;\n middy.use = (middlewares)=>{\n if (!Array.isArray(middlewares)) {\n middlewares = [\n middlewares\n ];\n }\n for (const middleware of middlewares){\n const { before, after, onError } = middleware;\n if (!before && !after && !onError) {\n throw new Error('Middleware must be an object containing at least one key among \"before\", \"after\", \"onError\"');\n }\n if (before) middy.before(before);\n if (after) middy.after(after);\n if (onError) middy.onError(onError);\n }\n return middy;\n };\n // Inline Middlewares\n middy.before = (beforeMiddleware)=>{\n beforeMiddlewares.push(beforeMiddleware);\n return middy;\n };\n middy.after = (afterMiddleware)=>{\n afterMiddlewares.unshift(afterMiddleware);\n return middy;\n };\n middy.onError = (onErrorMiddleware)=>{\n onErrorMiddlewares.unshift(onErrorMiddleware);\n return middy;\n };\n middy.handler = (replaceLambdaHandler)=>{\n lambdaHandler = replaceLambdaHandler;\n return middy;\n };\n return middy;\n};\nconst runRequest = async (request, beforeMiddlewares, lambdaHandler, afterMiddlewares, onErrorMiddlewares, plugin)=>{\n let timeoutAbort;\n const timeoutEarly = plugin.timeoutEarly && request.context.getRemainingTimeInMillis // disable when AWS context missing (tests, containers)\n ;\n try {\n await runMiddlewares(request, beforeMiddlewares, plugin);\n // Check if before stack hasn't exit early\n if (typeof request.response === 'undefined') {\n plugin.beforeHandler?.();\n const handlerAbort = new AbortController();\n if (timeoutEarly) timeoutAbort = new AbortController();\n request.response = await Promise.race([\n lambdaHandler(request.event, request.context, {\n signal: handlerAbort.signal\n }),\n timeoutEarly ? setTimeout(request.context.getRemainingTimeInMillis() - plugin.timeoutEarlyInMillis, undefined, {\n signal: timeoutAbort.signal\n }).then(()=>{\n handlerAbort.abort();\n return plugin.timeoutEarlyResponse();\n }) : Promise.race([])\n ]);\n timeoutAbort?.abort() // lambdaHandler may not be a promise\n ;\n plugin.afterHandler?.();\n await runMiddlewares(request, afterMiddlewares, plugin);\n }\n } catch (e) {\n timeoutAbort?.abort() // timeout should be aborted on errors\n ;\n // Reset response changes made by after stack before error thrown\n request.response = undefined;\n request.error = e;\n try {\n await runMiddlewares(request, onErrorMiddlewares, plugin);\n } catch (e) {\n // Save error that wasn't handled\n e.originalError = request.error;\n request.error = e;\n throw request.error;\n }\n // Catch if onError stack hasn't handled the error\n if (typeof request.response === 'undefined') throw request.error;\n } finally{\n await plugin.requestEnd?.(request);\n }\n return request.response;\n};\nconst runMiddlewares = async (request, middlewares, plugin)=>{\n for (const nextMiddleware of middlewares){\n plugin.beforeMiddleware?.(nextMiddleware.name);\n const res = await nextMiddleware(request);\n plugin.afterMiddleware?.(nextMiddleware.name);\n // short circuit chaining and respond early\n if (typeof res !== 'undefined') {\n request.response = res;\n return;\n }\n }\n};\nexport default middy;\n\n", "export const createPrefetchClient = (options) => {\n\tconst { awsClientOptions } = options;\n\tconst client = new options.AwsClient(awsClientOptions);\n\n\t// AWS XRay\n\tif (options.awsClientCapture) {\n\t\tif (options.disablePrefetch) {\n\t\t\treturn options.awsClientCapture(client);\n\t\t}\n\t\tconsole.warn(\"Unable to apply X-Ray outside of handler invocation scope.\");\n\t}\n\n\treturn client;\n};\n\nexport const createClient = async (options, request) => {\n\tlet awsClientCredentials = {};\n\n\t// Role Credentials\n\tif (options.awsClientAssumeRole) {\n\t\tif (!request) {\n\t\t\tthrow new Error(\"Request required when assuming role\", {\n\t\t\t\tcause: { package: \"@middy/util\" },\n\t\t\t});\n\t\t}\n\t\tawsClientCredentials = await getInternal(\n\t\t\t{ credentials: options.awsClientAssumeRole },\n\t\t\trequest,\n\t\t);\n\t}\n\n\tawsClientCredentials = {\n\t\t...awsClientCredentials,\n\t\t...options.awsClientOptions,\n\t};\n\n\treturn createPrefetchClient({\n\t\t...options,\n\t\tawsClientOptions: awsClientCredentials,\n\t});\n};\n\nexport const canPrefetch = (options = {}) => {\n\treturn !options.awsClientAssumeRole && !options.disablePrefetch;\n};\n\n// Internal Context\nexport const getInternal = async (variables, request) => {\n\tif (!variables || !request) return {};\n\tlet keys = [];\n\tlet values = [];\n\tif (variables === true) {\n\t\tkeys = values = Object.keys(request.internal);\n\t} else if (typeof variables === \"string\") {\n\t\tkeys = values = [variables];\n\t} else if (Array.isArray(variables)) {\n\t\tkeys = values = variables;\n\t} else if (typeof variables === \"object\") {\n\t\tkeys = Object.keys(variables);\n\t\tvalues = Object.values(variables);\n\t}\n\tconst promises = [];\n\tfor (const internalKey of values) {\n\t\t// 'internal.key.sub_value' -> { [key]: internal.key.sub_value }\n\t\tconst pathOptionKey = internalKey.split(\".\");\n\t\tconst rootOptionKey = pathOptionKey.shift();\n\t\tlet valuePromise = request.internal[rootOptionKey];\n\t\tif (!isPromise(valuePromise)) {\n\t\t\tvaluePromise = Promise.resolve(valuePromise);\n\t\t}\n\t\tpromises.push(\n\t\t\tvaluePromise.then((value) =>\n\t\t\t\tpathOptionKey.reduce((p, c) => p?.[c], value),\n\t\t\t),\n\t\t);\n\t}\n\t// ensure promise has resolved by the time it's needed\n\t// If one of the promises throws it will bubble up to @middy/core\n\tvalues = await Promise.allSettled(promises);\n\tconst errors = values\n\t\t.filter((res) => res.status === \"rejected\")\n\t\t.map((res) => res.reason);\n\tif (errors.length) {\n\t\tthrow new Error(\"Failed to resolve internal values\", {\n\t\t\tcause: { package: \"@middy/util\", data: errors },\n\t\t});\n\t}\n\tconst obj = {};\n\tfor (let i = keys.length; i--; ) {\n\t\tobj[sanitizeKey(keys[i])] = values[i].value;\n\t}\n\treturn obj;\n};\n\nconst isPromise = (promise) => typeof promise?.then === \"function\";\n\nconst sanitizeKeyPrefixLeadingNumber = /^([0-9])/;\nconst sanitizeKeyRemoveDisallowedChar = /[^a-zA-Z0-9]+/g;\nexport const sanitizeKey = (key) => {\n\treturn key\n\t\t.replace(sanitizeKeyPrefixLeadingNumber, \"_$1\")\n\t\t.replace(sanitizeKeyRemoveDisallowedChar, \"_\");\n};\n\n// fetch Cache\nconst cache = {}; // key: { value:{fetchKey:Promise}, expiry }\nexport const processCache = (\n\toptions,\n\tmiddlewareFetch = () => undefined,\n\trequest = {},\n) => {\n\tlet { cacheKey, cacheKeyExpiry, cacheExpiry } = options;\n\tcacheExpiry = cacheKeyExpiry?.[cacheKey] ?? cacheExpiry;\n\tconst now = Date.now();\n\tif (cacheExpiry) {\n\t\tconst cached = getCache(cacheKey);\n\t\tconst unexpired = cached.expiry && (cacheExpiry < 0 || cached.expiry > now);\n\n\t\tif (unexpired) {\n\t\t\tif (cached.modified) {\n\t\t\t\tconst value = middlewareFetch(request, cached.value);\n\t\t\t\tObject.assign(cached.value, value);\n\t\t\t\tcache[cacheKey] = { value: cached.value, expiry: cached.expiry };\n\t\t\t\treturn cache[cacheKey];\n\t\t\t}\n\t\t\treturn { ...cached, cache: true };\n\t\t}\n\t}\n\tconst value = middlewareFetch(request);\n\t// secrets-manager can override to unix timestamp\n\tconst expiry = cacheExpiry > 86400000 ? cacheExpiry : now + cacheExpiry;\n\tconst duration = cacheExpiry > 86400000 ? cacheExpiry - now : cacheExpiry;\n\tif (cacheExpiry) {\n\t\tconst refresh =\n\t\t\tduration > 0\n\t\t\t\t? setTimeout(\n\t\t\t\t\t\t() => processCache(options, middlewareFetch, request),\n\t\t\t\t\t\tduration,\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\t\tcache[cacheKey] = { value, expiry, refresh };\n\t}\n\treturn { value, expiry };\n};\n\nexport const catchInvalidSignatureException = (e, client, command) => {\n\tif (e.__type === \"InvalidSignatureException\") {\n\t\treturn client.send(command);\n\t}\n\tthrow e;\n};\n\nexport const getCache = (key) => {\n\tif (!cache[key]) return {};\n\treturn cache[key];\n};\n\n// Used to remove parts of a cache\nexport const modifyCache = (cacheKey, value) => {\n\tif (!cache[cacheKey]) return;\n\tclearTimeout(cache[cacheKey]?.refresh);\n\tcache[cacheKey] = { ...cache[cacheKey], value, modified: true };\n};\n\nexport const clearCache = (inputKeys = null) => {\n\tlet keys = inputKeys;\n\tkeys ??= Object.keys(cache);\n\tif (!Array.isArray(keys)) {\n\t\tkeys = [keys];\n\t}\n\tfor (const cacheKey of keys) {\n\t\tclearTimeout(cache[cacheKey]?.refresh);\n\t\tcache[cacheKey] = undefined;\n\t}\n};\n\nexport const jsonSafeParse = (text, reviver) => {\n\tif (typeof text !== \"string\") return text;\n\tconst firstChar = text[0];\n\tif (firstChar !== \"{\" && firstChar !== \"[\" && firstChar !== '\"') return text;\n\ttry {\n\t\treturn JSON.parse(text, reviver);\n\t} catch (_e) {}\n\n\treturn text;\n};\n\nexport const jsonSafeStringify = (value, replacer, space) => {\n\ttry {\n\t\treturn JSON.stringify(value, replacer, space);\n\t} catch (_e) {}\n\n\treturn value;\n};\n\nexport const normalizeHttpResponse = (request) => {\n\tlet { response } = request;\n\tif (typeof response === \"undefined\") {\n\t\tresponse = {};\n\t} else if (\n\t\ttypeof response?.statusCode === \"undefined\" &&\n\t\ttypeof response?.body === \"undefined\" &&\n\t\ttypeof response?.headers === \"undefined\"\n\t) {\n\t\tresponse = { statusCode: 200, body: response };\n\t}\n\tresponse.statusCode ??= 500;\n\tresponse.headers ??= {};\n\trequest.response = response;\n\treturn response;\n};\n\nconst createErrorRegexp = /[^a-zA-Z]/g;\nexport class HttpError extends Error {\n\tconstructor(code, optionalMessage, optionalOptions = {}) {\n\t\tlet message = optionalMessage;\n\t\tlet options = optionalOptions;\n\t\tif (message && typeof message !== \"string\") {\n\t\t\toptions = message;\n\t\t\tmessage = undefined;\n\t\t}\n\t\tmessage ??= httpErrorCodes[code];\n\t\tsuper(message, options);\n\n\t\tconst name = httpErrorCodes[code].replace(createErrorRegexp, \"\");\n\t\tthis.name = name.substr(-5) !== \"Error\" ? `${name}Error` : name;\n\n\t\tthis.status = this.statusCode = code; // setting `status` for backwards compatibility w/ `http-errors`\n\t\tthis.expose = options.expose ?? code < 500;\n\t}\n}\n\nexport const createError = (code, message, properties = {}) => {\n\treturn new HttpError(code, message, properties);\n};\n\nconst httpErrorCodes = {\n\t100: \"Continue\",\n\t101: \"Switching Protocols\",\n\t102: \"Processing\",\n\t103: \"Early Hints\",\n\t200: \"OK\",\n\t201: \"Created\",\n\t202: \"Accepted\",\n\t203: \"Non-Authoritative Information\",\n\t204: \"No Content\",\n\t205: \"Reset Content\",\n\t206: \"Partial Content\",\n\t207: \"Multi-Status\",\n\t208: \"Already Reported\",\n\t226: \"IM Used\",\n\t300: \"Multiple Choices\",\n\t301: \"Moved Permanently\",\n\t302: \"Found\",\n\t303: \"See Other\",\n\t304: \"Not Modified\",\n\t305: \"Use Proxy\",\n\t306: \"(Unused)\",\n\t307: \"Temporary Redirect\",\n\t308: \"Permanent Redirect\",\n\t400: \"Bad Request\",\n\t401: \"Unauthorized\",\n\t402: \"Payment Required\",\n\t403: \"Forbidden\",\n\t404: \"Not Found\",\n\t405: \"Method Not Allowed\",\n\t406: \"Not Acceptable\",\n\t407: \"Proxy Authentication Required\",\n\t408: \"Request Timeout\",\n\t409: \"Conflict\",\n\t410: \"Gone\",\n\t411: \"Length Required\",\n\t412: \"Precondition Failed\",\n\t413: \"Payload Too Large\",\n\t414: \"URI Too Long\",\n\t415: \"Unsupported Media Type\",\n\t416: \"Range Not Satisfiable\",\n\t417: \"Expectation Failed\",\n\t418: \"I'm a teapot\",\n\t421: \"Misdirected Request\",\n\t422: \"Unprocessable Entity\",\n\t423: \"Locked\",\n\t424: \"Failed Dependency\",\n\t425: \"Unordered Collection\",\n\t426: \"Upgrade Required\",\n\t428: \"Precondition Required\",\n\t429: \"Too Many Requests\",\n\t431: \"Request Header Fields Too Large\",\n\t451: \"Unavailable For Legal Reasons\",\n\t500: \"Internal Server Error\",\n\t501: \"Not Implemented\",\n\t502: \"Bad Gateway\",\n\t503: \"Service Unavailable\",\n\t504: \"Gateway Timeout\",\n\t505: \"HTTP Version Not Supported\",\n\t506: \"Variant Also Negotiates\",\n\t507: \"Insufficient Storage\",\n\t508: \"Loop Detected\",\n\t509: \"Bandwidth Limit Exceeded\",\n\t510: \"Not Extended\",\n\t511: \"Network Authentication Required\",\n};\n", "import { jsonSafeParse, normalizeHttpResponse } from \"@middy/util\";\n\nconst defaults = {\n\tlogger: console.error, // TODO v7 change to pass in request\n\tfallbackMessage: undefined,\n};\n\nconst httpErrorHandlerMiddleware = (opts = {}) => {\n\tconst options = { ...defaults, ...opts };\n\n\tconst httpErrorHandlerMiddlewareOnError = async (request) => {\n\t\tif (request.response !== undefined) return;\n\t\tif (typeof options.logger === \"function\") {\n\t\t\toptions.logger(request.error);\n\t\t}\n\n\t\t// Set default expose value, only passes in when there is an override\n\t\tif (request.error.statusCode && request.error.expose === undefined) {\n\t\t\trequest.error.expose = request.error.statusCode < 500;\n\t\t}\n\n\t\t// Non-http error OR expose set to false\n\t\tif (!request.error.expose || !request.error.statusCode) {\n\t\t\trequest.error = {\n\t\t\t\tstatusCode: 500,\n\t\t\t\tmessage: options.fallbackMessage,\n\t\t\t\texpose: true,\n\t\t\t};\n\t\t}\n\n\t\tif (request.error.expose) {\n\t\t\tnormalizeHttpResponse(request);\n\t\t\tconst { statusCode, message, headers } = request.error;\n\n\t\t\trequest.response = {\n\t\t\t\t...request.response,\n\t\t\t\tstatusCode,\n\t\t\t\theaders: {\n\t\t\t\t\t...request.response.headers,\n\t\t\t\t\t...headers,\n\t\t\t\t},\n\t\t\t};\n\n\t\t\tif (message) {\n\t\t\t\tconst headerContentType =\n\t\t\t\t\ttypeof jsonSafeParse(message) === \"string\"\n\t\t\t\t\t\t? \"text/plain\"\n\t\t\t\t\t\t: \"application/json\";\n\t\t\t\trequest.response.body = message;\n\t\t\t\trequest.response.headers[\"Content-Type\"] = headerContentType;\n\t\t\t}\n\t\t}\n\t};\n\n\treturn {\n\t\tonError: httpErrorHandlerMiddlewareOnError,\n\t};\n};\nexport default httpErrorHandlerMiddleware;\n"],
5
+ "mappings": ";AAAA;AAAA,EACE;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAGA;AAAA,OACK;AAEP,SAAS,cAAc;AACvB,OAAOA,aAAY;AACnB,SAAS,mBAAmB;;;ACf5B,OAAOC,aAAY;;;ACAZ,IAAM,wBAAwB,CAAC,UAA2B;AAC/D,MAAI,iBAAiB,OAAO;AAC1B,WAAO,MAAM;AAAA,EACf,WAAW,OAAO,UAAU,UAAU;AACpC,WAAO;AAAA,EACT,WAAW,OAAO,UAAU,YAAY,UAAU,MAAM;AACtD,WAAO,KAAK,UAAU,KAAK;AAAA,EAC7B,OAAO;AACL,WAAO,OAAO,KAAK;AAAA,EACrB;AACF;;;ACVA,SAAS,eAAe;AAEjB,IAAM,iBAAiB;AACvB,IAAM,gBAAgB;AACtB,IAAM,iBAAiB;AACvB,IAAM,gBAAgB;AACtB,IAAM,mBAAmB;AACzB,IAAM,0BAA0B;AAChC,IAAM,qBAAqB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AACF;AACO,IAAM,2BAA2B,CAAC,aAAa;AAE/C,IAAM,wBAAwB;AAAA,EACnC,CAAC,KAAK,GAAG;AAAA,EACT,CAAC,MAAM,GAAG;AACZ;AAEO,IAAM,eAAe,CAAC;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AACF,MAIM;AACJ,SAAO,GAAG,IACP,MAAM,GAAG,EACT,MAAM,GAAG,EAAE,EACX,KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,MAAM,IAAI,gBAAgB;AACrD;AAEO,IAAM,qBAAqB,CAAC,EA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oBAAoB;AAAA,EACtC,QAAQ,qBAAqB,WAAW;AAC1C;AAuBO,IAAM,4BAA4B,CAAC,YAAwB;AAChE,QAAM,YAAY,IAAI,eAAe,UAAU,GAAG;AAClD,SAAO,OAAO,OAAY,YACxB,uBAAuB,OAAO,SAAS,WAAW;AAAA,IAChD;AAAA,EACF,CAAC;AACL;",
6
+ "names": ["assert", "assert", "logger", "assert", "logger", "assert", "assert", "logger", "assert", "assert", "logger", "assert", "assert", "logger", "assert", "assert", "logger", "assert", "logger", "assert", "InvokeStore", "Logger", "setTimeout", "middy", "e", "Logger", "logger", "metrics"]
7
7
  }
@@ -7,6 +7,7 @@ import middy from "@middy/core";
7
7
  import type { Handler, SQSHandler } from "aws-lambda";
8
8
  import { DynamoDBService, LocationService, S3Service, SQSService, SSMService, STSService } from "../services/index.js";
9
9
  export declare const logger: Logger;
10
+ export type { Logger } from "@aws-lambda-powertools/logger";
10
11
  export declare const tracer: Tracer;
11
12
  export declare const metrics: Metrics;
12
13
  export declare const withMiddlewares: (handler: Handler) => middy.MiddyfiedHandler<any, any, Error, any>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aspan-corporation/ac-shared",
3
- "version": "1.2.7",
3
+ "version": "1.2.9",
4
4
  "description": "",
5
5
  "keywords": [],
6
6
  "main": "lib/index.js",