npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@kleanjs/core

v0.4.0

Published

The agnostic middleware engine for KleanJS. Built for high performance and strict type safety, it allows developers to write clean, hexagonal business logic while keeping the infrastructure details separate.

Readme

@kleanjs/core

The agnostic middleware engine for KleanJS. Built for high performance and strict type safety, it allows developers to write clean, hexagonal business logic while keeping the infrastructure details separate.

Key Features

  • Zero-Overhead Typing: Use Use<T>() to define input/output contracts. No manual generics needed in your handlers.
  • Agnostic by Design: Works in AWS Lambda, Google Cloud Functions, Azure, or pure Node.js environments.
  • Advanced Validation: Optimized AJV integration with support for both simplified and full error reporting.
  • Hexagonal Ready: Clear separation between data transformation, validation, and business execution.

Installation

npm install @kleanjs/core

Configuration Reference (HandlerConfig)

The middleware function accepts a configuration object that defines the behavior of the request lifecycle.

1. Type Markers: event, result, context

These attributes use the Use<T>() utility to register types for inference. They do not hold values; they only carry type information.

  • event: The raw input event type (e.g., APIGatewayProxyEvent).
  • result: The expected return type of the middleware.
  • context: The infrastructure context (e.g., AWS Context).

2. validators

Defines the schema validation or type contracts for specific parts of the event.

  • If a JSON Schema is provided: The data is validated at runtime using AJV.
  • If Use<T>() is provided: Only type inference is applied (Zero runtime cost).

3. transformers

Functions that extract or normalize data from the raw event before validation.

  • Signature: (event: TEvent, context?: TContext) => any

4. customResponse

A factory function to format the successful output of the handler.

  • Signature: (data: any, context?: TContext) => TResult

5. errorHandler

Intercepts any thrown error. If omitted, the default handler normalizes errors into EventError and rethrows them.

  • Signature: (error: any, context?: TContext) => any

6. ajvError & ajvConfig

  • ajvError: Choose between AJVSimpleError (default, formatted details) or AJVFullError (raw AJV objects).
  • ajvConfig: Native AJV options (e.g., { allErrors: true }).

Technical Interfaces

HandlerConfig

export interface HandlerConfig<
  TEvent = any,
  TResult = any,
  TContext = any,
  TValidators = TSchemaMap
> {
  event?: TInterface<TEvent>;
  result?: TInterface<TResult>;
  context?: TInterface<TContext>;
  validators?: TValidators;
  transformers?: Record<string, (event: TEvent, context?: TContext) => any>;
  ajvConfig?: Options;
  customResponse?: (data: any, context?: TContext) => TResult;
  errorHandler?: (error: any, context?: TContext) => any;
  ajvError?: typeof AJVFullError | typeof AJVSimpleError;
}

Error Classes

KleanJS uses a hierarchical error system where all validation or controlled errors extend EventError.

EventError

export class EventError extends Error {
  public readonly statusCode: number;
  public readonly type: string;
  public readonly details?: any;
}

AJVSimpleError

Standard validation error that transforms AJV's ErrorObject into:

  • field: Clean path (e.g., "user/email").
  • rule: Failed keyword (e.g., "required").
  • message: Human-readable description.

Internal Type Logic

KleanJS leverages advanced TypeScript mapped types to provide an "Invisible" DX.

TCombinedEvent

Merges the original TEvent with the inferred types from TValidators. If a key exists in both, the validated type takes precedence.

export type TCombinedEvent<TEvent, TValidators> = Omit<TEvent, keyof TValidators> &
  TExtract<TValidators>;

TExtract

Recursively resolves types from JSON Schemas, Classes, or Use<T>() contracts.

export type TExtract<V> = {
  [K in keyof V]: V[K] extends TInterface<infer T>
    ? T
    : V[K] extends Constructor<infer T>
      ? T
      : V[K] extends JSONSchemaType<infer T>
        ? T
        : any;
};

Usage Examples

Basic with Type Inference

import { middleware, Use } from "@kleanjs/core";

export const handler = middleware(
  async (event) => {
    // event.body is automatically typed as { id: number }
    return { success: true };
  },
  {
    validators: {
      body: Use<{ id: number }>()
    }
  }
);

Advanced Transformers

const handler = middleware(
  async (event) => event.user,
  {
    transformers: {
      user: (event, context) => ({
        id: event.headers['user-id'],
        region: context.invokedFunctionArn
      })
    },
    validators: {
      user: Use<{ id: string; region: string }>()
    }
  }
);

License

GPLv3