Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 3 additions & 6 deletions examples/app/functions/commons/powertools/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@
* We have single entry point for all the powertools modules so that functions that need only one
* can bundle only that one that they need and keep the bundle size small.
*/
import { logger } from './logger.js';
import { metrics } from './metrics.js';
import { tracer } from './tracer.js';

// We export all three modules for those functions who need to use all of them
export { logger, metrics, tracer };
export { logger } from './logger.js';
export { metrics } from './metrics.js';
export { tracer } from './tracer.js';
10 changes: 5 additions & 5 deletions layers/src/layer-publisher-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,12 +122,12 @@ export class LayerPublisherStack extends Stack {

if (buildFromLocal) {
for (const util of utilities) {
// Build latest version of the package
buildCommands.push(`npm run build -w packages/${util}`);
// Pack the package to a .tgz file
buildCommands.push(`npm pack -w packages/${util}`);
// Move the .tgz file to the tmp folder
buildCommands.push(
// Build latest version of the package
`npm run build -w packages/${util}`,
// Pack the package to a .tgz file
`npm pack -w packages/${util}`,
// Move the .tgz file to the tmp folder
`mv aws-lambda-powertools-${util}-*.tgz ${tmpBuildDir}`
);
}
Expand Down
2 changes: 1 addition & 1 deletion layers/tests/e2e/layerPublisher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ describe('Layers E2E tests', () => {
await testStack.deploy();

// Invoke the lambda function once for each output format and collect the logs
for await (const outputFormat of cases) {
for (const outputFormat of cases) {
invocationLogsMap.set(
outputFormat,
await invokeFunctionOnce({
Expand Down
2 changes: 1 addition & 1 deletion packages/commons/src/unmarshallDynamoDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const typeHandlers: Record<string, (value: any) => unknown> = {
B: (value) => value,
BS: (value) => new Set(value),
SS: (value) => new Set(value),
BOOL: (value) => Boolean(value),
BOOL: Boolean,
N: (value) => convertNumber(value),
NS: (value) => new Set((value as Array<string>).map(convertNumber)),
L: (value) => (value as Array<AttributeValue>).map(convertAttributeValue),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,11 @@ class RouteHandlerRegistry {
* @param path - The path to be converted to a regex string
*/
static pathToRegexString(path: string): string {
const escapedPath = path.replace(/([.*+?^=!:${}()|[\]/\\])/g, '\\$1');
return `^${escapedPath.replace(/\\\*/g, '.*')}$`;
const escapedPath = path.replace(
/([.*+?^=!:${}()|[\]/\\])/g,
String.raw`\$1`
);
return `^${escapedPath.replaceAll('\\*', '.*')}$`;
}
}

Expand Down
55 changes: 27 additions & 28 deletions packages/event-handler/tests/helpers/factories.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,32 @@
const onPublishEventFactory = (
events: Array<{ payload: unknown; id: string }> = [
{
payload: {
event_1: 'data_1',
},
id: '5f7dfbd1-b8ff-4c20-924e-23b42db467a0',
const defaultChannel = {
path: '/request/channel',
segments: ['request', 'channel'],
};

const defaultEvents = [
{
payload: {
event_1: 'data_1',
},
{
payload: {
event_2: 'data_2',
},
id: 'ababdf65-a3e6-4c1d-acd3-87466eab433c',
id: '5f7dfbd1-b8ff-4c20-924e-23b42db467a0',
},
{
payload: {
event_2: 'data_2',
},
{
payload: {
event_3: 'data_3',
},
id: '8bb2983a-0967-45a0-8243-0aeb8c83d80e',
id: 'ababdf65-a3e6-4c1d-acd3-87466eab433c',
},
{
payload: {
event_3: 'data_3',
},
],
channel = {
path: '/request/channel',
segments: ['request', 'channel'],
}
id: '8bb2983a-0967-45a0-8243-0aeb8c83d80e',
},
];

const onPublishEventFactory = (
events: Array<{ payload: unknown; id: string }> = defaultEvents,
channel = defaultChannel
) => ({
identity: null,
result: null,
Expand All @@ -46,12 +50,7 @@ const onPublishEventFactory = (
events,
});

const onSubscribeEventFactory = (
channel = {
path: '/request/channel',
segments: ['request', 'channel'],
}
) => ({
const onSubscribeEventFactory = (channel = defaultChannel) => ({
identity: null,
result: null,
request: {
Expand Down
10 changes: 4 additions & 6 deletions packages/idempotency/src/makeIdempotent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ function makeIdempotent<Func extends AnyFunction>(
options: ItempotentFunctionOptions<Parameters<Func>>
): (...args: Parameters<Func>) => ReturnType<Func> {
const { persistenceStore, config, keyPrefix } = options;
const idempotencyConfig = config ? config : new IdempotencyConfig({});
const idempotencyConfig = config ?? new IdempotencyConfig({});

if (!idempotencyConfig.isEnabled()) return fn;

Expand All @@ -140,12 +140,10 @@ function makeIdempotent<Func extends AnyFunction>(
args[1]?.lambdaContext || args[1]
);
functionPayloadToBeHashed = args[0];
} else if (isOptionsWithDataIndexArgument(options)) {
functionPayloadToBeHashed = args[options.dataIndexArgument];
} else {
if (isOptionsWithDataIndexArgument(options)) {
functionPayloadToBeHashed = args[options.dataIndexArgument];
} else {
functionPayloadToBeHashed = args[0];
}
functionPayloadToBeHashed = args[0];
}

const isReplay = args[1]?.durableExecutionMode === 'ReplayMode';
Expand Down
4 changes: 1 addition & 3 deletions packages/idempotency/src/middleware/makeHandlerIdempotent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,7 @@ const makeHandlerIdempotent = (
* @param request - The Middy request object
*/
const before = (request: MiddyLikeRequest): unknown => {
const idempotencyConfig = options.config
? options.config
: new IdempotencyConfig({});
const idempotencyConfig = options.config ?? new IdempotencyConfig({});
const persistenceStore = options.persistenceStore;
const keyPrefix = options.keyPrefix;
persistenceStore.configure({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ class DynamoDBPersistenceLayer extends BasePersistenceLayer {

if (this.isPayloadValidationEnabled() && record.payloadHash !== undefined) {
item[this.validationKeyAttr] = {
S: record.payloadHash as string,
S: record.payloadHash,
};
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { setTimeout } from 'node:timers/promises';
import { Logger } from '@aws-lambda-powertools/logger';
import type { Context } from 'aws-lambda';
import { IdempotencyConfig } from '../../src/IdempotencyConfig.js';
Expand Down Expand Up @@ -31,7 +32,8 @@ const logger = new Logger();
*/
const idempotencyConfig = new IdempotencyConfig({});
const processIdempotently = makeIdempotent(
(record: Record<string, unknown>): string => {
async (record: Record<string, unknown>): Promise<string> => {
await setTimeout(0);
logger.info('Got test event', { record });

return `Processing done: ${record.foo}`;
Expand Down Expand Up @@ -62,7 +64,11 @@ const idempotencyConfigWithSelection = new IdempotencyConfig({
payloadValidationJmesPath: 'foo',
});
const processIdempotentlyCustomized = makeIdempotent(
(baz: number, record: Record<string, unknown>): Record<string, unknown> => {
async (
baz: number,
record: Record<string, unknown>
): Promise<Record<string, unknown>> => {
await setTimeout(0);
logger.info('Got test event', { baz, record });

return record;
Expand Down
7 changes: 4 additions & 3 deletions packages/jmespath/src/Functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,8 @@ class Functions {
if (isNumber(arg[0])) {
return Math.max(...(arg as number[]));
}
// local compare function to handle string comparison
return arg.reduce((a, b) => (a > b ? a : b));
// Math.max doesn't work with strings (returns NaN), so we use reduce for lexicographic comparison
return arg.reduce((a, b) => (a > b ? a : b)); // NOSONAR - Math.max only works with numbers
}

/**
Expand Down Expand Up @@ -279,7 +279,8 @@ class Functions {
if (isNumber(arg[0])) {
return Math.min(...arg);
}
return arg.reduce((a, b) => (a < b ? a : b));
// Math.min doesn't work with strings (returns NaN), so we use reduce for lexicographic comparison
return arg.reduce((a, b) => (a < b ? a : b)); // NOSONAR - Math.min only works with numbers
}

/**
Expand Down
13 changes: 5 additions & 8 deletions packages/logger/src/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,9 +253,7 @@ class Logger extends Utility implements LoggerInterface {
public constructor(options: ConstructorOptions = {}) {
super();
const { customConfigService, ...rest } = options;
this.customConfigService = customConfigService
? customConfigService
: undefined;
this.customConfigService = customConfigService;
// all logs are buffered until the logger is initialized
this.setOptions(rest);
this.#isInitialized = true;
Expand Down Expand Up @@ -1098,13 +1096,13 @@ class Logger extends Utility implements LoggerInterface {
* or as the global node console if the `POWERTOOLS_DEV' env variable is set and has truthy value.
*/
private setConsole(): void {
if (!isDevMode()) {
if (isDevMode()) {
this.console = console;
} else {
this.console = new Console({
stdout: process.stdout,
stderr: process.stderr,
});
} else {
this.console = console;
}

/**
Expand Down Expand Up @@ -1159,8 +1157,7 @@ class Logger extends Utility implements LoggerInterface {
defaultValue: '',
});

const logLevelValue =
logLevelVariable !== '' ? logLevelVariable : logLevelVariableAlias;
const logLevelValue = logLevelVariable || logLevelVariableAlias;

if (this.isValidLogLevel(logLevelValue)) {
this.logLevel = LogLevelThreshold[logLevelValue];
Expand Down
4 changes: 2 additions & 2 deletions packages/logger/src/types/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import type {
LogKeys,
} from './logKeys.js';

export type { Environment, LogAttributes } from './logKeys.js';

/**
* Type definition for the log level.
*
Expand Down Expand Up @@ -276,9 +278,7 @@ type LoggerInterface = {
export type {
ConstructorOptions,
CustomJsonReplacerFn,
Environment,
InjectLambdaContextOptions,
LogAttributes,
LogFunction,
LoggerInterface,
LogItemExtraInput,
Expand Down
12 changes: 5 additions & 7 deletions packages/metrics/src/Metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -885,13 +885,13 @@ class Metrics extends Utility implements MetricsInterface {
* @private
*/
private setConsole(): void {
if (!this.#envConfig.devMode) {
if (this.#envConfig.devMode) {
this.console = console;
} else {
this.console = new Console({
stdout: process.stdout,
stderr: process.stderr,
});
} else {
this.console = console;
}
}

Expand All @@ -903,9 +903,7 @@ class Metrics extends Utility implements MetricsInterface {
private setCustomConfigService(
customConfigService?: ConfigServiceInterface
): void {
this.customConfigService = customConfigService
? customConfigService
: undefined;
this.customConfigService = customConfigService;
}

/**
Expand Down Expand Up @@ -976,7 +974,7 @@ class Metrics extends Utility implements MetricsInterface {
*
* @param options - The options to be used
*/
private setOptions(options: MetricsOptions): Metrics {
private setOptions(options: MetricsOptions): this {
const {
customConfigService,
namespace,
Expand Down
2 changes: 1 addition & 1 deletion packages/testing/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const generateTestUniqueName = ({
[
testPrefix,
getRuntimeKey().replace(/[nodejsx]/g, ''),
getArchitectureKey().replace(/_64/g, ''),
getArchitectureKey().replaceAll('_64', ''),
randomUUID().toString().substring(0, 5),
testName,
]
Expand Down
4 changes: 1 addition & 3 deletions packages/tracer/src/Tracer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -851,9 +851,7 @@ class Tracer extends Utility implements TracerInterface {
private setCustomConfigService(
customConfigService?: ConfigServiceInterface
): void {
this.customConfigService = customConfigService
? customConfigService
: undefined;
this.customConfigService = customConfigService;
}

/**
Expand Down
2 changes: 2 additions & 0 deletions sonar-project.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Exclude generated proto files from Sonar analysis
sonar.exclusions=packages/kafka/tests/protos/*.generated.js,packages/kafka/tests/protos/*.generated.d.ts
Loading