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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@karin-js/core

v1.1.15

Published

The core package of Karin-JS framework, providing the foundation for building decorator-based backend applications with Bun.

Readme

@karin-js/core

The core package of Karin-JS framework, providing the foundation for building decorator-based backend applications with Bun.

Installation

bun add @karin-js/core

Overview

@karin-js/core provides:

  • Decorator-based routing (@Controller, @Get, @Post, etc.)
  • Dependency Injection system with TypeScript decorators
  • Guards for route protection and authorization
  • Pipes for data transformation and validation
  • Interceptors for request/response manipulation
  • Exception Filters for error handling
  • Plugin system for extending functionality
  • HTTP adapter abstraction for multiple runtimes

Quick Start


import { KarinFactory, Controller, Get } from "@karin-js/core";
import { HonoAdapter } from "@karin-js/platform-hono";

@Controller("/")
class AppController {
  @Get()
  hello() {
    return { message: "Hello, Karin!" };
  }
}

const app = await KarinFactory.create(new HonoAdapter(), {
  controllers: [AppController],
});

app.listen(3000);

Core Concepts

Controllers

Controllers handle HTTP requests and define routes:

import { Controller, Get, Post, Put, Delete, Param, Body } from "@karin-js/core";

@Controller("/users")
export class UsersController {
  @Get()
  findAll() {
    return [{ id: 1, name: "Alice" }];
  }

  @Get("/:id")
  findOne(@Param("id") id: string) {
    return { id, name: "Alice" };
  }

  @Post()
  create(@Body() body: any) {
    return { id: 2, ...body };
  }

  @Put("/:id")
  update(@Param("id") id: string, @Body() body: any) {
    return { id, ...body };
  }

  @Delete("/:id")
  remove(@Param("id") id: string) {
    return { deleted: true };
  }
}

Services & Dependency Injection

Services encapsulate business logic and can be injected:

import { Service } from "@karin-js/core";

@Service()
export class UsersService {
  private users = [{ id: 1, name: "Alice" }];

  findAll() {
    return this.users;
  }

  findOne(id: string) {
    return this.users.find(u => u.id === parseInt(id));
  }
}

@Controller("/users")
export class UsersController {
  constructor(private usersService: UsersService) {}

  @Get()
  findAll() {
    return this.usersService.findAll();
  }
}

Guards

Guards control access to routes:

import { CanActivate, ExecutionContext, UnauthorizedException } from "@karin-js/core";

@Service()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const token = request.headers.get("authorization");
    
    if (!token) {
      throw new UnauthorizedException("Missing authorization header");
    }
    
    return true;
  }
}

// Apply to controller
@Controller("/admin")
@UseGuards(AuthGuard)
export class AdminController {
  // All routes protected
}

// Or apply to specific route
@Get("/profile")
@UseGuards(AuthGuard)
getProfile() {
  return { user: "admin" };
}

Pipes

Pipes transform and validate input:

import { PipeTransform, BadRequestException } from "@karin-js/core";

@Service()
export class ParseIntPipe implements PipeTransform {
  transform(value: any) {
    const val = parseInt(value, 10);
    if (isNaN(val)) {
      throw new BadRequestException("Invalid number");
    }
    return val;
  }
}

@Get("/:id")
findOne(@Param("id", ParseIntPipe) id: number) {
  return { id }; // id is now a number
}

Interceptors

Interceptors can modify requests and responses:

import { KarinInterceptor, ExecutionContext, CallHandler } from "@karin-js/core";

@Service()
export class LoggingInterceptor implements KarinInterceptor {
  async intercept(context: ExecutionContext, next: CallHandler) {
    const start = Date.now();
    const result = await next();
    const duration = Date.now() - start;
    
    console.log(`Request took ${duration}ms`);
    return result;
  }
}

@Controller("/users")
@UseInterceptors(LoggingInterceptor)
export class UsersController {
  // All routes will be logged
}

Exception Filters

Filters handle errors and format responses:

