@hazeljs/core

中文文档
2.1.0发布于 2026/11/17Apache-2.0TypeScriptCommonJS构建来源已验证近 30 天下载 7017

Part of HazelJS — the open-source Agent OS for TypeScript. Dependency injection, routing, decorators, and base functionality

原始使用文档
文档目录35 节
  1. Why @hazeljs/core?
  2. Features
  3. Installation
  4. Quick Start
  5. 1. Create a Controller
  6. 2. Create a Service
  7. 3. Create a Module
  8. 4. Bootstrap the Application
  9. Dependency Injection
  10. Scopes
  11. Constructor Injection
  12. Routing & Decorators
  13. HTTP Methods
  14. Parameter Decorators
  15. Custom metadata and parameter decorators
  16. Middleware
  17. Global Middleware
  18. Route-Level Middleware
  19. Global exception filters
  20. Guards
  21. Interceptors
  22. Pipes
  23. Validation
  24. Health Checks
  25. Graceful Shutdown
  26. Exception Handling
  27. Testing
  28. Logging
  29. API Reference
  30. Decorators
  31. Classes
  32. Examples
  33. Contributing
  34. License
  35. Links

@hazeljs/core

DI, routing, and modules for Agent OS and HTTP APIs.

The kernel every HazelJS app boots: modules, controllers, dependency injection, middleware. Agent OS (@hazeljs/agent) runs in the same HazelApp. TypeScript-first. No Express or Fastify dependency.

Do not install or import reflect-metadata in your app — this package declares it and loads it.

npm version npm downloads License: Apache-2.0

Why @hazeljs/core?

The HTTP / DI layer Agent OS sits on. Combine with @hazeljs/agent, Skillgate, Gatekeeper, and Agent VM to ship durable agents beside REST — without Nest + LangGraph + a worker fleet.

Perfect for:

  • Teams putting agents in the same TypeScript backend as APIs
  • Replacing Express-only or DIY DI stacks with one framework
  • TypeScript-first DI without a heavy HTTP adapter

Features

  • 🎯 Dependency Injection - Advanced DI with Singleton, Transient, and Request scopes
  • 🎨 Decorator-Based API - Clean, intuitive programming model
  • 🛣️ Routing - Built-in routing with parameter extraction (no Express/Fastify)
  • 🔌 Middleware Support - Global and route-level middleware
  • 🛡️ Guards & Interceptors - Request validation and transformation
  • 🔧 Pipes - Data transformation and validation
  • 🏥 Health Checks - Built-in liveness, readiness, and startup probes
  • 🛑 Graceful Shutdown - Proper cleanup and connection draining
  • 📊 Logging - Winston-based structured logging
  • ✅ Validation - Automatic request validation with class-validator
  • 🧪 Testing Utilities - Full testing support with TestingModule

Installation

npm install @hazeljs/core

Do not install or import reflect-metadata in your app. @hazeljs/core declares it and loads it on import. Enable experimentalDecorators in tsconfig.json.

Quick Start

1. Create a Controller

import { Controller, Get, Post, Body, Param } from '@hazeljs/core';

@Controller('/users')
export class UserController {
  @Get()
  findAll() {
    return { users: [] };
  }

  @Get('/:id')
  findOne(@Param('id') id: string) {
    return { id, name: 'John Doe' };
  }

  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    return { message: 'User created', data: createUserDto };
  }
}

2. Create a Service

import { Injectable } from '@hazeljs/core';

@Injectable()
export class UserService {
  private users = [];

  findAll() {
    return this.users;
  }

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

  create(data: any) {
    const user = { id: Date.now().toString(), ...data };
    this.users.push(user);
    return user;
  }
}

3. Create a Module

import { HazelModule } from '@hazeljs/core';
import { UserController } from './user.controller';
import { UserService } from './user.service';

@HazelModule({
  controllers: [UserController],
  providers: [UserService],
})
export class AppModule {}

