koatty 3.13.2 β†’ 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/README.md CHANGED
@@ -1,162 +1,346 @@
1
- # Koatty πŸš€
2
-
3
- [![npm version](https://img.shields.io/npm/v/koatty)](https://www.npmjs.com/package/koatty)
4
- [![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause)
5
-
6
- Koa2 + Typescript + IOC = koatty. **Koatty** is a progressive Node.js framework for building efficient and scalable server-side applications. Perfect for crafting enterprise-level APIs, microservices, and full-stack applications with TypeScript excellence.
7
-
8
- ## Why Koatty? πŸ’‘
9
-
10
- - πŸš„ **High Performance**: Built on top of Koa2 with optimized architecture
11
- - 🧩 **Full-Featured**: Supports gRPC, HTTP, WebSocket, Schedule tasks, and more
12
- - 🧠 **TypeScript First**: Native TypeScript support with elegant OOP design
13
- - πŸŒ€ **Spring-like IOC Container**: Powerful dependency injection system with autowiring
14
- - βœ‚οΈ **AOP Support**: Aspect-oriented programming with decorator-based interceptors
15
- - πŸ”Œ **Extensible Architecture**: Plugin system with dependency injection
16
- - πŸ“¦ **Modern Tooling**: CLI scaffolding, testing utilities, and production-ready configs
17
- - 🌐 **Protocol Agnostic**: Write once, deploy as HTTP/gRPC/WebSocket services
18
-
19
-
20
- ## New features ✨
21
-
22
- * HTTP、HTTPS、HTTP2、gRPC、WebSocket server.βœ”οΈ
23
- * Support loading configurations based on the environment, support command-line argument parsing(process.argv), and support environment variable parsing(process.env).βœ”οΈ
24
- * `@ExceptionHandler()` Register global exception handling.βœ”οΈ
25
- * Graceful shutdown and pre-exit event.βœ”οΈ
26
- * Supports custom decorators, bound to app events for execution.βœ”οΈ
27
- * GraphQL integration is available. βœ”οΈ
28
- * Full-stack tracing capability through OpenTelemetry . βœ”οΈ
29
- * Middleware can be bound to controllers and their method routes.βœ”οΈ
30
- * gRPC streaming is now supported. βœ”οΈ
31
- * Added support for Swagger OpenAPI 3.0. πŸ’ͺ
32
-
33
-
34
- ## Core Features ✨
35
-
36
- ### πŸ“‘ Multi-Protocol Support
37
- ```typescript
38
- // config/config.ts
39
- export default {
40
- ...
41
- protocol: "grpc", // Server protocol 'http' | 'https' | 'http2' | 'grpc' | 'ws' | 'wss' | 'graphql'
42
- ...
43
- }
44
- ```
45
-
46
- ### πŸ’‰ Dependency Injection
47
- ```typescript
48
- @Service()
49
- export class UserService {
50
- async findUser(id: number) {
51
- return { id, name: 'Koatty User' };
52
- }
53
- }
54
-
55
- @Controller()
56
- export class IndexController {
57
- app: App;
58
- ctx: KoattyContext;
59
- @Config("protocol")
60
- conf: { protocol: string };
61
- ...
62
-
63
- @Autowired()
64
- private userService: UserService;
65
-
66
- async test(id: number) {
67
- const info = await this.userService.findUser(id);
68
- ...
69
- }
70
- }
71
- ```
72
-
73
- ### βœ‚οΈ Aspect-Oriented Programming
74
- ```javascript
75
- @Aspect()
76
- export class LogAspect implements IAspect {
77
- app: App;
78
-
79
- run() {
80
- console.log('LogAspect');
81
- }
82
- }
83
-
84
- // Apply aspect to controller
85
- @Controller()
86
- @BeforeEach(LogAspect)
87
- export class UserController {
88
- ...
89
- @After(LogAspect)
90
- test() {
91
- ...
92
- }
93
- }
94
- ```
95
-
96
- ### πŸ”Œ Plugin System
97
- ```javascript
98
- // plugin/logger.ts
99
- export class LoggerPlugin implements IPlugin {
100
- app: App;
101
-
102
- run() {
103
- // todo something or hook on app.event
104
- Logger.Debug("LoggerPlugin");
105
- return Promise.resolve();
106
- }
107
- }
108
- ```
109
-
110
-
111
- ## Benchmarks πŸ“Š
112
-
113
- | Framework | Requests/sec | Latency | Memory Usage |
114
- | ---------- | ------------ | ------- | ------------ |
115
- | **Koatty** | 13,321 | 1.43ms | 54MB |
116
- | Express | 12,456 | 1.45ms | 52MB |
117
- | NestJS | 11,892 | 1.51ms | 63MB |
118
-
119
- *Tested on AWS t3.micro with 100 concurrent connections*
120
-
121
- ## Documentation πŸ“š
122
-
123
- - [δΈ­ζ–‡ζ–‡ζ‘£](https://koatty.org/)
124
- - [Getting Started Guide](https://github.com/Koatty/koatty_doc/blob/master/docs/README-en.md)
125
- - [API Reference](https://koatty.org/#/?id=api)
126
- - [Recipes & Best Practices](https://github.com/Koatty/koatty_awesome)
127
- - [Example](https://github.com/Koatty/koatty_demo)
128
-
129
-
130
- ## Quick Start ⚑
131
-
132
- 1. **Install CLI**:
133
- ```bash
134
- npm install -g koatty_cli
135
- ```
136
-
137
- 2. **Create Project**:
138
- ```bash
139
- koatty new awesome-app
140
- ```
141
-
142
- 3. **Run Development Server**:
143
- ```bash
144
- cd awesome-app
145
- npm run dev
146
- ```
147
-
148
-
149
- ## Community 🌍
150
-
151
- - [GitHub Discussions](https://github.com/Koatty/koatty/discussions)
152
-
153
- ## Contributors ✨
154
-
155
- Thanks to these amazing developers:
156
-
157
- <!-- Add contributor list here -->
158
-
159
-
160
- ## License πŸ“„
161
-
162
- BSD-3 Β© [Koatty Team](https://github.com/Koatty)
1
+ # Koatty πŸš€
2
+
3
+ [![npm version](https://img.shields.io/npm/v/koatty)](https://www.npmjs.com/package/koatty)
4
+ [![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause)
5
+
6
+ Koa + TypeScript + IOC = Koatty. **Koatty** is a progressive Node.js framework for building efficient and scalable server-side applications. It's perfect for crafting enterprise-level APIs, microservices, and full-stack applications with TypeScript excellence.
7
+
8
+ ## Why Koatty? πŸ’‘
9
+
10
+ - πŸš„ **High Performance**: Built on top of Koa with optimized architecture
11
+ - 🧩 **Full-Featured**: Supports gRPC, HTTP, WebSocket, scheduled tasks, and more
12
+ - 🧠 **TypeScript First**: Native TypeScript support with elegant OOP design
13
+ - πŸŒ€ **Spring-like IOC Container**: Powerful dependency injection system with autowiring
14
+ - βœ‚οΈ **AOP Support**: Aspect-oriented programming with decorator-based interceptors
15
+ - πŸ”Œ **Extensible Architecture**: Plugin system with dependency injection
16
+ - πŸ“¦ **Modern Tooling**: CLI scaffolding, testing utilities, and production-ready configurations
17
+ - 🌐 **Protocol Agnostic**: Write once, deploy as HTTP/gRPC/WebSocket services
18
+
19
+ ### ✨ New Features
20
+
21
+ - βœ… **Multi-Protocol Architecture** - Run HTTP, HTTPS, HTTP/2, HTTP/3, gRPC, WebSocket, and GraphQL simultaneously
22
+ - βœ… **Intelligent Metadata Cache** - LRU caching with preloading for 70%+ performance boost
23
+ - βœ… **Protocol-Specific Middleware** - Bind middleware to specific protocols with `@Middleware({ protocol: [...] })`
24
+ - βœ… **Graceful Shutdown** - Enhanced connection pool management and cleanup handlers
25
+ - βœ… **Enhanced gRPC Support** - Timeout detection, duplicate call protection, streaming improvements
26
+ - βœ… **Application Lifecycle Hooks** - Custom decorators with `BindEventHook` API for boot/ready/stop events
27
+ - βœ… **Version Conflict Detection** - Automatic detection and resolution of dependency conflicts
28
+ - βœ… **GraphQL over HTTP/2** - Automatic HTTP/2 upgrade with SSL for multiplexing and compression
29
+ - βœ… **Global Exception Handling** - `@ExceptionHandler()` decorator for centralized error management
30
+ - βœ… **OpenTelemetry Tracing** - Full-stack observability with distributed tracing
31
+ - πŸ’ͺ **Swagger/OpenAPI 3.0** - Automatic API documentation generation
32
+
33
+ ## Core Features ✨
34
+
35
+ ### πŸ“‘ Multi-Protocol Support
36
+
37
+ Koatty now supports running multiple protocols simultaneously on different ports. Configure multiple servers easily:
38
+
39
+ ```typescript
40
+ // config/config.ts
41
+ export default {
42
+ ...
43
+ server: {
44
+ hostname: '127.0.0.1',
45
+ port: 3000,
46
+ protocol: ["http", "grpc"], // Multiple protocols: 'http' | 'https' | 'http2' | 'http3' | 'grpc' | 'ws' | 'wss' | 'graphql'
47
+ trace: false,
48
+ },
49
+ ...
50
+ }
51
+ ```
52
+
53
+ **Single Protocol (backward compatible):**
54
+ ```typescript
55
+ // config/config.ts
56
+ export default {
57
+ server: {
58
+ protocol: "grpc", // Single protocol
59
+ }
60
+ }
61
+ ```
62
+
63
+ **Multi-Protocol Router Configuration:**
64
+
65
+ When using multiple protocols, configure protocol-specific extensions in `config/router.ts`:
66
+
67
+ ```typescript
68
+ // config/router.ts
69
+ export default {
70
+ ext: {
71
+ // HTTP protocol config (optional)
72
+ ...,
73
+
74
+ // gRPC protocol config (optional)
75
+ protoFile: "./resource/proto/Hello.proto",
76
+ poolSize: 10,
77
+ streamConfig: { messageCount: 50 }
78
+
79
+
80
+ // WebSocket protocol config (optional)
81
+ maxFrameSize: 1024 * 1024,
82
+ heartbeatInterval: 15000,
83
+ maxConnections: 1000
84
+ }
85
+ }
86
+ ```
87
+
88
+ **How It Works:**
89
+ - `koatty_serve` automatically creates server instances for each protocol
90
+ - `koatty_router` creates dedicated router instances for each protocol
91
+ - Controllers are automatically registered to appropriate routers based on their decorators
92
+ - HTTP controllers (`@Controller`) work with HTTP/HTTPS/HTTP2
93
+ - gRPC controllers (`@GrpcController`) work with gRPC
94
+ - GraphQL controllers (`@GraphQLController`) work with GraphQL (over HTTP/HTTPS)
95
+ - WebSocket controllers (`@WsController`) work with WebSocket
96
+
97
+ **Important Notes:**
98
+ - **GraphQL Protocol**: GraphQL is an application-layer protocol that runs over HTTP/HTTP2, not a separate transport protocol. When you specify `protocol: "graphql"`, Koatty automatically:
99
+ - Uses **HTTP** as transport by default
100
+ - Uses **HTTP/2** when SSL certificates are configured (recommended for production)
101
+
102
+ - **GraphQL over HTTP/2** (Recommended): HTTP/2 provides significant benefits for GraphQL:
103
+ - **Multiplexing**: Handle multiple queries over a single connection
104
+ - **Header Compression**: Reduce bandwidth for large queries
105
+ - **Server Push**: Prefetch related resources
106
+ - **HTTP/1.1 Fallback**: Automatic downgrade for compatibility
107
+
108
+ To enable HTTP/2 for GraphQL, configure in `config/config.ts`:
109
+ ```typescript
110
+ // config/config.ts
111
+ export default {
112
+ server: {
113
+ protocol: "graphql",
114
+ ssl: {
115
+ mode: 'auto',
116
+ key: './ssl/server.key',
117
+ cert: './ssl/server.crt'
118
+ },
119
+ ext: {
120
+ maxConcurrentStreams: 100 // Optional: HTTP/2 config
121
+ }
122
+ }
123
+ }
124
+ ```
125
+
126
+ And configure GraphQL schema in `config/router.ts`:
127
+ ```typescript
128
+ // config/router.ts
129
+ export default {
130
+ ext: {
131
+ schemaFile: "./resource/graphql/schema.graphql"
132
+ }
133
+ }
134
+ ```
135
+
136
+
137
+ ### πŸ’‰ Dependency Injection
138
+
139
+ **Enhanced Features:**
140
+ -βœ… **Intelligent Metadata Cache** - LRU caching mechanism, significantly improves performance
141
+ -βœ… **Metadata Preloading** - Preload at startup, optimize component registration
142
+ -βœ… **Version Conflict Detection** - Automatically detect and resolve dependency version conflicts
143
+ -βœ… **Circular Dependency Detection** - Circular dependency detection and resolution suggestions
144
+
145
+ ```typescript
146
+ @Service()
147
+ export class UserService {
148
+ async findUser(id: number) {
149
+ return { id, name: 'Koatty User' };
150
+ }
151
+ }
152
+
153
+ @Controller()
154
+ export class IndexController {
155
+ app: App;
156
+ ctx: KoattyContext;
157
+ @Config("server")
158
+ conf: { protocol: string | string[] };
159
+ ...
160
+
161
+ @Autowired()
162
+ private userService: UserService;
163
+
164
+ async test(id: number) {
165
+ const info = await this.userService.findUser(id);
166
+ ...
167
+ }
168
+ }
169
+ ```
170
+
171
+ **Performance Improvements:**
172
+ ```typescript
173
+ // In Loader.ts - Metadata is now preloaded for optimal performance
174
+ IOC.preloadMetadata(); // Preload all metadata to populate cache
175
+
176
+ // Intelligent caching reduces reflect operations by 70%+
177
+ // Cache hits: ~95% in typical applications
178
+ ```
179
+
180
+ ### 🌐 Multi-Protocol Controllers
181
+
182
+ Different controllers for different protocols:
183
+
184
+ ```typescript
185
+ // HTTP Controller
186
+ @Controller('/api')
187
+ export class UserController {
188
+ @GetMapping('/users/:id')
189
+ async getUser(@PathVariable('id') id: string) {
190
+ return { id, name: 'User' };
191
+ }
192
+ }
193
+
194
+ // gRPC Controller
195
+ @GrpcController('/Hello')
196
+ export class HelloController {
197
+ @PostMapping('/SayHello')
198
+ @Validated()
199
+ async sayHello(@RequestBody() params: SayHelloRequestDto): Promise<SayHelloReplyDto> {
200
+ const res = new SayHelloReplyDto();
201
+ res.message = `Hello, ${params.name}!`;
202
+ return res;
203
+ }
204
+ }
205
+
206
+ // GraphQL Controller (runs over HTTP/HTTPS)
207
+ @GraphQLController('/graphql')
208
+ export class UserController {
209
+ @GetMapping()
210
+ async getUser(@RequestParam() id: string): Promise<User> {
211
+ return { id, name: 'GraphQL User' };
212
+ }
213
+
214
+ @PostMapping()
215
+ async createUser(@RequestParam() input: UserInput): Promise<User> {
216
+ return { id: input.id, name: input.name };
217
+ }
218
+ }
219
+ ```
220
+
221
+ ### βœ‚οΈ Aspect-Oriented Programming
222
+ ```typescript
223
+ @Aspect()
224
+ export class LogAspect implements IAspect {
225
+ app: App;
226
+
227
+ run() {
228
+ console.log('LogAspect');
229
+ }
230
+ }
231
+
232
+ // Apply aspect to controller
233
+ @Controller()
234
+ @BeforeEach(LogAspect)
235
+ export class UserController {
236
+ ...
237
+ @After(LogAspect)
238
+ test() {
239
+ ...
240
+ }
241
+ }
242
+ ```
243
+
244
+ ### πŸ”Œ Plugin System & Middleware
245
+
246
+ **Protocol-Specific Middleware:**
247
+ ```typescript
248
+ // Middleware can now be bound to specific protocols
249
+ @Middleware({ protocol: ["http", "https"] })
250
+ export class HttpOnlyMiddleware implements IMiddleware {
251
+ run(options: any, app: App) {
252
+ return async (ctx: KoattyContext, next: Function) => {
253
+ // This middleware only runs for HTTP/HTTPS protocols
254
+ console.log('HTTP request:', ctx.url);
255
+ await next();
256
+ };
257
+ }
258
+ }
259
+ ```
260
+
261
+ **Plugin System:**
262
+ ```typescript
263
+ // plugin/logger.ts
264
+ export class LoggerPlugin implements IPlugin {
265
+ app: App;
266
+
267
+ run() {
268
+ // Hook into application lifecycle events
269
+ Logger.Debug("LoggerPlugin");
270
+ return Promise.resolve();
271
+ }
272
+ }
273
+ ```
274
+
275
+ **Application Lifecycle Events:**
276
+ ```typescript
277
+ // Use BindEventHook to customize application behavior
278
+ export function CustomDecorator(): ClassDecorator {
279
+ return (target: Function) => {
280
+ BindEventHook(AppEvent.appBoot, async (app: KoattyApplication) => {
281
+ // Executed during application boot
282
+ console.log('App is booting...');
283
+ }, target);
284
+
285
+ BindEventHook(AppEvent.appReady, async (app: KoattyApplication) => {
286
+ // Executed when app is ready
287
+ console.log('App is ready!');
288
+ }, target);
289
+
290
+ BindEventHook(AppEvent.appStop, async (app: KoattyApplication) => {
291
+ // Executed during graceful shutdown
292
+ console.log('App is stopping...');
293
+ }, target);
294
+ };
295
+ }
296
+ ```
297
+
298
+ ## Benchmarks πŸ“Š
299
+
300
+ | Framework | Requests/sec | Latency | Memory Usage |
301
+ | ---------- | ------------ | ------- | ------------ |
302
+ | **Koatty** | 13,321 | 1.43ms | 54MB |
303
+ | Express | 12,456 | 1.45ms | 52MB |
304
+ | NestJS | 11,892 | 1.51ms | 63MB |
305
+
306
+ *Tested on AWS t3.micro with 100 concurrent connections*
307
+
308
+ ## Documentation πŸ“š
309
+
310
+ - [δΈ­ζ–‡ζ–‡ζ‘£](https://koatty.org/)
311
+ - [Getting Started Guide](https://github.com/Koatty/koatty_doc/blob/master/docs/README-en.md)
312
+ - [API Reference](https://koatty.org/#/?id=api)
313
+ - [Recipes & Best Practices](https://github.com/Koatty/koatty_awesome)
314
+ - [Example](https://github.com/Koatty/koatty_demo)
315
+
316
+ ## Quick Start ⚑
317
+
318
+ 1. **Install CLI**:
319
+ ```bash
320
+ npm install -g koatty_cli
321
+ ```
322
+
323
+ 2. **Create Project**:
324
+ ```bash
325
+ koatty new awesome-app
326
+ ```
327
+
328
+ 3. **Run Development Server**:
329
+ ```bash
330
+ cd awesome-app
331
+ npm run dev
332
+ ```
333
+
334
+ ## Community 🌍
335
+
336
+ - [GitHub Discussions](https://github.com/Koatty/koatty/discussions)
337
+
338
+ ## Contributors ✨
339
+
340
+ Thanks to these amazing developers:
341
+
342
+ <!-- Add contributor list here -->
343
+
344
+ ## License πŸ“„
345
+
346
+ BSD-3 Β© [Koatty Team](https://github.com/Koatty)
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
2
  * @Author: richen
3
- * @Date: 2025-04-25 21:48:09
3
+ * @Date: 2025-11-02 10:59:26
4
4
  * @License: BSD (3-Clause)
5
5
  * @Copyright (c) - <richenlin(at)gmail.com>
6
6
  * @HomePage: https://koatty.org/
@@ -10,7 +10,8 @@ import { Config } from 'koatty_config';
10
10
  import { EventHookFunc } from 'koatty_core';
11
11
  import { Helper } from 'koatty_lib';
12
12
  import { KoattyApplication } from 'koatty_core';
13
- import { Logger as Logger_2 } from 'koatty_logger';
13
+ import { LoggerConfig } from 'koatty_logger';
14
+ import { LogLevelType } from 'koatty_logger';
14
15
 
15
16
  /**
16
17
  * Bind event hook to target class.
@@ -48,7 +49,7 @@ export declare function BindEventHook(eventName: AppEvent, eventFunc: EventHookF
48
49
  * }
49
50
  * ```
50
51
  */
51
- export declare function Bootstrap(bootFunc?: Function): ClassDecorator;
52
+ export declare function Bootstrap(bootFunc?: (...args: any[]) => any): ClassDecorator;
52
53
 
53
54
  /**
54
55
  * Component scan decorator for Koatty application.
@@ -96,11 +97,63 @@ export declare function ConfigurationScan(scanPath?: string | string[]): ClassDe
96
97
  * app = await ExecBootStrap()(App);
97
98
  * ```
98
99
  */
99
- export declare function ExecBootStrap(bootFunc?: Function): (target: any) => Promise<KoattyApplication>;
100
+ export declare function ExecBootStrap(bootFunc?: (...args: any[]) => any): (target: any) => Promise<KoattyApplication>;
100
101
 
101
102
  export { Helper }
102
103
 
103
- export declare const Logger: Logger_2;
104
+ export declare const Logger: {
105
+ configure(config: Partial<LoggerConfig>, hotReload?: boolean): void;
106
+ setMinLevel(level: LogLevelType): void;
107
+ getMinLevel(): LogLevelType | null;
108
+ setLogPath(path: string): void;
109
+ setSensitiveFields(fields: string[]): void;
110
+ enableBuffering(config?: {
111
+ maxBufferSize?: number;
112
+ flushInterval?: number;
113
+ flushOnLevel?: "error" | "warn" | "info" | "debug";
114
+ }): void;
115
+ disableBuffering(): void;
116
+ setSamplingRate(key: string, rate: number): void;
117
+ getConfig(): LoggerConfig;
118
+ isInitialized(): boolean;
119
+ getStatus(): {
120
+ initialized: boolean;
121
+ failed: boolean;
122
+ usingFallback: boolean;
123
+ };
124
+ Debug(...args: any[]): void;
125
+ Info(...args: any[]): void;
126
+ Warn(...args: any[]): void;
127
+ Error(...args: any[]): void;
128
+ debug(...args: any[]): void;
129
+ info(...args: any[]): void;
130
+ warn(...args: any[]): void;
131
+ error(...args: any[]): void;
132
+ Fatal(...args: any[]): void;
133
+ fatal(...args: any[]): void;
134
+ fatalAndExit(message: string, exitCode?: number, error?: Error): Promise<never>;
135
+ Log(name: string, ...args: any[]): void;
136
+ log(name: string, ...args: any[]): void;
137
+ enable(b?: boolean): void;
138
+ getLevel(): LogLevelType;
139
+ setLevel(level: LogLevelType): void;
140
+ getLogFilePath(): string;
141
+ setLogFilePath(f: string): void;
142
+ getSensFields(): Set<string>;
143
+ setSensFields(fields: string[]): void;
144
+ clearSensFields(): void;
145
+ resetSensFields(fields: string[]): void;
146
+ destroy(): Promise<void>;
147
+ DebugSampled(key: string, message: string, ...args: any[]): void;
148
+ InfoSampled(key: string, message: string, ...args: any[]): void;
149
+ WarnSampled(key: string, message: string, ...args: any[]): void;
150
+ ErrorSampled(key: string, message: string, ...args: any[]): void;
151
+ configureBuffering(config: any): void;
152
+ configureSampling(key: string, rate: number): void;
153
+ getStats(): any;
154
+ flush(): Promise<void>;
155
+ stop(): Promise<void>;
156
+ };
104
157
 
105
158
 
106
159
  export * from "koatty_container";