https://github.com/dangaogit/bun-server
A high-performance, decorator-driven DI web framework running on Bun Runtime.
https://github.com/dangaogit/bun-server
ai ai-agents aop bun bun-server ddd di-framework framework mirror-server monorepo nacos node server typescript web web-server
Last synced: 7 days ago
JSON representation
A high-performance, decorator-driven DI web framework running on Bun Runtime.
- Host: GitHub
- URL: https://github.com/dangaogit/bun-server
- Owner: dangaogit
- License: mit
- Created: 2025-12-04T07:11:32.000Z (2 months ago)
- Default Branch: main
- Last Pushed: 2026-01-20T09:04:52.000Z (18 days ago)
- Last Synced: 2026-01-20T16:44:00.969Z (18 days ago)
- Topics: ai, ai-agents, aop, bun, bun-server, ddd, di-framework, framework, mirror-server, monorepo, nacos, node, server, typescript, web, web-server
- Language: TypeScript
- Homepage:
- Size: 883 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Bun Server
[](https://bun.sh/)
[](https://www.typescriptlang.org/)
[](#license)
> A high-performance, decorator-driven DI web framework running on Bun Runtime.
- [Why Bun Server](#why-@dangao/bun-server)
- [Features](#features)
- [Architecture](#architecture)
- [Getting Started](#getting-started)
- [Examples & Extensions](#examples--extensions)
- [Benchmark Suite](#benchmark-suite)
- [Docs & Localization](#docs--localization)
- [Roadmap](#roadmap)
- [AI-Assisted Development](#ai-assisted-development)
- [Engineering Guidelines](#engineering-guidelines)
- [Contributing](#contributing)
- [License](#license)
- [Other Languages](#other-languages)
## Why Bun Server
- **Native Bun**: built on top of `Bun.serve`, embracing native TS, fast I/O and
the Bun package manager.
- **Modern DX**: decorators, metadata and DI everywhere β controllers, services,
middleware, validation.
- **Lightweight yet extensible**: modular DI + extension layer + logging
provider that scales from MVP to enterprise.
- **Well-tested**: unit, integration, stress and benchmark suites ship with the
repo.
- **AI-friendly**: source code and tests are included in the npm package,
enabling AI tools (like Cursor) to provide better code analysis, suggestions,
and understanding of the framework internals.
## Features
- π **Fast HTTP stack** powered by Bun with `Application`, `Router`, `Context`
and `ResponseBuilder` helpers.
- π§© **Dependency injection container** with `@Injectable`, `@Inject`, module
metadata, lifecycle management and cached dependency plans.
- π§΅ **Middleware pipeline** with global/class/method scopes plus built-ins
(logging, error, CORS, upload, static, ...).
- β
**Input validation** via decorators and `ValidationError` integration.
- π‘ **WebSocket gateways** with `@WebSocketGateway`, `@OnMessage`, etc.
- π **Docs & samples** including multi-language docs, benchmark scripts and
best practices.
## Architecture
### Request Lifecycle
The following diagram shows the complete request processing flow:
```
HTTP Request
β
βββββββββββββββββββββββββββββββββββββββ
β Middleware Pipeline β β Global β Module β Controller β Method
β (Logger, CORS, RateLimit, etc.) β
βββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββ
β Security Filter β β Authentication / Authorization
β (JWT, OAuth2, Role Check) β
βββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββ
β Router Matching β β Path, Method, Params
β (Static β Dynamic β Wildcard) β
βββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββ
β Interceptors (Pre) β β Global β Controller β Method
β (Cache, Log, Transform) β
βββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββ
β Parameter Binding β β @Body, @Query, @Param, @Header
β + Validation β β @Validate, IsString, IsEmail...
βββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββ
β Controller Method β β Business Logic Execution
β (with DI injected services) β
βββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββ
β Interceptors (Post) β β Method β Controller β Global
β (Response Transform) β
βββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββ
β Exception Filter β β Exception Handling
β (HttpException, ValidationError) β
βββββββββββββββββββββββββββββββββββββββ
β
HTTP Response
```
**Execution Order**: Middleware β Security β Router β Interceptors(Pre) β
Validation β Handler β Interceptors(Post) β Exception Filter
### Module System
```
Application
β
βββ ModuleRegistry
β β
β βββ ConfigModule (Configuration)
β βββ LoggerModule (Logging)
β βββ SecurityModule (Authentication)
β β βββ auth/ (JWT, OAuth2)
β βββ SwaggerModule (API Docs)
β βββ CacheModule (Caching)
β βββ DatabaseModule (Database)
β β βββ ORM (Entity, Repository, Transaction)
β βββ QueueModule (Job Queue)
β βββ SessionModule (Session)
β βββ MetricsModule (Metrics)
β βββ HealthModule (Health Check)
β βββ Microservice/
β βββ ConfigCenterModule
β βββ ServiceRegistryModule
β βββ ServiceClient
β βββ Governance (Circuit Breaker/Rate Limit/Retry)
β βββ Tracing
β
βββ ControllerRegistry
β βββ All module controllers
β
βββ WebSocketGatewayRegistry
β βββ WebSocket gateways
β
βββ InterceptorRegistry
βββ Interceptor registry
```
### DI Container
```
Container
β
βββ providers (Map)
β βββ Singleton (shared globally)
β βββ Transient (new instance per resolve)
β βββ Scoped (per-request instance)
β
βββ singletons (singleton instance cache)
β
βββ scopedInstances (WeakMap, request-level cache)
β
βββ dependencyPlans (dependency resolution plan cache)
β
βββ postProcessors (instance post-processors)
```
For detailed lifecycle documentation, see
[Request Lifecycle](./docs/request-lifecycle.md).
## Getting Started
### Requirements
- Bun β₯ `1.3.3`
### TypeScript Configuration β οΈ
**Critical**: Ensure your `tsconfig.json` includes these decorator settings:
```json
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true
}
}
```
Without these, dependency injection will fail (injected services will be
`undefined`). See
[Troubleshooting Guide](./docs/troubleshooting.md#-critical-injected-dependencies-are-undefined)
for details.
### Install
```bash
bun install
```
### Hello World
```ts
import { Application, Controller, GET, Injectable } from "@dangao/bun-server";
@Injectable()
class HealthService {
public ping() {
return { status: "ok" };
}
}
@Controller("/api")
class HealthController {
public constructor(private readonly service: HealthService) {}
@GET("/health")
public check() {
return this.service.ping();
}
}
const app = new Application({ port: 3100 });
app.getContainer().register(HealthService);
app.registerController(HealthController);
app.listen();
```
### Useful scripts
```bash
bun --cwd=packages/bun-server test
bun --cwd=packages/bun-server run bench
bun --cwd=packages/bun-server run bench:router
bun --cwd=packages/bun-server run bench:di
```
> Running `bun test` from the repo root fails because Bun only scans the current
> workspace. Use the commands above or `cd packages/bun-server` first.
### Advanced Example: Interface + Symbol + Module
This example demonstrates using interfaces with Symbol tokens and module-based
dependency injection:
```ts
import {
Application,
Body,
CONFIG_SERVICE_TOKEN,
ConfigModule,
ConfigService,
Controller,
GET,
Inject,
Injectable,
Module,
Param,
POST,
} from "@dangao/bun-server";
// Define service interface
interface UserService {
find(id: string): Promise<{ id: string; name: string } | undefined>;
create(name: string): { id: string; name: string };
}
// Create Symbol token for DI
const UserService = Symbol("UserService");
// Implement the interface
@Injectable()
class UserServiceImpl implements UserService {
private readonly users = new Map([
["1", { id: "1", name: "Alice" }],
]);
public async find(id: string) {
return this.users.get(id);
}
public create(name: string) {
const id = String(this.users.size + 1);
const user = { id, name };
this.users.set(id, user);
return user;
}
}
@Controller("/api/users")
class UserController {
public constructor(
private readonly service: UserService,
@Inject(CONFIG_SERVICE_TOKEN) private readonly config: ConfigService,
) {}
@GET("/:id")
public async getUser(@Param("id") id: string) {
const user = await this.service.find(id);
if (!user) {
return { error: "Not Found" };
}
return user;
}
@POST("/")
public createUser(@Body("name") name: string) {
return this.service.create(name);
}
}
// Define module with Symbol-based provider
@Module({
controllers: [UserController],
providers: [
{
provide: UserService,
useClass: UserServiceImpl,
},
],
exports: [UserService],
})
class UserModule {}
// Configure modules
ConfigModule.forRoot({
defaultConfig: {
app: {
name: "Advanced App",
port: 3100,
},
},
});
// Register module and start application
@Module({
imports: [ConfigModule],
controllers: [UserController],
providers: [
{
provide: UserService,
useClass: UserServiceImpl,
},
],
})
class AppModule {}
const app = new Application({ port: 3100 });
app.registerModule(AppModule);
app.listen();
```
**Key points:**
- **Interface-based design**: Define contracts with TypeScript interfaces
- **Symbol tokens**: Use `Symbol()` for type-safe dependency injection tokens
- **Module providers**: Register providers using
`provide: Symbol, useClass: Implementation`
- **Type-safe injection**: Inject services using `@Inject(Symbol)` with
interface types
## Examples & Extensions
### π Organized Examples
Examples are organized by difficulty and feature category:
- **[Quick Start](./examples/00-quick-start/)** - Get started in 5 minutes
- `01-hello-world.ts` - Minimal example (5 lines)
- `02-basic-routing.ts` - HTTP methods and route parameters
- `03-dependency-injection.ts` - DI basics with services
- **[Core Features](./examples/01-core-features/)** - Deep dive into framework
mechanics
- `basic-app.ts` - DI + Logger + Swagger + Config integration
- `multi-module-app.ts` - Module dependencies and organization
- `context-scope-app.ts` - Request scoping and ContextService
- `full-app.ts` - Validation, uploads, static files, WebSocket
- **[Official Modules](./examples/02-official-modules/)** - Ready-to-use modules
- `auth-app.ts` - JWT + OAuth2 authentication (with Web UI)
- `session-app.ts` - Session management
- `database-app.ts` - Database connection and queries
- `orm-app.ts` - Entity + Repository pattern
- `cache-app.ts` - Caching with decorators
- `queue-app.ts` - Task queues and Cron jobs
- **[Advanced](./examples/03-advanced/)** - Custom framework extensions
- `custom-decorator-app.ts` - Create custom decorators
- `websocket-chat-app.ts` - Complete WebSocket chat with rooms (with Web UI)
- `microservice-app.ts` - Microservices architecture
- **[Real World](./examples/04-real-world/)** - Production-ready examples
- `database-test-app.ts` - Database connection tester (Web UI)
- `perf/app.ts` - Performance benchmarking
### π Symbol + Interface Pattern
This framework features a unique **Symbol + Interface co-naming pattern** that
solves TypeScript's type erasure problem:
```typescript
// 1. Define interface and Symbol with same name
interface UserService {
find(id: string): Promise;
}
const UserService = Symbol('UserService');
// 2. Implement interface
@Injectable()
class UserServiceImpl implements UserService {
async find(id: string) { ... }
}
// 3. Register with Symbol token
@Module({
providers: [{
provide: UserService, // Symbol token
useClass: UserServiceImpl, // Implementation
}],
})
// 4. Inject with type safety
constructor(private readonly userService: UserService) {}
```
**Key**: Import as `import { UserService }` (not `import type { UserService }`).
See [Symbol + Interface Pattern Guide](./docs/symbol-interface-pattern.md) for
details.
### π Extensions
- `packages/bun-server/src/extensions/`: Official extensions (e.g.
`LoggerExtension`) for plugging in external capabilities.
### π Complete Example Index
See [examples/README.md](./examples/README.md) for the complete catalog with
learning paths, difficulty ratings, and usage scenarios.
## Benchmark Suite
Benchmarks live in `benchmark/` and rely on `PerformanceHarness` &
`StressTester`.
| Script | Description |
| ----------------- | --------------------------------------------------------------------- |
| `router.bench.ts` | static/dynamic route hits, `router.handle` and stress runs |
| `di.bench.ts` | singleton vs factory resolves, nested dependencies, concurrent stress |
Run directly:
```bash
bun benchmark/router.bench.ts
bun benchmark/di.bench.ts
```
Or use `bun run bench*` scripts for convenience.
## Docs & Localization
- **English** (default): `docs/api.md`, `docs/guide.md`,
`docs/best-practices.md`, `docs/migration.md`, `docs/extensions.md`,
`docs/deployment.md`, `docs/performance.md`, `docs/troubleshooting.md`,
`docs/error-handling.md`, `docs/request-lifecycle.md`.
- **Chinese**: mirrored under `docs/zh/`. If something is missing, please fall
back to the English source.
## Roadmap
Detailed milestones and history are tracked in the [`.roadmap/`](./.roadmap/)
directory.
## AI-Assisted Development
Bun Server is designed to work seamlessly with AI coding assistants like Cursor,
GitHub Copilot, and others. The framework includes source code and tests in the
npm package distribution, enabling AI tools to:
- **Understand framework internals**: AI can analyze the actual implementation
code, not just type definitions, providing more accurate suggestions.
- **Provide context-aware help**: When you ask about framework features, AI can
reference the actual source code to give precise answers.
- **Suggest best practices**: AI can learn from the framework's patterns and
suggest similar approaches in your code.
- **Debug more effectively**: AI can trace through the framework code to help
diagnose issues.
### Best Practices for AI-Assisted Development
1. **Reference framework source**: When working with Bun Server, AI tools can
access the source code at `node_modules/@dangao/bun-server/src/` to
understand implementation details.
2. **Use type hints**: The framework provides comprehensive TypeScript types.
Leverage these in your code to help AI understand your intent better.
3. **Follow framework patterns**: The included source code serves as a reference
for framework patterns. Ask AI to suggest code that follows similar patterns.
4. **Leverage test examples**: The included test files demonstrate usage
patterns and edge cases. Reference these when asking AI for implementation
help.
5. **Ask specific questions**: Since AI can access the framework source, you can
ask specific questions like "How does the DI container resolve dependencies?"
and get accurate answers based on the actual code.
## Engineering Guidelines
- Comments & log messages **must be in English** to keep the codebase
international-friendly.
- Documentation defaults to English; Chinese copies live in `docs/zh/`.
- Benchmarks belong to `benchmark/` and should run inside Bun environments.
## Contributing
1. Fork & create a feature branch.
2. Run `bun test` (and relevant benchmarks if the change affects performance).
3. Submit a PR with a clear description and test evidence.
Issues and discussions are welcome for new ideas or perf bottlenecks.
## License
Released under the [MIT License](./LICENSE).
## Other Languages
- [δΈζ README](./readme_zh.md)
Enjoy building on Bun Server!