4. Bootstrap the Application

import { HazelApp, BuiltInHealthChecks } from '@hazeljs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await HazelApp.create(AppModule);

  // Register health checks
  app.registerHealthCheck(BuiltInHealthChecks.memoryCheck(500));
  app.registerHealthCheck(BuiltInHealthChecks.eventLoopCheck(100));

  // Register shutdown handlers
  app.registerShutdownHandler({
    name: 'cleanup',
    handler: async () => {
      console.log('Cleaning up resources...');
    },
    timeout: 5000,
  });

  await app.listen(3000);
}

bootstrap();

Dependency Injection

Scopes

import { Injectable, Scope } from '@hazeljs/core';

// Singleton (default) - one instance for entire app
@Injectable()
export class SingletonService {}

// Transient - new instance every time
@Injectable({ scope: Scope.TRANSIENT })
export class TransientService {}

// Request - one instance per HTTP request
@Injectable({ scope: Scope.REQUEST })
export class RequestContextService {}

Constructor Injection

@Injectable()
export class OrderService {
  constructor(
    private userService: UserService,
    private paymentService: PaymentService
  ) {}

  async createOrder(userId: string) {
    const user = await this.userService.findOne(userId);
    const payment = await this.paymentService.process(user);
    return { user, payment };
  }
}

Routing & Decorators

HTTP Methods

import { Controller, Get, Post, Put, Delete, Patch } from '@hazeljs/core';

@Controller('/api')
export class ApiController {
  @Get('/items')
  getItems() {}

  @Post('/items')
  createItem() {}

  @Put('/items/:id')
  updateItem() {}

  @Patch('/items/:id')
  patchItem() {}

  @Delete('/items/:id')
  deleteItem() {}
}

Parameter Decorators

import { Controller, Get, Post, Param, Query, Body, Headers, Req, Res } from '@hazeljs/core';

@Controller('/users')
export class UserController {
  @Get('/:id')
  findOne(@Param('id') id: string, @Query('include') include?: string) {
    return { id, include };
  }

  @Post()
  create(@Body() createUserDto: CreateUserDto, @Headers('authorization') auth: string) {
    return { data: createUserDto, auth };
  }

  @Get('/raw')
  rawAccess(@Req() req: Request, @Res() res: Response) {
    res.json({ message: 'Direct access to req/res' });
  }
}

Custom metadata and parameter decorators

Attach custom metadata for guards or other layers with SetMetadata / getMetadata, and build your own parameter decorators with createParamDecorator:

import { SetMetadata, getMetadata, createParamDecorator } from '@hazeljs/core';

// Custom metadata (e.g. for guards)
@SetMetadata('roles', ['admin'])
class AdminController {}

// Custom parameter decorator
const CurrentUser = createParamDecorator((_req, ctx) => ctx.user);

@Get('profile')
getProfile(@CurrentUser user: User) {
  return user;
}

Use the custom param decorator without parentheses: @CurrentUser. See the full API reference for ParamDecoratorContext and CUSTOM_METADATA_PREFIX.

Middleware

Global Middleware

import { Middleware, type RequestContext } from '@hazeljs/core';

@Injectable()
export class LoggerMiddleware implements Middleware {
  async use(context: RequestContext, next: () => Promise<unknown>) {
    console.log(`${context.method} ${context.url}`);
    return next();
  }
}

// Register globally
const app = await HazelApp.create(AppModule);
app.useGlobalMiddleware(new LoggerMiddleware());

Route-Level Middleware

import { Controller, Get, UseMiddleware } from '@hazeljs/core';

@Controller('/admin')
@UseMiddleware(AuthMiddleware)
export class AdminController {
  @Get('/dashboard')
  @UseMiddleware(RoleCheckMiddleware)
  getDashboard() {
    return { data: 'admin dashboard' };
  }
}

Global exception filters

