@aspan-corporation/ac-shared 1.2.20 → 1.2.21

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
@@ -1,1694 +1,3 @@
1
- // src/services/s3.ts
2
- import {
3
- DeleteObjectCommand,
4
- DeleteObjectsCommand,
5
- GetObjectCommand,
6
- HeadObjectCommand,
7
- ListObjectsV2Command,
8
- PutObjectCommand,
9
- S3Client
10
- } from "@aws-sdk/client-s3";
11
- import { Upload } from "@aws-sdk/lib-storage";
12
- import assert3 from "node:assert/strict";
13
- import { PassThrough } from "node:stream";
14
-
15
- // src/utils/index.ts
16
- import assert2 from "node:assert/strict";
17
-
18
- // src/utils/normalizeErrorMessage.ts
19
- var normalizeErrorMessage = (error) => {
20
- if (error instanceof Error) {
21
- return error.message;
22
- } else if (typeof error === "string") {
23
- return error;
24
- } else if (typeof error === "object" && error !== null) {
25
- return JSON.stringify(error);
26
- } else {
27
- return String(error);
28
- }
29
- };
30
-
31
- // src/utils/thumbsKey.ts
32
- import { extname } from "node:path";
33
- var JPEG_EXTENSION = "jpeg";
34
- var JPG_EXTENSION = "jpg";
35
- var HEIC_EXTENSION = "heic";
36
- var MOV_EXTENSION = "mov";
37
- var THUMBS_EXTENSION = JPG_EXTENSION;
38
- var ENCODED_VIDEO_EXTENSION = "mp4";
39
- var ALLOWED_EXTENSIONS = [
40
- JPEG_EXTENSION,
41
- JPG_EXTENSION,
42
- HEIC_EXTENSION
43
- ];
44
- var ALLOWED_VIDEO_EXTENSIONS = [MOV_EXTENSION];
45
- var THUMBNAIL_RESOLUTIONS = [
46
- [200, 200],
47
- [1180, 820]
48
- ];
49
- var getThumbsKey = ({
50
- key,
51
- width,
52
- height
53
- }) => {
54
- return `${key.split(".").slice(0, -1).join(".")}.${width}x${height}.${THUMBS_EXTENSION}`;
55
- };
56
- var getEncodedVideoKey = ({ key }) => {
57
- return `${key.split(".").slice(0, -1).join(".")}.${ENCODED_VIDEO_EXTENSION}`;
58
- };
59
- var getKeyExtension = (key) => extname(key).slice(1).toLowerCase();
60
- var isAllowedExtension = (key) => {
61
- const ext = getKeyExtension(key);
62
- return ALLOWED_EXTENSIONS.includes(ext);
63
- };
64
- var isAllowedVideoExtension = (key) => {
65
- const ext = getKeyExtension(key);
66
- return ALLOWED_VIDEO_EXTENSIONS.includes(ext);
67
- };
68
-
69
- // src/utils/helpers.ts
70
- var getObjectWithAssumeRoleCommandOutputAttribute = (assumeRoleCommandOutput) => assumeRoleCommandOutput ? {
71
- credentials: {
72
- accessKeyId: assumeRoleCommandOutput?.Credentials?.AccessKeyId,
73
- secretAccessKey: assumeRoleCommandOutput?.Credentials?.SecretAccessKey,
74
- sessionToken: assumeRoleCommandOutput?.Credentials?.SessionToken
75
- }
76
- } : {};
77
- var getObjectWithStackAttribute = (error) => error && error instanceof Error ? { stack: error.stack } : {};
78
-
79
- // src/utils/processMeta.ts
80
- import assert from "node:assert/strict";
81
- var processMeta = async ({
82
- id,
83
- meta,
84
- metaTableName,
85
- size,
86
- logger: logger2,
87
- locationService,
88
- dynamoDBService
89
- }) => {
90
- const latitude = Number(meta.find((tag) => tag.key === "latitude")?.value);
91
- const longitude = Number(meta.find((tag) => tag.key === "longitude")?.value);
92
- let geoPositionResult;
93
- if (!Number.isNaN(longitude) && !Number.isNaN(latitude)) {
94
- try {
95
- const res = await locationService.searchPlaceIndexForPositionCommand({
96
- IndexName: "TauPlaceIndex",
97
- Position: [longitude, latitude]
98
- });
99
- if (res?.Results && res?.Results?.length > 0) {
100
- geoPositionResult = res?.Results[0];
101
- } else {
102
- throw Error("Can not resolve geo data");
103
- }
104
- } catch (error) {
105
- logger2.error("Error fetching geo data", {
106
- message: error instanceof Error ? error.message : ""
107
- });
108
- }
109
- }
110
- const newTags = [
111
- ...meta,
112
- ...meta.find((tag) => tag.key === "dateCreated") ? [] : extractMetaFromKey(id),
113
- { key: "extension", value: getKeyExtension(id) },
114
- { key: "size", value: String(size) },
115
- { key: "sizeMb", value: String(Math.round(size / 1024 ** 2)) },
116
- ...geoPositionResult?.Place?.Label ? [{ key: "label", value: geoPositionResult?.Place?.Label }] : [],
117
- ...geoPositionResult?.Place?.Country ? [{ key: "country", value: geoPositionResult?.Place?.Country }] : [],
118
- ...geoPositionResult?.Place?.Region ? [{ key: "region", value: geoPositionResult?.Place?.Region }] : [],
119
- ...geoPositionResult?.Place?.SubRegion ? [{ key: "subRegion", value: geoPositionResult?.Place?.SubRegion }] : [],
120
- ...geoPositionResult?.Place?.Municipality ? [{ key: "municipality", value: geoPositionResult?.Place?.Municipality }] : [],
121
- ...geoPositionResult?.Place?.Neighborhood ? [{ key: "neighborhood", value: geoPositionResult?.Place?.Neighborhood }] : [],
122
- ...geoPositionResult?.Place?.PostalCode ? [{ key: "postalCode", value: geoPositionResult?.Place?.PostalCode }] : []
123
- ].map((tag) => ({
124
- key: "ac:tau:" + tag.key,
125
- value: tag.value
126
- }));
127
- logger2.debug("metaData", { newTags });
128
- logger2.debug("trying to read existing metadata");
129
- const getResponse = await dynamoDBService.getCommand({
130
- TableName: metaTableName,
131
- Key: {
132
- id
133
- }
134
- });
135
- const oldTags = getResponse.Item?.tags;
136
- logger2.debug("existing tags", { getResponse });
137
- const reconciledTags = reconcileTags({ newTags, oldTags }, logger2);
138
- logger2.debug("result", { reconciledTags });
139
- const updateResponse = await dynamoDBService.updateCommand({
140
- TableName: metaTableName,
141
- Key: {
142
- id
143
- },
144
- UpdateExpression: "set tags = :tags",
145
- ExpressionAttributeValues: {
146
- ":tags": reconciledTags
147
- },
148
- ReturnValues: "ALL_NEW"
149
- });
150
- logger2.debug("sent UpdateCommand", { updateResponse });
151
- };
152
- var reconcileTags = ({ oldTags = [], newTags = [] }, logger2) => oldTags.reduce((acc, cur) => {
153
- if (acc.find((element) => element.key === cur.key)) {
154
- return acc;
155
- } else {
156
- logger2.debug("added", cur);
157
- return [...acc, cur];
158
- }
159
- }, newTags);
160
- var SUBSTRING_ANSI_DATES_BEGIN_WITH = "20";
161
- var extractMetaFromKey = (key) => {
162
- if (!key)
163
- return [];
164
- let firstToken = void 0;
165
- try {
166
- const folder = key.split("/").at(-2);
167
- assert(typeof folder === "string");
168
- firstToken = folder.split(".")[0];
169
- } catch (error) {
170
- }
171
- if (firstToken === void 0 || firstToken.length !== 8 || !firstToken.startsWith(SUBSTRING_ANSI_DATES_BEGIN_WITH))
172
- return [];
173
- const year = Number(firstToken.substring(0, 4));
174
- const month = Number(firstToken.substring(4, 6)) - 1;
175
- const day = Number(firstToken.substring(6));
176
- if (isNaN(year) || isNaN(month) || isNaN(day))
177
- return [];
178
- if (year < 2e3 || month < 1 || month > 11 || day < 1 || day > 31)
179
- return [];
180
- const dateCreatedBin = new Date(year, month, day);
181
- return [
182
- { key: "dateCreated", value: dateCreatedBin.toISOString() },
183
- { key: "yearCreated", value: dateCreatedBin.getFullYear().toString() },
184
- { key: "dayCreated", value: dateCreatedBin.getDate().toString() },
185
- {
186
- key: "monthCreated",
187
- value: (dateCreatedBin.getMonth() + 1).toString()
188
- }
189
- ];
190
- };
191
-
192
- // src/utils/index.ts
193
- var assertEnvVar = (envVar) => {
194
- assert2(process.env[envVar], `${envVar} is not set`);
195
- return process.env[envVar];
196
- };
197
-
198
- // src/services/s3.ts
199
- import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
200
- var S3Service = class {
201
- logger;
202
- client;
203
- constructor({
204
- logger: logger2,
205
- client,
206
- assumeRoleCommandOutput,
207
- region
208
- }) {
209
- this.logger = logger2;
210
- if (client) {
211
- this.client = client;
212
- } else {
213
- assert3(region, "Region must be provided if client is not passed");
214
- this.client = new S3Client({
215
- region,
216
- ...getObjectWithAssumeRoleCommandOutputAttribute(
217
- assumeRoleCommandOutput
218
- )
219
- });
220
- }
221
- }
222
- createS3UploadStream(putObjectCommandInput) {
223
- this.logger.debug("upload stream started", { putObjectCommandInput });
224
- const pass = new PassThrough();
225
- const parallelUploads = new Upload({
226
- client: this.client,
227
- params: {
228
- ...putObjectCommandInput,
229
- Body: pass
230
- }
231
- });
232
- const donePromise = parallelUploads.done().then(() => this.logger.debug("upload stream finished")).catch((err) => {
233
- this.logger.error("upload stream error", err);
234
- pass.destroy(err);
235
- });
236
- return { stream: pass, done: donePromise };
237
- }
238
- async createS3DownloadStream(getObjectCommandInput) {
239
- this.logger.debug("download stream started", { getObjectCommandInput });
240
- const item = await this.client.send(
241
- new GetObjectCommand(getObjectCommandInput)
242
- );
243
- this.logger.debug("download stream finished");
244
- return item.Body;
245
- }
246
- async listObjectsV2(listObjectsV2CommandInput) {
247
- this.logger.debug("listObjectsV2", { listObjectsV2CommandInput });
248
- return await this.client.send(
249
- new ListObjectsV2Command(listObjectsV2CommandInput)
250
- );
251
- }
252
- async getObject(getObjectCommandInput) {
253
- this.logger.debug("getObject", { getObjectCommandInput });
254
- const stream = await this.createS3DownloadStream(getObjectCommandInput);
255
- return Buffer.from(await stream.transformToByteArray());
256
- }
257
- async getSignedUrl(getObjectCommandInput) {
258
- this.logger.debug("getSignedUrl", { getObjectCommandInput });
259
- const signedUrl = await getSignedUrl(
260
- this.client,
261
- new GetObjectCommand(getObjectCommandInput),
262
- { expiresIn: 3600 }
263
- );
264
- return signedUrl;
265
- }
266
- async putObject(putObjectCommandInput) {
267
- this.logger.debug("putObject", { putObjectCommandInput });
268
- return await this.client.send(new PutObjectCommand(putObjectCommandInput));
269
- }
270
- async headObject(headObjectCommandInput) {
271
- this.logger.debug("headObject", { headObjectCommandInput });
272
- return await this.client.send(
273
- new HeadObjectCommand(headObjectCommandInput)
274
- );
275
- }
276
- async checkIfObjectExists(headObjectCommandInput) {
277
- this.logger.debug("checkIfObjectExists", { headObjectCommandInput });
278
- try {
279
- await this.headObject(headObjectCommandInput);
280
- return true;
281
- } catch (error) {
282
- if (error.name === "NotFound") {
283
- return false;
284
- }
285
- throw error;
286
- }
287
- }
288
- async deleteObject(deleteObjectCommandInput) {
289
- this.logger.debug("deleteObject", { deleteObjectCommandInput });
290
- return await this.client.send(
291
- new DeleteObjectCommand(deleteObjectCommandInput)
292
- );
293
- }
294
- async deleteObjects(deleteObjectsCommandInput) {
295
- this.logger.debug("deleteObjects", { deleteObjectsCommandInput });
296
- return await this.client.send(
297
- new DeleteObjectsCommand(deleteObjectsCommandInput)
298
- );
299
- }
300
- };
301
-
302
- // src/services/dynamoDB.ts
303
- import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
304
- import {
305
- DynamoDBDocumentClient,
306
- GetCommand,
307
- PutCommand,
308
- QueryCommand,
309
- UpdateCommand,
310
- ScanCommand,
311
- BatchWriteCommand
312
- } from "@aws-sdk/lib-dynamodb";
313
- import assert4 from "node:assert/strict";
314
- var DynamoDBService = class {
315
- logger;
316
- client;
317
- documentClient;
318
- constructor({
319
- logger: logger2,
320
- client,
321
- assumeRoleCommandOutput,
322
- region
323
- }) {
324
- this.logger = logger2;
325
- if (client) {
326
- this.client = client;
327
- } else {
328
- assert4(region, "Region must be provided if client is not passed");
329
- this.client = new DynamoDBClient({
330
- region,
331
- ...getObjectWithAssumeRoleCommandOutputAttribute(
332
- assumeRoleCommandOutput
333
- )
334
- });
335
- }
336
- this.documentClient = DynamoDBDocumentClient.from(this.client);
337
- }
338
- async getCommand(getCommandInput) {
339
- return await this.documentClient.send(new GetCommand(getCommandInput));
340
- }
341
- async updateCommand(updateCommandInput) {
342
- return await this.documentClient.send(
343
- new UpdateCommand(updateCommandInput)
344
- );
345
- }
346
- async queryCommand(queryCommandInput) {
347
- return await this.documentClient.send(new QueryCommand(queryCommandInput));
348
- }
349
- async putCommand(putCommandInput) {
350
- return await this.documentClient.send(new PutCommand(putCommandInput));
351
- }
352
- async checkIfItemExists(checkInput) {
353
- const result = await this.getCommand(checkInput);
354
- return !!result.Item;
355
- }
356
- async scanCommand(scanCommandInput) {
357
- return await this.client.send(new ScanCommand(scanCommandInput));
358
- }
359
- async batchWriteCommand(batchWriteCommandInput) {
360
- return await this.client.send(
361
- new BatchWriteCommand(batchWriteCommandInput)
362
- );
363
- }
364
- };
365
-
366
- // src/services/ssm.ts
367
- import {
368
- GetParameterCommand,
369
- PutParameterCommand,
370
- SSMClient
371
- } from "@aws-sdk/client-ssm";
372
- import assert5 from "node:assert/strict";
373
- var SSMService = class {
374
- logger;
375
- client;
376
- constructor({
377
- logger: logger2,
378
- client,
379
- assumeRoleCommandOutput,
380
- region
381
- }) {
382
- this.logger = logger2;
383
- if (client) {
384
- this.client = client;
385
- } else {
386
- assert5(region, "Region must be provided if client is not passed");
387
- this.client = new SSMClient({
388
- region,
389
- ...getObjectWithAssumeRoleCommandOutputAttribute(
390
- assumeRoleCommandOutput
391
- )
392
- });
393
- }
394
- }
395
- async getParameter(params) {
396
- return await this.client.send(new GetParameterCommand(params));
397
- }
398
- async putParameter(params) {
399
- return await this.client.send(new PutParameterCommand(params));
400
- }
401
- };
402
-
403
- // src/services/sqs.ts
404
- import {
405
- DeleteMessageCommand,
406
- ReceiveMessageCommand,
407
- SQSClient,
408
- SendMessageBatchCommand,
409
- SendMessageCommand
410
- } from "@aws-sdk/client-sqs";
411
- import assert6 from "node:assert/strict";
412
- var SQSService = class {
413
- logger;
414
- client;
415
- constructor({
416
- logger: logger2,
417
- client,
418
- assumeRoleCommandOutput,
419
- region
420
- }) {
421
- this.logger = logger2;
422
- if (client) {
423
- this.client = client;
424
- } else {
425
- assert6(region, "Region must be provided if client is not passed");
426
- this.client = new SQSClient({
427
- region,
428
- ...getObjectWithAssumeRoleCommandOutputAttribute(
429
- assumeRoleCommandOutput
430
- )
431
- });
432
- }
433
- }
434
- async sendMessage(params) {
435
- return await this.client.send(new SendMessageCommand(params));
436
- }
437
- async sendMessageBatch(params) {
438
- return await this.client.send(new SendMessageBatchCommand(params));
439
- }
440
- async receiveMessage(params) {
441
- return await this.client.send(new ReceiveMessageCommand(params));
442
- }
443
- async deleteMessage(params) {
444
- return await this.client.send(new DeleteMessageCommand(params));
445
- }
446
- };
447
-
448
- // src/services/sts.ts
449
- import { Logger } from "@aws-lambda-powertools/logger";
450
- import {
451
- AssumeRoleCommand,
452
- GetCallerIdentityCommand,
453
- STSClient
454
- } from "@aws-sdk/client-sts";
455
- import assert7 from "node:assert/strict";
456
- var STSService = class {
457
- logger;
458
- client;
459
- constructor({
460
- logger: logger2,
461
- region,
462
- client
463
- }) {
464
- if (logger2) {
465
- this.logger = logger2;
466
- } else {
467
- this.logger = new Logger();
468
- this.logger.appendKeys({ scope: "STSService" });
469
- }
470
- if (client) {
471
- this.client = client;
472
- } else {
473
- assert7(region, "Region must be provided if client is not passed");
474
- this.client = new STSClient({
475
- region
476
- });
477
- }
478
- }
479
- async getCallerIdentity() {
480
- this.logger.debug("getCallerIdentity");
481
- return await this.client.send(new GetCallerIdentityCommand({}));
482
- }
483
- async assumeRole(assumeRoleCommandInput) {
484
- this.logger.debug("assumeRole", { assumeRoleCommandInput });
485
- return await this.client.send(
486
- new AssumeRoleCommand(assumeRoleCommandInput)
487
- );
488
- }
489
- };
490
-
491
- // src/services/location.ts
492
- import {
493
- LocationClient,
494
- SearchPlaceIndexForPositionCommand
495
- } from "@aws-sdk/client-location";
496
- import assert8 from "node:assert/strict";
497
- var LocationService = class {
498
- logger;
499
- client;
500
- constructor({
501
- logger: logger2,
502
- client,
503
- assumeRoleCommandOutput,
504
- region
505
- }) {
506
- this.logger = logger2;
507
- if (client) {
508
- this.client = client;
509
- } else {
510
- assert8(region, "Region must be provided if client is not passed");
511
- this.client = new LocationClient({
512
- region,
513
- ...getObjectWithAssumeRoleCommandOutputAttribute(
514
- assumeRoleCommandOutput
515
- )
516
- });
517
- }
518
- }
519
- async searchPlaceIndexForPositionCommand(searchPlaceIndexForPositionCommandInput) {
520
- return await this.client.send(
521
- new SearchPlaceIndexForPositionCommand(
522
- searchPlaceIndexForPositionCommandInput
523
- )
524
- );
525
- }
526
- };
527
-
528
- // src/services/cloudWatch.ts
529
- import {
530
- CloudWatchLogsClient,
531
- DescribeLogStreamsCommand,
532
- PutLogEventsCommand
533
- } from "@aws-sdk/client-cloudwatch-logs";
534
- import assert9 from "node:assert/strict";
535
- var CloudWatchService = class {
536
- logger;
537
- client;
538
- constructor({
539
- logger: logger2,
540
- client,
541
- assumeRoleCommandOutput,
542
- region
543
- }) {
544
- this.logger = logger2;
545
- if (client) {
546
- this.client = client;
547
- } else {
548
- assert9(region, "Region must be provided if client is not passed");
549
- this.client = new CloudWatchLogsClient({
550
- region,
551
- ...getObjectWithAssumeRoleCommandOutputAttribute(
552
- assumeRoleCommandOutput
553
- )
554
- });
555
- }
556
- }
557
- async describeLogStreamsCommand(describeLogStreamsCommandInput) {
558
- this.logger.debug("describeLogStreamsCommand", {
559
- describeLogStreamsCommandInput
560
- });
561
- return await this.client.send(
562
- new DescribeLogStreamsCommand(describeLogStreamsCommandInput)
563
- );
564
- }
565
- async putLogEventsCommand(putLogEventsCommandInput) {
566
- this.logger.debug("putLogEventsCommand", { putLogEventsCommandInput });
567
- return await this.client.send(
568
- new PutLogEventsCommand(putLogEventsCommandInput)
569
- );
570
- }
571
- };
572
-
573
- // node_modules/@aws-lambda-powertools/commons/node_modules/@aws/lambda-invoke-store/dist-es/invoke-store.js
574
- var PROTECTED_KEYS = {
575
- REQUEST_ID: Symbol.for("_AWS_LAMBDA_REQUEST_ID"),
576
- X_RAY_TRACE_ID: Symbol.for("_AWS_LAMBDA_X_RAY_TRACE_ID"),
577
- TENANT_ID: Symbol.for("_AWS_LAMBDA_TENANT_ID")
578
- };
579
- var NO_GLOBAL_AWS_LAMBDA = ["true", "1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA ?? "");
580
- if (!NO_GLOBAL_AWS_LAMBDA) {
581
- globalThis.awslambda = globalThis.awslambda || {};
582
- }
583
- var InvokeStoreBase = class {
584
- static PROTECTED_KEYS = PROTECTED_KEYS;
585
- isProtectedKey(key) {
586
- return Object.values(PROTECTED_KEYS).includes(key);
587
- }
588
- getRequestId() {
589
- return this.get(PROTECTED_KEYS.REQUEST_ID) ?? "-";
590
- }
591
- getXRayTraceId() {
592
- return this.get(PROTECTED_KEYS.X_RAY_TRACE_ID);
593
- }
594
- getTenantId() {
595
- return this.get(PROTECTED_KEYS.TENANT_ID);
596
- }
597
- };
598
- var InvokeStoreSingle = class extends InvokeStoreBase {
599
- currentContext;
600
- getContext() {
601
- return this.currentContext;
602
- }
603
- hasContext() {
604
- return this.currentContext !== void 0;
605
- }
606
- get(key) {
607
- return this.currentContext?.[key];
608
- }
609
- set(key, value) {
610
- if (this.isProtectedKey(key)) {
611
- throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`);
612
- }
613
- this.currentContext = this.currentContext || {};
614
- this.currentContext[key] = value;
615
- }
616
- run(context, fn) {
617
- this.currentContext = context;
618
- return fn();
619
- }
620
- };
621
- var InvokeStoreMulti = class _InvokeStoreMulti extends InvokeStoreBase {
622
- als;
623
- static async create() {
624
- const instance = new _InvokeStoreMulti();
625
- const asyncHooks = await import("node:async_hooks");
626
- instance.als = new asyncHooks.AsyncLocalStorage();
627
- return instance;
628
- }
629
- getContext() {
630
- return this.als.getStore();
631
- }
632
- hasContext() {
633
- return this.als.getStore() !== void 0;
634
- }
635
- get(key) {
636
- return this.als.getStore()?.[key];
637
- }
638
- set(key, value) {
639
- if (this.isProtectedKey(key)) {
640
- throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`);
641
- }
642
- const store = this.als.getStore();
643
- if (!store) {
644
- throw new Error("No context available");
645
- }
646
- store[key] = value;
647
- }
648
- run(context, fn) {
649
- return this.als.run(context, fn);
650
- }
651
- };
652
- var InvokeStore;
653
- (function(InvokeStore3) {
654
- let instance = null;
655
- async function getInstanceAsync() {
656
- if (!instance) {
657
- instance = (async () => {
658
- const isMulti = "AWS_LAMBDA_MAX_CONCURRENCY" in process.env;
659
- const newInstance = isMulti ? await InvokeStoreMulti.create() : new InvokeStoreSingle();
660
- if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda?.InvokeStore) {
661
- return globalThis.awslambda.InvokeStore;
662
- } else if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda) {
663
- globalThis.awslambda.InvokeStore = newInstance;
664
- return newInstance;
665
- } else {
666
- return newInstance;
667
- }
668
- })();
669
- }
670
- return instance;
671
- }
672
- InvokeStore3.getInstanceAsync = getInstanceAsync;
673
- InvokeStore3._testing = process.env.AWS_LAMBDA_BENCHMARK_MODE === "1" ? {
674
- reset: () => {
675
- instance = null;
676
- if (globalThis.awslambda?.InvokeStore) {
677
- delete globalThis.awslambda.InvokeStore;
678
- }
679
- globalThis.awslambda = { InvokeStore: void 0 };
680
- }
681
- } : void 0;
682
- })(InvokeStore || (InvokeStore = {}));
683
-
684
- // node_modules/@aws-lambda-powertools/commons/lib/esm/constants.js
685
- var AWS_LAMBDA_MAX_CONCURRENCY = "AWS_LAMBDA_MAX_CONCURRENCY";
686
-
687
- // node_modules/@aws-lambda-powertools/commons/lib/esm/envUtils.js
688
- var getStringFromEnv = ({ key, defaultValue, errorMessage }) => {
689
- const value = process.env[key];
690
- if (value === void 0) {
691
- if (defaultValue !== void 0) {
692
- return defaultValue;
693
- }
694
- if (errorMessage) {
695
- throw new Error(errorMessage);
696
- }
697
- throw new Error(`Environment variable ${key} is required`);
698
- }
699
- return value.trim();
700
- };
701
- var shouldUseInvokeStore = () => {
702
- const res = getStringFromEnv({
703
- key: AWS_LAMBDA_MAX_CONCURRENCY,
704
- defaultValue: ""
705
- });
706
- return res !== "";
707
- };
708
-
709
- // node_modules/@aws-lambda-powertools/batch/node_modules/@aws/lambda-invoke-store/dist-es/invoke-store.js
710
- var PROTECTED_KEYS2 = {
711
- REQUEST_ID: Symbol.for("_AWS_LAMBDA_REQUEST_ID"),
712
- X_RAY_TRACE_ID: Symbol.for("_AWS_LAMBDA_X_RAY_TRACE_ID"),
713
- TENANT_ID: Symbol.for("_AWS_LAMBDA_TENANT_ID")
714
- };
715
- var NO_GLOBAL_AWS_LAMBDA2 = ["true", "1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA ?? "");
716
- if (!NO_GLOBAL_AWS_LAMBDA2) {
717
- globalThis.awslambda = globalThis.awslambda || {};
718
- }
719
- var InvokeStoreBase2 = class {
720
- static PROTECTED_KEYS = PROTECTED_KEYS2;
721
- isProtectedKey(key) {
722
- return Object.values(PROTECTED_KEYS2).includes(key);
723
- }
724
- getRequestId() {
725
- return this.get(PROTECTED_KEYS2.REQUEST_ID) ?? "-";
726
- }
727
- getXRayTraceId() {
728
- return this.get(PROTECTED_KEYS2.X_RAY_TRACE_ID);
729
- }
730
- getTenantId() {
731
- return this.get(PROTECTED_KEYS2.TENANT_ID);
732
- }
733
- };
734
- var InvokeStoreSingle2 = class extends InvokeStoreBase2 {
735
- currentContext;
736
- getContext() {
737
- return this.currentContext;
738
- }
739
- hasContext() {
740
- return this.currentContext !== void 0;
741
- }
742
- get(key) {
743
- return this.currentContext?.[key];
744
- }
745
- set(key, value) {
746
- if (this.isProtectedKey(key)) {
747
- throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`);
748
- }
749
- this.currentContext = this.currentContext || {};
750
- this.currentContext[key] = value;
751
- }
752
- run(context, fn) {
753
- this.currentContext = context;
754
- return fn();
755
- }
756
- };
757
- var InvokeStoreMulti2 = class _InvokeStoreMulti extends InvokeStoreBase2 {
758
- als;
759
- static async create() {
760
- const instance = new _InvokeStoreMulti();
761
- const asyncHooks = await import("node:async_hooks");
762
- instance.als = new asyncHooks.AsyncLocalStorage();
763
- return instance;
764
- }
765
- getContext() {
766
- return this.als.getStore();
767
- }
768
- hasContext() {
769
- return this.als.getStore() !== void 0;
770
- }
771
- get(key) {
772
- return this.als.getStore()?.[key];
773
- }
774
- set(key, value) {
775
- if (this.isProtectedKey(key)) {
776
- throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`);
777
- }
778
- const store = this.als.getStore();
779
- if (!store) {
780
- throw new Error("No context available");
781
- }
782
- store[key] = value;
783
- }
784
- run(context, fn) {
785
- return this.als.run(context, fn);
786
- }
787
- };
788
- var InvokeStore2;
789
- (function(InvokeStore3) {
790
- let instance = null;
791
- async function getInstanceAsync() {
792
- if (!instance) {
793
- instance = (async () => {
794
- const isMulti = "AWS_LAMBDA_MAX_CONCURRENCY" in process.env;
795
- const newInstance = isMulti ? await InvokeStoreMulti2.create() : new InvokeStoreSingle2();
796
- if (!NO_GLOBAL_AWS_LAMBDA2 && globalThis.awslambda?.InvokeStore) {
797
- return globalThis.awslambda.InvokeStore;
798
- } else if (!NO_GLOBAL_AWS_LAMBDA2 && globalThis.awslambda) {
799
- globalThis.awslambda.InvokeStore = newInstance;
800
- return newInstance;
801
- } else {
802
- return newInstance;
803
- }
804
- })();
805
- }
806
- return instance;
807
- }
808
- InvokeStore3.getInstanceAsync = getInstanceAsync;
809
- InvokeStore3._testing = process.env.AWS_LAMBDA_BENCHMARK_MODE === "1" ? {
810
- reset: () => {
811
- instance = null;
812
- if (globalThis.awslambda?.InvokeStore) {
813
- delete globalThis.awslambda.InvokeStore;
814
- }
815
- globalThis.awslambda = { InvokeStore: void 0 };
816
- }
817
- } : void 0;
818
- })(InvokeStore2 || (InvokeStore2 = {}));
819
-
820
- // node_modules/@aws-lambda-powertools/batch/lib/esm/BatchProcessingStore.js
821
- var BatchProcessingStore = class {
822
- #recordsKey = Symbol("powertools.batch.records");
823
- #handlerKey = Symbol("powertools.batch.handler");
824
- #optionsKey = Symbol("powertools.batch.options");
825
- #failureMessagesKey = Symbol("powertools.batch.failureMessages");
826
- #successMessagesKey = Symbol("powertools.batch.successMessages");
827
- #batchResponseKey = Symbol("powertools.batch.batchResponse");
828
- #errorsKey = Symbol("powertools.batch.errors");
829
- #fallbackRecords = [];
830
- #fallbackHandler = () => {
831
- };
832
- #fallbackOptions;
833
- #fallbackFailureMessages = [];
834
- #fallbackSuccessMessages = [];
835
- #fallbackBatchResponse = {
836
- batchItemFailures: []
837
- };
838
- #fallbackErrors = [];
839
- getRecords() {
840
- if (!shouldUseInvokeStore()) {
841
- return this.#fallbackRecords;
842
- }
843
- if (globalThis.awslambda?.InvokeStore === void 0) {
844
- throw new Error("InvokeStore is not available");
845
- }
846
- const store = globalThis.awslambda.InvokeStore;
847
- return store.get(this.#recordsKey) ?? [];
848
- }
849
- setRecords(records) {
850
- if (!shouldUseInvokeStore()) {
851
- this.#fallbackRecords = records;
852
- return;
853
- }
854
- if (globalThis.awslambda?.InvokeStore === void 0) {
855
- throw new Error("InvokeStore is not available");
856
- }
857
- const store = globalThis.awslambda.InvokeStore;
858
- store.set(this.#recordsKey, records);
859
- }
860
- getHandler() {
861
- if (!shouldUseInvokeStore()) {
862
- return this.#fallbackHandler;
863
- }
864
- return globalThis.awslambda?.InvokeStore?.get(this.#handlerKey) ?? (() => {
865
- });
866
- }
867
- setHandler(handler) {
868
- if (!shouldUseInvokeStore()) {
869
- this.#fallbackHandler = handler;
870
- return;
871
- }
872
- globalThis.awslambda?.InvokeStore?.set(this.#handlerKey, handler);
873
- }
874
- getOptions() {
875
- if (!shouldUseInvokeStore()) {
876
- return this.#fallbackOptions;
877
- }
878
- return globalThis.awslambda?.InvokeStore?.get(this.#optionsKey);
879
- }
880
- setOptions(options) {
881
- if (!shouldUseInvokeStore()) {
882
- this.#fallbackOptions = options;
883
- return;
884
- }
885
- globalThis.awslambda?.InvokeStore?.set(this.#optionsKey, options);
886
- }
887
- getFailureMessages() {
888
- if (!shouldUseInvokeStore()) {
889
- return this.#fallbackFailureMessages;
890
- }
891
- return globalThis.awslambda?.InvokeStore?.get(this.#failureMessagesKey) ?? [];
892
- }
893
- setFailureMessages(messages) {
894
- if (!shouldUseInvokeStore()) {
895
- this.#fallbackFailureMessages = messages;
896
- return;
897
- }
898
- globalThis.awslambda?.InvokeStore?.set(this.#failureMessagesKey, messages);
899
- }
900
- getSuccessMessages() {
901
- if (!shouldUseInvokeStore()) {
902
- return this.#fallbackSuccessMessages;
903
- }
904
- return globalThis.awslambda?.InvokeStore?.get(this.#successMessagesKey) ?? [];
905
- }
906
- setSuccessMessages(messages) {
907
- if (!shouldUseInvokeStore()) {
908
- this.#fallbackSuccessMessages = messages;
909
- return;
910
- }
911
- globalThis.awslambda?.InvokeStore?.set(this.#successMessagesKey, messages);
912
- }
913
- getBatchResponse() {
914
- if (!shouldUseInvokeStore()) {
915
- return this.#fallbackBatchResponse;
916
- }
917
- return globalThis.awslambda?.InvokeStore?.get(this.#batchResponseKey) ?? { batchItemFailures: [] };
918
- }
919
- setBatchResponse(response) {
920
- if (!shouldUseInvokeStore()) {
921
- this.#fallbackBatchResponse = response;
922
- return;
923
- }
924
- globalThis.awslambda?.InvokeStore?.set(this.#batchResponseKey, response);
925
- }
926
- getErrors() {
927
- if (!shouldUseInvokeStore()) {
928
- return this.#fallbackErrors;
929
- }
930
- return globalThis.awslambda?.InvokeStore?.get(this.#errorsKey) ?? [];
931
- }
932
- setErrors(errors) {
933
- if (!shouldUseInvokeStore()) {
934
- this.#fallbackErrors = errors;
935
- return;
936
- }
937
- globalThis.awslambda?.InvokeStore?.set(this.#errorsKey, errors);
938
- }
939
- };
940
-
941
- // node_modules/@aws-lambda-powertools/batch/lib/esm/BasePartialProcessor.js
942
- var BasePartialProcessor = class {
943
- /**
944
- * Store for managing invocation-specific state
945
- */
946
- #store = new BatchProcessingStore();
947
- get errors() {
948
- return this.#store.getErrors();
949
- }
950
- set errors(errors) {
951
- this.#store.setErrors(errors);
952
- }
953
- get failureMessages() {
954
- return this.#store.getFailureMessages();
955
- }
956
- set failureMessages(messages) {
957
- this.#store.setFailureMessages(messages);
958
- }
959
- get handler() {
960
- return this.#store.getHandler();
961
- }
962
- set handler(handler) {
963
- this.#store.setHandler(handler);
964
- }
965
- get options() {
966
- return this.#store.getOptions();
967
- }
968
- set options(options) {
969
- this.#store.setOptions(options);
970
- }
971
- get records() {
972
- return this.#store.getRecords();
973
- }
974
- set records(records) {
975
- this.#store.setRecords(records);
976
- }
977
- get successMessages() {
978
- return this.#store.getSuccessMessages();
979
- }
980
- set successMessages(messages) {
981
- this.#store.setSuccessMessages(messages);
982
- }
983
- get batchResponse() {
984
- return this.#store.getBatchResponse();
985
- }
986
- set batchResponse(response) {
987
- this.#store.setBatchResponse(response);
988
- }
989
- /**
990
- * Method to handle a record that failed processing
991
- *
992
- * This method should be called when a record fails processing so that
993
- * the processor can keep track of the error and the record that failed.
994
- *
995
- * @param record - Record that failed processing
996
- * @param error - Error that was thrown
997
- */
998
- failureHandler(record, error) {
999
- const entry = ["fail", error.message, record];
1000
- this.errors.push(error);
1001
- this.failureMessages.push(record);
1002
- return entry;
1003
- }
1004
- /**
1005
- * Process all records with an asynchronous handler
1006
- *
1007
- * Once called, the processor will create an array of promises to process each record
1008
- * and wait for all of them to settle before returning the results.
1009
- *
1010
- * Before and after processing, the processor will call the prepare and clean methods respectively.
1011
- */
1012
- async process() {
1013
- this.prepare();
1014
- const processInParallel = this.options?.processInParallel ?? true;
1015
- const processedRecords = processInParallel ? await this.#processRecordsInParallel() : await this.#processRecordsSequentially();
1016
- this.clean();
1017
- return processedRecords;
1018
- }
1019
- /**
1020
- * Orchestrate the processing of a batch of records synchronously
1021
- * and sequentially.
1022
- *
1023
- * The method is responsible for calling the prepare method before
1024
- * processing the records and the clean method after processing the records.
1025
- *
1026
- * In the middle, the method will iterate over the records and call the
1027
- * processRecordSync method for each record.
1028
- *
1029
- * @returns List of processed records
1030
- */
1031
- processSync() {
1032
- if (this.constructor.name === "BatchProcessor") {
1033
- this.processRecordSync(this.records[0]);
1034
- }
1035
- this.prepare();
1036
- const processedRecords = [];
1037
- for (const record of this.records) {
1038
- processedRecords.push(this.processRecordSync(record));
1039
- }
1040
- this.clean();
1041
- return processedRecords;
1042
- }
1043
- /**
1044
- * Set up the processor with the records and the handler
1045
- *
1046
- * This method should be called before processing the records to
1047
- * bind the records and the handler for a specific invocation to
1048
- * the processor.
1049
- *
1050
- * We use a separate method to do this rather than the constructor
1051
- * to allow for reusing the processor instance across multiple invocations
1052
- * by instantiating the processor outside the Lambda function handler.
1053
- *
1054
- * @param records - Array of records to be processed
1055
- * @param handler - CallableFunction to process each record from the batch
1056
- * @param options - Options to be used during processing (optional)
1057
- */
1058
- register(records, handler, options) {
1059
- this.records = records;
1060
- this.handler = handler;
1061
- if (options) {
1062
- this.options = options;
1063
- }
1064
- return this;
1065
- }
1066
- /**
1067
- * Method to handle a record that succeeded processing
1068
- *
1069
- * This method should be called when a record succeeds processing so that
1070
- * the processor can keep track of the result and the record that succeeded.
1071
- *
1072
- * @param record - Record that succeeded processing
1073
- * @param result - Result from record handler
1074
- */
1075
- successHandler(record, result) {
1076
- const entry = ["success", result, record];
1077
- this.successMessages.push(record);
1078
- return entry;
1079
- }
1080
- /**
1081
- * Processes records in parallel using `Promise.all`.
1082
- */
1083
- #processRecordsInParallel() {
1084
- return Promise.all(this.records.map((record) => this.processRecord(record)));
1085
- }
1086
- /**
1087
- * Processes records sequentially, ensuring that each record is processed one after the other.
1088
- */
1089
- async #processRecordsSequentially() {
1090
- const processedRecords = [];
1091
- for (const record of this.records) {
1092
- processedRecords.push(await this.processRecord(record));
1093
- }
1094
- return processedRecords;
1095
- }
1096
- };
1097
-
1098
- // node_modules/@aws-lambda-powertools/batch/lib/esm/constants.js
1099
- var EventType = {
1100
- SQS: "SQS",
1101
- KinesisDataStreams: "KinesisDataStreams",
1102
- DynamoDBStreams: "DynamoDBStreams"
1103
- };
1104
- var DEFAULT_RESPONSE = {
1105
- batchItemFailures: []
1106
- };
1107
- var DATA_CLASS_MAPPING = {
1108
- [EventType.SQS]: (record) => record,
1109
- [EventType.KinesisDataStreams]: (record) => record,
1110
- [EventType.DynamoDBStreams]: (record) => record
1111
- };
1112
-
1113
- // node_modules/@aws-lambda-powertools/batch/lib/esm/errors.js
1114
- var BatchProcessingError = class extends Error {
1115
- constructor(message) {
1116
- super(message);
1117
- this.name = "BatchProcessingError";
1118
- }
1119
- };
1120
- var FullBatchFailureError = class extends BatchProcessingError {
1121
- recordErrors;
1122
- constructor(childErrors) {
1123
- super("All records failed processing. See individual errors below.");
1124
- this.recordErrors = childErrors;
1125
- this.name = "FullBatchFailureError";
1126
- }
1127
- };
1128
- var UnexpectedBatchTypeError = class extends BatchProcessingError {
1129
- constructor() {
1130
- super(`Unexpected batch type. Possible values are: ${Object.values(EventType).join(", ")}`);
1131
- this.name = "UnexpectedBatchTypeError";
1132
- }
1133
- };
1134
-
1135
- // node_modules/@aws-lambda-powertools/batch/lib/esm/BasePartialBatchProcessor.js
1136
- var BasePartialBatchProcessor = class extends BasePartialProcessor {
1137
- /**
1138
- * Mapping of event types to their respective failure collectors
1139
- *
1140
- * Each service expects a different format for partial failure reporting,
1141
- * this mapping ensures that the correct format is used for each event type.
1142
- */
1143
- COLLECTOR_MAPPING;
1144
- /**
1145
- * Type of event that the processor is handling
1146
- */
1147
- eventType;
1148
- /**
1149
- * A logger instance to be used for logging debug, warning, and error messages.
1150
- *
1151
- * When no logger is provided, we'll only log warnings and errors using the global `console` object.
1152
- */
1153
- logger;
1154
- /**
1155
- * The configuration options for the parser integration
1156
- */
1157
- parserConfig;
1158
- /**
1159
- * Initializes base batch processing class
1160
- *
1161
- * @param eventType The type of event to process (SQS, Kinesis, DynamoDB)
1162
- */
1163
- constructor(eventType, parserConfig) {
1164
- super();
1165
- this.eventType = eventType;
1166
- this.batchResponse = DEFAULT_RESPONSE;
1167
- this.COLLECTOR_MAPPING = {
1168
- [EventType.SQS]: () => this.collectSqsFailures(),
1169
- [EventType.KinesisDataStreams]: () => this.collectKinesisFailures(),
1170
- [EventType.DynamoDBStreams]: () => this.collectDynamoDBFailures()
1171
- };
1172
- this.parserConfig = parserConfig;
1173
- const alcLogLevel = getStringFromEnv({
1174
- key: "AWS_LAMBDA_LOG_LEVEL",
1175
- defaultValue: ""
1176
- });
1177
- this.logger = parserConfig?.logger ?? {
1178
- debug: alcLogLevel === "DEBUG" ? console.debug : () => void 0,
1179
- error: console.error,
1180
- warn: console.warn
1181
- };
1182
- }
1183
- /**
1184
- * Clean up logic to be run after processing a batch
1185
- *
1186
- * If the entire batch failed this method will throw a {@link FullBatchFailureError | `FullBatchFailureError`} with the list of
1187
- * errors that occurred during processing, unless the `throwOnFullBatchFailure` option is set to `false`.
1188
- *
1189
- * Otherwise, it will build the partial failure response based on the event type.
1190
- */
1191
- clean() {
1192
- if (!this.hasMessagesToReport()) {
1193
- return;
1194
- }
1195
- if (this.options?.throwOnFullBatchFailure !== false && this.entireBatchFailed()) {
1196
- throw new FullBatchFailureError(this.errors);
1197
- }
1198
- const messages = this.getMessagesToReport();
1199
- this.batchResponse = { batchItemFailures: messages };
1200
- }
1201
- /**
1202
- * Collect the identifiers of failed items for a DynamoDB stream
1203
- *
1204
- * The failures are collected based on the sequence number of the record
1205
- * and formatted as a list of objects with the key `itemIdentifier` as
1206
- * expected by the service.
1207
- */
1208
- collectDynamoDBFailures() {
1209
- const failures = [];
1210
- for (const msg of this.failureMessages) {
1211
- const msgId = msg.dynamodb?.SequenceNumber;
1212
- if (msgId) {
1213
- failures.push({ itemIdentifier: msgId });
1214
- }
1215
- }
1216
- return failures;
1217
- }
1218
- /**
1219
- * Collect identifiers of failed items for a Kinesis batch
1220
- *
1221
- * The failures are collected based on the sequence number of the record
1222
- * and formatted as a list of objects with the key `itemIdentifier` as
1223
- * expected by the service.
1224
- */
1225
- collectKinesisFailures() {
1226
- const failures = [];
1227
- for (const msg of this.failureMessages) {
1228
- const msgId = msg.kinesis.sequenceNumber;
1229
- failures.push({ itemIdentifier: msgId });
1230
- }
1231
- return failures;
1232
- }
1233
- /**
1234
- * Collect identifiers of failed items for an SQS batch
1235
- *
1236
- * The failures are collected based on the message ID of the record
1237
- * and formatted as a list of objects with the key `itemIdentifier` as
1238
- * expected by the service.
1239
- */
1240
- collectSqsFailures() {
1241
- const failures = [];
1242
- for (const msg of this.failureMessages) {
1243
- const msgId = msg.messageId;
1244
- failures.push({ itemIdentifier: msgId });
1245
- }
1246
- return failures;
1247
- }
1248
- /**
1249
- * Determine if the entire batch failed
1250
- *
1251
- * If the number of errors is equal to the number of records, then the
1252
- * entire batch failed and this method will return `true`.
1253
- */
1254
- entireBatchFailed() {
1255
- return this.errors.length === this.records.length;
1256
- }
1257
- /**
1258
- * Collect identifiers for failed batch items
1259
- *
1260
- * The method will call the appropriate collector based on the event type
1261
- * and return the list of failed items.
1262
- */
1263
- getMessagesToReport() {
1264
- return this.COLLECTOR_MAPPING[this.eventType]();
1265
- }
1266
- /**
1267
- * Determine if there are any failed records to report
1268
- *
1269
- * If there are no failed records, then the batch was successful
1270
- * and this method will return `false`.
1271
- */
1272
- hasMessagesToReport() {
1273
- return this.failureMessages.length !== 0;
1274
- }
1275
- /**
1276
- * Set up the processor with the initial state ready for processing
1277
- */
1278
- prepare() {
1279
- this.successMessages = [];
1280
- this.failureMessages = [];
1281
- this.errors = [];
1282
- this.batchResponse = DEFAULT_RESPONSE;
1283
- }
1284
- /**
1285
- * Get the response from the batch processing
1286
- */
1287
- response() {
1288
- return this.batchResponse;
1289
- }
1290
- /**
1291
- * Forward a record to the appropriate batch type
1292
- *
1293
- * Based on the event type that the processor was initialized with, this method
1294
- * will cast the record to the appropriate batch type handler.
1295
- *
1296
- * @param record The record to be processed
1297
- * @param eventType The type of event to process
1298
- */
1299
- toBatchType(record, eventType) {
1300
- return DATA_CLASS_MAPPING[eventType](record);
1301
- }
1302
- };
1303
-
1304
- // node_modules/@aws-lambda-powertools/batch/lib/esm/BatchProcessor.js
1305
- var BatchProcessor = class extends BasePartialBatchProcessor {
1306
- /**
1307
- * Handle a record asynchronously with the instance handler provided.
1308
- *
1309
- * This method implements the abstract method from the parent class,
1310
- * and orchestrates the processing of a single record.
1311
- *
1312
- * First, it converts the record to the appropriate type for the batch processor.
1313
- * Then, it calls the handler function with the record data and context.
1314
- *
1315
- * If the handler function completes successfully, the method returns a success response.
1316
- * Otherwise, it returns a failure response with the error that occurred during processing.
1317
- *
1318
- * @param record - The record to be processed
1319
- */
1320
- async processRecord(record) {
1321
- try {
1322
- const recordToProcess = this.parserConfig?.parser ? await this.parserConfig.parser(record, this.eventType, this.logger, this.parserConfig) : record;
1323
- const data = this.toBatchType(recordToProcess, this.eventType);
1324
- const result = await this.handler(data, this.options?.context);
1325
- return this.successHandler(record, result);
1326
- } catch (error) {
1327
- return this.failureHandler(record, error);
1328
- }
1329
- }
1330
- /**
1331
- * @throws {BatchProcessingError} This method is not implemented for synchronous processing.
1332
- *
1333
- * @param _record - The record to be processed
1334
- */
1335
- processRecordSync(_record) {
1336
- throw new BatchProcessingError("Not implemented. Use asyncProcess() instead.");
1337
- }
1338
- };
1339
-
1340
- // node_modules/@aws-lambda-powertools/batch/lib/esm/processPartialResponse.js
1341
- var processPartialResponse = async (event, recordHandler, processor, options) => {
1342
- if (!event.Records || !Array.isArray(event.Records)) {
1343
- throw new UnexpectedBatchTypeError();
1344
- }
1345
- processor.register(event.Records, recordHandler, options);
1346
- await processor.process();
1347
- return processor.response();
1348
- };
1349
-
1350
- // src/lambda/index.ts
1351
- import { IdempotencyConfig } from "@aws-lambda-powertools/idempotency";
1352
- import { DynamoDBPersistenceLayer } from "@aws-lambda-powertools/idempotency/dynamodb";
1353
- import { Logger as Logger2 } from "@aws-lambda-powertools/logger";
1354
- import { injectLambdaContext } from "@aws-lambda-powertools/logger/middleware";
1355
- import { Metrics, MetricUnit } from "@aws-lambda-powertools/metrics";
1356
- import { logMetrics } from "@aws-lambda-powertools/metrics/middleware";
1357
- import { Tracer } from "@aws-lambda-powertools/tracer";
1358
- import { captureLambdaHandler } from "@aws-lambda-powertools/tracer/middleware";
1359
-
1360
- // node_modules/@middy/core/index.js
1361
- import { Readable } from "node:stream";
1362
- import { pipeline } from "node:stream/promises";
1363
- import { setTimeout as setTimeout2 } from "node:timers/promises";
1364
- var defaultLambdaHandler = () => {
1365
- };
1366
- var defaultPlugin = {
1367
- timeoutEarlyInMillis: 5,
1368
- timeoutEarlyResponse: () => {
1369
- throw new Error("Timeout");
1370
- },
1371
- streamifyResponse: false
1372
- // Deprecate need for this when AWS provides a flag for when it's looking for it
1373
- };
1374
- var middy = (lambdaHandler = defaultLambdaHandler, plugin = {}) => {
1375
- if (typeof lambdaHandler !== "function") {
1376
- plugin = lambdaHandler;
1377
- lambdaHandler = defaultLambdaHandler;
1378
- }
1379
- plugin = {
1380
- ...defaultPlugin,
1381
- ...plugin
1382
- };
1383
- plugin.timeoutEarly = plugin.timeoutEarlyInMillis > 0;
1384
- plugin.beforePrefetch?.();
1385
- const beforeMiddlewares = [];
1386
- const afterMiddlewares = [];
1387
- const onErrorMiddlewares = [];
1388
- const middyHandler = (event = {}, context = {}) => {
1389
- plugin.requestStart?.();
1390
- const request = {
1391
- event,
1392
- context,
1393
- response: void 0,
1394
- error: void 0,
1395
- internal: plugin.internal ?? {}
1396
- };
1397
- return runRequest(request, [
1398
- ...beforeMiddlewares
1399
- ], lambdaHandler, [
1400
- ...afterMiddlewares
1401
- ], [
1402
- ...onErrorMiddlewares
1403
- ], plugin);
1404
- };
1405
- const middy2 = plugin.streamifyResponse ? awslambda.streamifyResponse(async (event, responseStream, context) => {
1406
- const handlerResponse = await middyHandler(event, context);
1407
- let handlerBody = handlerResponse;
1408
- if (handlerResponse.statusCode) {
1409
- handlerBody = handlerResponse.body ?? "";
1410
- responseStream = awslambda.HttpResponseStream.from(responseStream, handlerResponse);
1411
- }
1412
- let handlerStream;
1413
- if (handlerBody._readableState) {
1414
- handlerStream = handlerBody;
1415
- } else if (typeof handlerBody === "string") {
1416
- function* iterator(input) {
1417
- const size = 16384;
1418
- let position = 0;
1419
- const length = input.length;
1420
- while (position < length) {
1421
- yield input.substring(position, position + size);
1422
- position += size;
1423
- }
1424
- }
1425
- handlerStream = Readable.from(iterator(handlerBody));
1426
- }
1427
- if (!handlerStream) {
1428
- throw new Error("handler response not a ReadableStream");
1429
- }
1430
- await pipeline(handlerStream, responseStream);
1431
- }) : middyHandler;
1432
- middy2.use = (middlewares) => {
1433
- if (!Array.isArray(middlewares)) {
1434
- middlewares = [
1435
- middlewares
1436
- ];
1437
- }
1438
- for (const middleware of middlewares) {
1439
- const { before, after, onError } = middleware;
1440
- if (!before && !after && !onError) {
1441
- throw new Error('Middleware must be an object containing at least one key among "before", "after", "onError"');
1442
- }
1443
- if (before)
1444
- middy2.before(before);
1445
- if (after)
1446
- middy2.after(after);
1447
- if (onError)
1448
- middy2.onError(onError);
1449
- }
1450
- return middy2;
1451
- };
1452
- middy2.before = (beforeMiddleware) => {
1453
- beforeMiddlewares.push(beforeMiddleware);
1454
- return middy2;
1455
- };
1456
- middy2.after = (afterMiddleware) => {
1457
- afterMiddlewares.unshift(afterMiddleware);
1458
- return middy2;
1459
- };
1460
- middy2.onError = (onErrorMiddleware) => {
1461
- onErrorMiddlewares.unshift(onErrorMiddleware);
1462
- return middy2;
1463
- };
1464
- middy2.handler = (replaceLambdaHandler) => {
1465
- lambdaHandler = replaceLambdaHandler;
1466
- return middy2;
1467
- };
1468
- return middy2;
1469
- };
1470
- var runRequest = async (request, beforeMiddlewares, lambdaHandler, afterMiddlewares, onErrorMiddlewares, plugin) => {
1471
- let timeoutAbort;
1472
- const timeoutEarly = plugin.timeoutEarly && request.context.getRemainingTimeInMillis;
1473
- try {
1474
- await runMiddlewares(request, beforeMiddlewares, plugin);
1475
- if (typeof request.response === "undefined") {
1476
- plugin.beforeHandler?.();
1477
- const handlerAbort = new AbortController();
1478
- if (timeoutEarly)
1479
- timeoutAbort = new AbortController();
1480
- request.response = await Promise.race([
1481
- lambdaHandler(request.event, request.context, {
1482
- signal: handlerAbort.signal
1483
- }),
1484
- timeoutEarly ? setTimeout2(request.context.getRemainingTimeInMillis() - plugin.timeoutEarlyInMillis, void 0, {
1485
- signal: timeoutAbort.signal
1486
- }).then(() => {
1487
- handlerAbort.abort();
1488
- return plugin.timeoutEarlyResponse();
1489
- }) : Promise.race([])
1490
- ]);
1491
- timeoutAbort?.abort();
1492
- plugin.afterHandler?.();
1493
- await runMiddlewares(request, afterMiddlewares, plugin);
1494
- }
1495
- } catch (e) {
1496
- timeoutAbort?.abort();
1497
- request.response = void 0;
1498
- request.error = e;
1499
- try {
1500
- await runMiddlewares(request, onErrorMiddlewares, plugin);
1501
- } catch (e2) {
1502
- e2.originalError = request.error;
1503
- request.error = e2;
1504
- throw request.error;
1505
- }
1506
- if (typeof request.response === "undefined")
1507
- throw request.error;
1508
- } finally {
1509
- await plugin.requestEnd?.(request);
1510
- }
1511
- return request.response;
1512
- };
1513
- var runMiddlewares = async (request, middlewares, plugin) => {
1514
- for (const nextMiddleware of middlewares) {
1515
- plugin.beforeMiddleware?.(nextMiddleware.name);
1516
- const res = await nextMiddleware(request);
1517
- plugin.afterMiddleware?.(nextMiddleware.name);
1518
- if (typeof res !== "undefined") {
1519
- request.response = res;
1520
- return;
1521
- }
1522
- }
1523
- };
1524
- var core_default = middy;
1525
-
1526
- // node_modules/@middy/util/index.js
1527
- var jsonSafeParse = (text, reviver) => {
1528
- if (typeof text !== "string")
1529
- return text;
1530
- const firstChar = text[0];
1531
- if (firstChar !== "{" && firstChar !== "[" && firstChar !== '"')
1532
- return text;
1533
- try {
1534
- return JSON.parse(text, reviver);
1535
- } catch (_e) {
1536
- }
1537
- return text;
1538
- };
1539
- var normalizeHttpResponse = (request) => {
1540
- let { response } = request;
1541
- if (typeof response === "undefined") {
1542
- response = {};
1543
- } else if (typeof response?.statusCode === "undefined" && typeof response?.body === "undefined" && typeof response?.headers === "undefined") {
1544
- response = { statusCode: 200, body: response };
1545
- }
1546
- response.statusCode ??= 500;
1547
- response.headers ??= {};
1548
- request.response = response;
1549
- return response;
1550
- };
1551
-
1552
- // node_modules/@middy/http-error-handler/index.js
1553
- var defaults = {
1554
- logger: console.error,
1555
- // TODO v7 change to pass in request
1556
- fallbackMessage: void 0
1557
- };
1558
- var httpErrorHandlerMiddleware = (opts = {}) => {
1559
- const options = { ...defaults, ...opts };
1560
- const httpErrorHandlerMiddlewareOnError = async (request) => {
1561
- if (request.response !== void 0)
1562
- return;
1563
- if (typeof options.logger === "function") {
1564
- options.logger(request.error);
1565
- }
1566
- if (request.error.statusCode && request.error.expose === void 0) {
1567
- request.error.expose = request.error.statusCode < 500;
1568
- }
1569
- if (!request.error.expose || !request.error.statusCode) {
1570
- request.error = {
1571
- statusCode: 500,
1572
- message: options.fallbackMessage,
1573
- expose: true
1574
- };
1575
- }
1576
- if (request.error.expose) {
1577
- normalizeHttpResponse(request);
1578
- const { statusCode, message, headers } = request.error;
1579
- request.response = {
1580
- ...request.response,
1581
- statusCode,
1582
- headers: {
1583
- ...request.response.headers,
1584
- ...headers
1585
- }
1586
- };
1587
- if (message) {
1588
- const headerContentType = typeof jsonSafeParse(message) === "string" ? "text/plain" : "application/json";
1589
- request.response.body = message;
1590
- request.response.headers["Content-Type"] = headerContentType;
1591
- }
1592
- }
1593
- };
1594
- return {
1595
- onError: httpErrorHandlerMiddlewareOnError
1596
- };
1597
- };
1598
- var http_error_handler_default = httpErrorHandlerMiddleware;
1599
-
1600
- // src/lambda/index.ts
1601
- import { randomUUID } from "node:crypto";
1602
- import { MetricUnit as MetricUnit2 } from "@aws-lambda-powertools/metrics";
1603
- import { makeIdempotent } from "@aws-lambda-powertools/idempotency";
1604
- var logger = new Logger2();
1605
- var tracer = new Tracer();
1606
- var metrics = new Metrics({ namespace: "aspan-corporation" });
1607
- var withMiddlewares = (handler) => core_default(handler).use(injectLambdaContext(logger)).use(captureLambdaHandler(tracer)).use(logMetrics(metrics, { captureColdStartMetric: true })).use({
1608
- before: async (request) => {
1609
- if (!logger.getCorrelationId()) {
1610
- logger.setCorrelationId(request.context.awsRequestId || randomUUID());
1611
- }
1612
- logger.logEventIfEnabled(request.event);
1613
- request.context.logger = logger;
1614
- request.context.tracer = tracer;
1615
- request.context.metrics = metrics;
1616
- }
1617
- }).use({
1618
- onError: async ({ error, context: { logger: logger2, metrics: metrics2 } }) => {
1619
- logger2.error("Error handled by middleware", {
1620
- error
1621
- });
1622
- metrics2.addMetric("ErrorHandled", MetricUnit.Count, 1);
1623
- }
1624
- }).use(http_error_handler_default());
1625
- var getPersistenceStore = (tableName) => {
1626
- return new DynamoDBPersistenceLayer({
1627
- tableName
1628
- });
1629
- };
1630
- var getIdempotencyConfig = (eventKeyJmesPath) => {
1631
- return new IdempotencyConfig({
1632
- eventKeyJmesPath
1633
- });
1634
- };
1635
- var getIdempotencyOptions = (tableName, path) => ({
1636
- persistenceStore: getPersistenceStore(tableName),
1637
- config: getIdempotencyConfig(path)
1638
- });
1639
- var getPartialResponseHandler = (handler) => {
1640
- const processor = new BatchProcessor(EventType.SQS);
1641
- return async (event, context) => processPartialResponse(event, handler, processor, {
1642
- context
1643
- });
1644
- };
1645
- export {
1646
- ALLOWED_EXTENSIONS,
1647
- ALLOWED_VIDEO_EXTENSIONS,
1648
- CloudWatchService,
1649
- DynamoDBService,
1650
- ENCODED_VIDEO_EXTENSION,
1651
- HEIC_EXTENSION,
1652
- JPEG_EXTENSION,
1653
- JPG_EXTENSION,
1654
- LocationService,
1655
- MOV_EXTENSION,
1656
- MetricUnit2 as MetricUnit,
1657
- S3Service,
1658
- SQSService,
1659
- SSMService,
1660
- STSService,
1661
- THUMBNAIL_RESOLUTIONS,
1662
- THUMBS_EXTENSION,
1663
- assertEnvVar,
1664
- getEncodedVideoKey,
1665
- getIdempotencyConfig,
1666
- getIdempotencyOptions,
1667
- getKeyExtension,
1668
- getObjectWithAssumeRoleCommandOutputAttribute,
1669
- getObjectWithStackAttribute,
1670
- getPartialResponseHandler,
1671
- getPersistenceStore,
1672
- getThumbsKey,
1673
- isAllowedExtension,
1674
- isAllowedVideoExtension,
1675
- logger,
1676
- makeIdempotent,
1677
- metrics,
1678
- normalizeErrorMessage,
1679
- processMeta,
1680
- tracer,
1681
- withMiddlewares
1682
- };
1683
- /*! Bundled license information:
1684
-
1685
- @aws-lambda-powertools/batch/lib/esm/BasePartialBatchProcessor.js:
1686
- (* v8 ignore else -- @preserve *)
1687
-
1688
- @aws-lambda-powertools/batch/lib/esm/BatchProcessorSync.js:
1689
- (* v8 ignore next -- @preserve *)
1690
-
1691
- @aws-lambda-powertools/batch/lib/esm/processPartialResponseSync.js:
1692
- (* v8 ignore next -- @preserve *)
1693
- */
1694
- //# sourceMappingURL=index.js.map
1
+ export * from "./services/index.js";
2
+ export * from "./lambda/index.js";
3
+ export * from "./utils/index.js";