import { Catch, ExceptionFilter, ArgumentsHost, HttpException } from "@karin-js/core";

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const request = ctx.getRequest();

    return new Response(
      JSON.stringify({
        statusCode: exception.status,
        message: exception.message,
        timestamp: new Date().toISOString(),
        path: request.url,
      }),
      {
        status: exception.status,
        headers: { "Content-Type": "application/json" },
      }
    );
  }
}

// Register globally
const app = await KarinFactory.create(adapter, {
  scan: "./src/**/*.ts",
  globalFilters: [new HttpExceptionFilter()],
});

Advanced Features

Custom Parameter Decorators

Create your own parameter decorators:

import { createParamDecorator, ExecutionContext } from "@karin-js/core";

export const User = createParamDecorator((data: unknown, ctx: ExecutionContext) => {
  const request = ctx.switchToHttp().getRequest();
  return request.user; // Assuming user is set by a guard
});

@Get("/profile")
getProfile(@User() user: any) {
  return user;
}

Fast Routes

Bypass guards/pipes/interceptors for maximum performance:

import { Fast } from "@karin-js/core";

@Get("/health")
@Fast()
health() {
  return { status: "ok" };
}

Plugin System

Extend the framework with plugins:

import { KarinPlugin, KarinApplication } from "@karin-js/core";

export class MyPlugin implements KarinPlugin {
  name = "MyPlugin";

  install(app: KarinApplication) {
    // Register services, configure DI, etc.
  }

  async onPluginInit() {
    // Initialize connections, etc.
  }

  async onPluginDestroy() {
    // Cleanup
  }
}

const app = await KarinFactory.create(adapter, {
  plugins: [new MyPlugin()],
});

API Reference

Decorators

Route Decorators

  • @Controller(path?: string) - Define a controller
  • @Get(path?: string) - HTTP GET
  • @Post(path?: string) - HTTP POST
  • @Put(path?: string) - HTTP PUT
  • @Patch(path?: string) - HTTP PATCH
  • @Delete(path?: string) - HTTP DELETE
  • @Fast() - Bypass middleware for performance

Parameter Decorators

  • @Param(key?: string) - Route parameter
  • @Query(key?: string) - Query string parameter
  • @Body() - Request body
  • @Headers(key?: string) - Request headers
  • @Req() - Full request object
  • @Res() - Full response object

Enhancement Decorators

  • @UseGuards(...guards) - Apply guards
  • @UsePipes(...pipes) - Apply pipes
  • @UseInterceptors(...interceptors) - Apply interceptors
  • @UseFilters(...filters) - Apply exception filters

Service Decorator

  • @Service() - Register as singleton in DI container

Filter Decorator

  • @Catch(...exceptions) - Specify which exceptions to catch

Classes

KarinFactory

  • create(adapter, options) - Create a Karin application

KarinApplication

  • listen(port, callback?) - Start the server
  • use(plugin) - Register a plugin
  • enableCors(options?) - Enable CORS
  • useGlobalFilters(...filters) - Register global filters
  • useGlobalGuards(...guards) - Register global guards
  • useGlobalPipes(...pipes) - Register global pipes

Exceptions

  • HttpException(message, status) - Base HTTP exception
  • BadRequestException(message?) - 400
  • UnauthorizedException(message?) - 401
  • ForbiddenException(message?) - 403
  • NotFoundException(message?) - 404
  • InternalServerErrorException(message?) - 500

Performance Optimizations

The core package includes several performance optimizations:

DI Cache

Pre-resolves and caches dependency injection instances for faster request handling.

Metadata Cache

Pre-compiles route metadata during bootstrap to eliminate runtime overhead.

Fast Decorator

Bypasses guards, pipes, and interceptors for maximum performance on specific routes.

Testing

The core package includes comprehensive tests:

bun test packages/core/test

See test documentation for details.

TypeScript Configuration

Ensure your tsconfig.json includes:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "target": "ES2022",
    "module": "ESNext"
  }
}

License

MIT