import { HazelApp, HttpExceptionFilter, type ExceptionFilter } from '@hazeljs/core';

const app = await HazelApp.create(AppModule);
app.useGlobalExceptionFilter(new HttpExceptionFilter());

Guards

import { CanActivate, ExecutionContext, Injectable, UseGuards } from '@hazeljs/core';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean | Promise<boolean> {
    const token = context.request.headers.authorization;
    return this.validateToken(token);
  }

  private validateToken(token: string | undefined): boolean {
    // Validate JWT token
    return !!token;
  }
}

// Use in controller
@Controller('/protected')
@UseGuards(AuthGuard)
export class ProtectedController {
  @Get()
  getData() {
    return { message: 'Protected data' };
  }
}

Interceptors

import { Interceptor, Injectable, UseInterceptors, type RequestContext } from '@hazeljs/core';

@Injectable()
export class TransformInterceptor implements Interceptor {
  async intercept(context: RequestContext, next: () => Promise<unknown>) {
    const result = await next();

    return {
      data: result,
      timestamp: new Date().toISOString(),
      path: context.url,
    };
  }
}

// Use globally or per route
@Controller('/api')
@UseInterceptors(TransformInterceptor)
export class ApiController {}

Pipes

import { Injectable, PipeTransform, type RequestContext } from '@hazeljs/core';

@Injectable()
export class NonEmptyPipe implements PipeTransform<string, string> {
  transform(value: string, _context: RequestContext): string {
    if (!value) {
      throw new Error('Value is required');
    }
    return value;
  }
}

// Prefer the built-in ValidationPipe with class-validator DTOs (see Validation below).

Validation

import { IsEmail, IsString, MinLength } from 'class-validator';

export class CreateUserDto {
  @IsEmail()
  email: string;

  @IsString()
  @MinLength(8)
  password: string;

  @IsString()
  name: string;
}

@Controller('/users')
export class UserController {
  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    // Automatically validated before reaching here
    return createUserDto;
  }
}

Health Checks

import { HazelApp, BuiltInHealthChecks } from '@hazeljs/core';

const app = await HazelApp.create(AppModule);

// Built-in checks
app.registerHealthCheck(BuiltInHealthChecks.memoryCheck(500)); // 500MB threshold
app.registerHealthCheck(BuiltInHealthChecks.eventLoopCheck(100)); // 100ms lag

// Custom health check
app.registerHealthCheck({
  name: 'database',
  check: async () => {
    try {
      await database.ping();
      return { status: 'healthy' };
    } catch (error) {
      return {
        status: 'unhealthy',
        message: error.message,
      };
    }
  },
  critical: true,
  timeout: 3000,
});

// Endpoints available:
// GET /health  - Liveness probe
// GET /ready   - Readiness probe
// GET /startup - Startup probe

Graceful Shutdown

const app = await HazelApp.create(AppModule);

app.registerShutdownHandler({
  name: 'database',
  handler: async () => {
    await database.disconnect();
    console.log('Database disconnected');
  },
  timeout: 5000,
});

app.registerShutdownHandler({
  name: 'cache',
  handler: async () => {
    await redis.quit();
    console.log('Redis connection closed');
  },
  timeout: 3000,
});

await app.listen(3000);

// On SIGTERM/SIGINT:
// 1. HTTP server stops accepting new connections
// 2. Existing requests complete (up to 10s)
// 3. Shutdown handlers execute in order
// 4. Process exits cleanly

Exception Handling

import { ExceptionFilter, ExceptionContext } from '@hazeljs/core';

@Injectable()
export class HttpExceptionFilter implements ExceptionFilter {
  catch(error: Error, context: ExceptionContext) {
    const response = context.response;

    response.status(500).json({
      statusCode: 500,
      message: error.message,
      timestamp: new Date().toISOString(),
      path: context.request.url,
    });
  }
}

// Use globally
app.useGlobalExceptionFilter(new HttpExceptionFilter());

Testing

import { TestingModule } from '@hazeljs/core';
import { UserController } from './user.controller';
import { UserService } from './user.service';

describe('UserController', () => {
  let module: TestingModule;
  let controller: UserController;
  let service: UserService;

  beforeEach(async () => {
    module = await TestingModule.create({
      controllers: [UserController],
      providers: [
        {
          provide: UserService,
          useValue: {
            findAll: jest.fn().mockResolvedValue([]),
          },
        },
      ],
    });

    controller = module.get(UserController);
    service = module.get(UserService);
  });

  afterEach(async () => {
    await module.close();
  });

  it('should return all users', async () => {
    const result = await controller.findAll();
    expect(result).toEqual([]);
    expect(service.findAll).toHaveBeenCalled();
  });
});

Logging

HTTP requests are logged in following format: METHOD path status duration (e.g. GET /api/health 200 3ms).

Env varDefaultDescription
LOG_LEVELinfoLog level (error, warn, info, debug)
LOG_HTTPtrueSet to false to disable HTTP request logs
LOG_ENABLEDtrueSet to false to disable all logging

Startup and registration logs (controllers, routes, providers) are at debug level. Use LOG_LEVEL=debug for troubleshooting.

API Reference

Decorators

  • @HazelModule(options) - Define a module
  • @Controller(path) - Define a controller
  • @Injectable(options?) - Mark class as injectable
  • @Get(path?), @Post(path?), @Put(path?), @Delete(path?), @Patch(path?) - HTTP methods
  • @Param(name), @Query(name), @Body(), @Headers(name), @Req(), @Res(), @Ip(), @Host() - Parameter extraction
  • @UseGuards(...guards), @UseInterceptors(...interceptors), @UsePipes(...pipes) - Apply guards, interceptors, pipes
  • @Public() / @SkipAuth() - Mark route as public
  • @Timeout(ms), @Retry(options), @Optional(), @Session() - Per-route behavior
  • @ApiTags(...tags), @ApiOperation(options) - OpenAPI metadata
  • SetMetadata(key, value) - Attach custom metadata to a class or method (read with getMetadata(key, target, propertyKey?))
  • createParamDecorator(resolve) - Build custom parameter decorators that inject values from (req, context, container)

Classes

  • HazelApp - Main application class
  • TestingModule - Testing utilities
  • Logger - Logging service

Examples

See the examples directory for complete working examples.

Contributing

Contributions are welcome! Please read our Contributing Guide for details.

License

Apache 2.0 © HazelJS

版本与发布记录

@hazeljs/core 共发布 135 个版本,首次发布于 2026/02/07;过去 12 个月发布了 135 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.1.0latest2026/11/171 天前
2.0.182026/11/152 天前
2.0.172026/11/143 天前
2.0.162026/11/116 天前
2.0.152026/11/098 天前
2.0.142026/11/0710 天前

其他发布通道:beta → 0.2.0-beta.81,alpha → 0.2.0-alpha.6,rc → 0.2.0-rc.8。

关于 @hazeljs/core 的常见问题

@hazeljs/core 是什么?

Part of HazelJS — the open-source Agent OS for TypeScript. Dependency injection, routing, decorators, and base functionality

如何安装 @hazeljs/core?

在项目目录运行 npm install @hazeljs/core,或使用 pnpm add / yarn add / bun add。

@hazeljs/core 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@hazeljs/core 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@hazeljs/core 可以商用吗?

@hazeljs/core 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@hazeljs/core 的下载量有多少?

根据 npm 官方下载统计,@hazeljs/core 在 2026/10/18 – 2026/11/16 这 30 天内被下载 7,017 次,日均约 234 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@hazeljs/core 还在维护吗?

最新版本 2.1.0 发布于 2026/11/17(1 天前);至今共发布 135 个版本,其中过去 12 个月发布了 135 个;首次发布于 2026/02/07。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。