zenweb 6.3.0 → 6.5.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/AGENTS.md ADDED
@@ -0,0 +1,419 @@
1
+ # AGENTS.md
2
+
3
+ AI 专用 API 参考文档,供 AI 编程助手使用。
4
+
5
+ **使用指引:**
6
+ - 创建新项目 → 阅读 `TEMPLATE.md`
7
+ - 理解现有代码 → 阅读 `AGENTS.md`
8
+
9
+ ---
10
+
11
+ ## 概述
12
+
13
+ ZenWeb 是基于 Koa 的模块化轻量级 Web 框架。`create()` 整合多个模块,开箱即用。
14
+
15
+ **核心设计:**
16
+ - AsyncLocalStorage 全局 Helper,请求期间任意位置可用
17
+ - TypeScript 装饰器驱动的控制器和依赖注入
18
+ - 统一的成功/失败响应格式
19
+
20
+ ---
21
+
22
+ ## 快速启动
23
+
24
+ ```ts
25
+ import { create } from 'zenweb';
26
+
27
+ create({
28
+ controller: {
29
+ discoverPaths: ['./controller'],
30
+ autoControllerPrefix: true,
31
+ },
32
+ }).start();
33
+ ```
34
+
35
+ ---
36
+
37
+ ## TypeScript 配置(必需)
38
+
39
+ ```json
40
+ {
41
+ "compilerOptions": {
42
+ "experimentalDecorators": true,
43
+ "emitDecoratorMetadata": true,
44
+ "target": "ES2020",
45
+ "module": "commonjs"
46
+ }
47
+ }
48
+ ```
49
+
50
+ ---
51
+
52
+ ## 导出概览
53
+
54
+ ```ts
55
+ // 主函数
56
+ export { create, Core };
57
+
58
+ // 依赖注入
59
+ export { Injectable, Init, Inject, $getInstance } from '@zenweb/inject';
60
+
61
+ // 控制器装饰器
62
+ export { Controller, Get, Post, Put, Patch, Delete, All, Mapping } from '@zenweb/controller';
63
+
64
+ // 路由
65
+ export { Router, RouterMethod, RouterPath } from '@zenweb/router';
66
+
67
+ // 结果处理
68
+ export { fail, ResultFail } from '@zenweb/result';
69
+
70
+ // 全局 Helper($前缀,AsyncLocalStorage)
71
+ export { $ctx, $getCore, $getContext, $core, $debug, createDebug } from '@zenweb/core';
72
+ export { $body, $getObjectBody, $getRawBody, $getTextBody } from '@zenweb/body';
73
+ export { $param, $query, $helperBase } from '@zenweb/helper';
74
+ export { $log, $getLogger, Logger } from '@zenweb/log';
75
+
76
+ // Core 类型
77
+ export { Context, Middleware, Next, SetupFunction, SetupHelper } from '@zenweb/core';
78
+ ```
79
+
80
+ ---
81
+
82
+ ## 控制器
83
+
84
+ 控制器类自动标记为请求级注入,方法参数自动注入。
85
+
86
+ ```ts
87
+ // controller/user.ts - 文件名映射为路由前缀 /user
88
+ export class UserController {
89
+ @Get() // GET /user
90
+ list() { return []; }
91
+
92
+ @Get('/:id') // GET /user/:id
93
+ async detail(ctx: Context, service: UserService) {
94
+ const { id } = await $param.get({ id: '!int' });
95
+ return service.getById(id);
96
+ }
97
+
98
+ @Post() // POST /user
99
+ async create() {
100
+ return await $body.get({ name: '!string', email: 'string' });
101
+ }
102
+ }
103
+ ```
104
+
105
+ **@Controller 装饰器(可选):**
106
+ ```ts
107
+ @Controller({ prefix: '/admin' }) // 绝对前缀
108
+ @Controller({ prefix: 'manage' }) // 相对前缀,拼接自动前缀
109
+ @Controller({ middleware: [authFn] }) // 控制器级中间件
110
+ ```
111
+
112
+ **生命周期:**
113
+ ```ts
114
+ @Controller()
115
+ export class MyController {
116
+ constructor(private ctx: Context) {} // 自动注入
117
+
118
+ @Init
119
+ init() { /* 实例化后调用 */ }
120
+ }
121
+ ```
122
+
123
+ **单例控制器**(适用于无状态场景):
124
+ ```ts
125
+ @Controller()
126
+ @Injectable('singleton')
127
+ export class CounterController {
128
+ counter = 0;
129
+ @Get() index() { return ++this.counter; }
130
+ }
131
+ ```
132
+
133
+ ---
134
+
135
+ ## Router 直接使用(非控制器场景)
136
+
137
+ 不使用控制器装饰器时,可直接通过 `app.router` 注册路由:
138
+
139
+ ```ts
140
+ import { create, Router } from 'zenweb';
141
+
142
+ const app = create({
143
+ controller: false, // 禁用控制器自动发现
144
+ });
145
+
146
+ // 直接注册路由
147
+ app.router.get('/hello', ctx => {
148
+ ctx.body = 'Hello';
149
+ });
150
+
151
+ // 子路由
152
+ const subRouter = new Router({ prefix: '/admin' });
153
+ subRouter.get('/dashboard', ctx => ctx.body = 'dashboard');
154
+ app.router.add(subRouter);
155
+
156
+ app.start();
157
+ ```
158
+
159
+ ---
160
+
161
+ ## 全局中间件
162
+
163
+ 通过 `setup.middleware()` 添加应用级中间件:
164
+
165
+ ```ts
166
+ import { create } from 'zenweb';
167
+
168
+ const app = create();
169
+
170
+ // Core 级中间件(所有请求)
171
+ app.setup(function myMiddleware(setup) {
172
+ setup.middleware(async (ctx, next) => {
173
+ ctx.set('X-Custom', 'value');
174
+ return next();
175
+ });
176
+ });
177
+ ```
178
+
179
+ ---
180
+
181
+ ## 消息代码(MessageCode)
182
+
183
+ 用于错误消息格式化,**优先使用统一定义文件**:
184
+
185
+ ```ts
186
+ // message-codes.json(推荐)
187
+ {
188
+ "user.notfound": "用户不存在",
189
+ "user.login.fail": "登录失败: {reason}",
190
+ "error.system": "系统错误"
191
+ }
192
+
193
+ // 或 message-codes.ts
194
+ export default {
195
+ 'user.notfound': '用户不存在',
196
+ 'user.login.fail': '登录失败: {reason}',
197
+ };
198
+
199
+ // 配置(默认自动加载 ./message-codes.json)
200
+ create({
201
+ messagecode: {
202
+ autoLoadFilenames: ['./message-codes.json', './codes/custom.ts'],
203
+ },
204
+ });
205
+
206
+ // 使用
207
+ ctx.messageCodeResolver.format('user.login.fail', { reason: '密码错误' });
208
+ ctx.messageCodeResolver.fail('user.notfound'); // 直接抛出 fail 异常
209
+ ```
210
+
211
+ ---
212
+
213
+ ## 依赖注入
214
+
215
+ **Service 类默认添加 @Injectable 注解**(将 service 类的作用域设置为 request):
216
+
217
+ ```ts
218
+ @Injectable // Service 类必须添加注解!
219
+ export class UserService {
220
+ constructor(private ctx: Context, private db: DatabaseService) {} // 自动注入
221
+ }
222
+ ```
223
+
224
+ **无法用构造器注入时,使用 @Inject 属性注入**:
225
+
226
+ ```ts
227
+ @Injectable
228
+ export class MyService {
229
+ constructor(private ctx: Context) {} // 构造器注入
230
+
231
+ @Inject private cache!: CacheService; // 属性注入(后注入)
232
+ }
233
+ ```
234
+
235
+ **作用域:**
236
+ ```ts
237
+ @Injectable // 请求级(默认)
238
+ @Injectable('singleton') // 单例,不可注入 request 级依赖
239
+ @Injectable('prototype') // 每次注入创建新实例
240
+ ```
241
+
242
+ ---
243
+
244
+ ## 全局 Helper
245
+
246
+ 请求期间任意位置可用,无需注入:
247
+
248
+ ```ts
249
+ // Body
250
+ await $body.get({ name: '!string', age: 'int' });
251
+ await $body.page({ limit: 10 });
252
+
253
+ // Query
254
+ await $query.get({ id: '!int', keyword: 'trim' });
255
+ await $query.page({ allowOrder: ['id'] });
256
+
257
+ // Param(路由参数)
258
+ $ctx.params; // 原始参数对象 { id: '123' }
259
+ await $param.get({ id: '!int' }); // 带类型转换
260
+
261
+ // 日志
262
+ $log.info('message');
263
+ $log.child({ requestId: 'abc' }).debug('with context');
264
+
265
+ // 上下文
266
+ $ctx.ip; $ctx.path; $ctx.header;
267
+ $getCore().name;
268
+ ```
269
+
270
+ ---
271
+
272
+ ## 错误处理
273
+
274
+ **fail() 用于预期业务错误**(给用户看的错误):
275
+
276
+ ```ts
277
+ import { fail } from 'zenweb';
278
+
279
+ // 业务预期的错误,如参数验证失败、用户不存在等
280
+ fail('用户不存在');
281
+ fail(400, '参数错误');
282
+ fail({ code: 10001, message: '余额不足' });
283
+ ```
284
+
285
+ **非预期错误使用自定义异常**(如数据库连接失败、代码 bug),不要用 fail():
286
+
287
+ ```ts
288
+ class DatabaseError extends Error {
289
+ constructor(message: string) {
290
+ super(message);
291
+ this.name = 'DatabaseError';
292
+ }
293
+ }
294
+
295
+ // 非预期错误,框架会返回 500 并隐藏详情
296
+ throw new DatabaseError('连接失败');
297
+ ```
298
+
299
+ **控制器 return 值通过 ctx.success(data) 输出,默认不做包装:**
300
+ ```ts
301
+ return { name: 'test' }; // → { name: 'test' }
302
+
303
+ // 如需包装需在 create() 中配置
304
+ create({
305
+ result: {
306
+ successWrap: (ctx, data) => ({ code: 0, data }),
307
+ },
308
+ });
309
+ ```
310
+
311
+ ---
312
+
313
+ ## create() 配置
314
+
315
+ ```ts
316
+ create({
317
+ global: true, // 全局实例,默认 true
318
+ core: { keys: ['secret'] },
319
+ meta: false, // 禁用模块
320
+ log: { dir: '/var/log' },
321
+ result: { failCode: 1, failStatus: 400 },
322
+ body: { limit: 1024 * 1024 },
323
+ helper: { page: { defaultLimit: 20 } },
324
+ controller: {
325
+ discoverPaths: ['./controller'],
326
+ autoControllerPrefix: true,
327
+ },
328
+ })
329
+ ```
330
+
331
+ ---
332
+
333
+ ## 集成模块
334
+
335
+ 已集成,无需单独安装:
336
+
337
+ | 模块 | 作用 |
338
+ |------|------|
339
+ | `@zenweb/core` | 核心应用 |
340
+ | `@zenweb/inject` | 依赖注入 |
341
+ | `@zenweb/router` | Trie 路由 |
342
+ | `@zenweb/controller` | 控制器装饰器 |
343
+ | `@zenweb/body` | Body 解析 |
344
+ | `@zenweb/helper` | 参数验证 |
345
+ | `@zenweb/result` | 结果处理 |
346
+ | `@zenweb/log` | 日志 |
347
+ | `@zenweb/meta` | 请求元信息 |
348
+ | `@zenweb/messagecode` | 错误消息格式化 |
349
+
350
+ **可选扩展:**
351
+
352
+ | 模块 | 作用 |
353
+ |------|------|
354
+ | `@zenweb/cors` | 跨域支持 |
355
+ | `@zenweb/sentry` | Sentry 错误收集 |
356
+ | `@zenweb/metric` | 运行健康信息 |
357
+ | `@zenweb/mysql` | MySQL 数据库 |
358
+ | `@zenweb/tenant` | 多租户数据库连接池 |
359
+ | `@zenweb/orm` | ORM 支持 |
360
+ | `@zenweb/template` | 模版渲染 |
361
+ | `@zenweb/schedule` | 定时任务 |
362
+ | `@zenweb/upload` | 文件上传 |
363
+ | `@zenweb/cache` | Redis 缓存支持 |
364
+ | `@zenweb/cache-opt` | Redis 缓存优化 |
365
+ | `@zenweb/msgpack` | MessagePack 输出 |
366
+ | `@zenweb/ratelimit` | 请求量控制(防CC攻击) |
367
+ | `@zenweb/websocket` | WebSocket 支持 |
368
+ | `@zenweb/xml-body` | XML Body 解析 |
369
+ | `@zenweb/form` | 表单构建 |
370
+ | `@zenweb/grid` | 数据表渲染 |
371
+
372
+ ---
373
+
374
+ ## 类型转换语法
375
+
376
+ ```ts
377
+ await $body.get({
378
+ name: '!string', // 必填字符串
379
+ age: 'int', // 可选整数
380
+ tags: 'string[]', // 字符串数组
381
+ active: '!bool', // 必填布尔
382
+ email: 'trim', // 去空格
383
+ });
384
+ ```
385
+
386
+ 支持类型:`int`, `float`, `number`, `bool`, `string`, `trim`, `date`, `datetime`, `array`, `object`, `json`
387
+
388
+ ---
389
+
390
+ ## 各模块详细文档
391
+
392
+ 详细 API 参阅各模块 AGENTS.md:
393
+
394
+ - `node_modules/@zenweb/core/AGENTS.md`
395
+ - `node_modules/@zenweb/inject/AGENTS.md`
396
+ - `node_modules/@zenweb/controller/AGENTS.md`
397
+ - `node_modules/@zenweb/body/AGENTS.md`
398
+ - `node_modules/@zenweb/helper/AGENTS.md`
399
+ - `node_modules/@zenweb/result/AGENTS.md`
400
+ - `node_modules/@zenweb/router/AGENTS.md`
401
+ - `node_modules/@zenweb/log/AGENTS.md`
402
+ - `node_modules/@zenweb/meta/AGENTS.md`
403
+ - `node_modules/@zenweb/messagecode/AGENTS.md`
404
+
405
+ ---
406
+
407
+ ## AI 使用要点
408
+
409
+ 1. **已集成模块从 zenweb 导入**,可选模块(cors, mysql, orm 等)从各自模块导入
410
+ ```ts
411
+ import { Injectable, Context, fail } from 'zenweb'; // 集成模块
412
+ import { MySQL } from '@zenweb/mysql'; // 可选模块
413
+ ```
414
+ 2. 优先用全局 Helper `$body/$query/$param/$log`,比 DI 更简洁
415
+ 3. **Service 类必须添加 @Injectable 注解**,优先用构造器参数注入
416
+ 4. 必填字段用 `!` 前缀,避免空值问题
417
+ 5. 单例服务不可依赖 Context,用方法参数传递
418
+ 6. 控制器文件名映射路由前缀(`autoControllerPrefix: true`)
419
+ 7. `fail()` 仅用于预期业务错误(给用户看),非预期错误用自定义异常
package/README.md CHANGED
@@ -1,129 +1,170 @@
1
1
  # ZenWeb
2
2
 
3
- Modular lightweight web framework based on Koa
3
+ 基于 Koa 的模块化轻量级 Web 框架。
4
4
 
5
- ## Document
5
+ ## 特性
6
+
7
+ - **开箱即用** - `create()` 整合多个模块,无需逐个安装
8
+ - **全局 Helper** - `$body/$query/$param/$log` 在请求期间任意位置可用
9
+ - **装饰器驱动** - TypeScript 装饰器实现控制器路由和依赖注入
10
+ - **统一响应** - `fail()` 处理业务错误,控制器 return 自动输出
11
+
12
+ ## 文档
6
13
 
7
14
  [ZenWeb 文档](https://zenweb.node.ltd)
8
15
 
9
- ## Install
16
+ ## 安装
10
17
 
11
18
  ```bash
12
- # for production
13
- npm install zenweb
19
+ npm i zenweb
14
20
 
15
- # for development
16
- npm install dotenv typescript rimraf tsc-watch --save-dev
21
+ # 开发依赖
22
+ npm i -D dotenv typescript rimraf tsc-watch
17
23
  ```
18
24
 
19
- ## Project Code
20
-
21
- edit `package.json` file at `scripts`:
22
-
23
- ```json
24
- "scripts": {
25
- "start": "node --enable-source-maps app",
26
- "dev": "rimraf app && tsc-watch --onSuccess \"npm run dev-start\"",
27
- "dev-start": "node -r dotenv/config --enable-source-maps app",
28
- "build": "rimraf app && tsc"
29
- }
30
- ```
25
+ ## TypeScript 配置(必需)
31
26
 
32
- create `tsconfig.json` file
27
+ 装饰器功能需要以下配置:
33
28
 
34
29
  ```json
35
30
  {
36
- "extends": "zenweb/tsconfig-app",
37
31
  "compilerOptions": {
38
- "outDir": "./app"
39
- },
40
- "include": ["src/**/*"]
32
+ "experimentalDecorators": true,
33
+ "emitDecoratorMetadata": true,
34
+ "target": "ES2020",
35
+ "module": "commonjs"
36
+ }
41
37
  }
42
38
  ```
43
39
 
44
- create `.env` file
45
-
46
- ```bash
47
- APP_NAME=myweb
48
- NODE_ENV=development
49
- DEBUG=*
50
- ```
51
-
52
- create `src/index.ts` file
40
+ ## 快速开始
53
41
 
54
42
  ```ts
55
43
  import { create } from 'zenweb';
56
- create().start();
44
+
45
+ create({
46
+ controller: {
47
+ discoverPaths: ['./controller'],
48
+ autoControllerPrefix: true,
49
+ },
50
+ }).start();
57
51
  ```
58
52
 
59
- create `src/service/hello.ts` file
53
+ ## 控制器
54
+
55
+ 文件名映射为路由前缀(开启 `autoControllerPrefix`):
60
56
 
61
57
  ```ts
62
- import { Component, Context } from 'zenweb';
58
+ // controller/user.ts /user
59
+ import { Get, Post, Context } from 'zenweb';
60
+ import { UserService } from '../service/user';
61
+
62
+ export class UserController {
63
+ constructor(private ctx: Context) {}
63
64
 
64
- @Component
65
- export class HelloService {
66
- constructor(
67
- private ctx: Context,
68
- ){}
65
+ @Get() // GET /user
66
+ list() { return []; }
69
67
 
70
- getIp() {
71
- return this.ctx.ip;
68
+ @Get('/:id') // GET /user/:id
69
+ detail() {
70
+ const { id } = this.ctx.params;
71
+ return { id };
72
+ }
73
+
74
+ @Post() // POST /user
75
+ create(service: UserService) {
76
+ return service.create();
72
77
  }
73
78
  }
74
79
  ```
75
80
 
76
- create `src/controller/hello.ts` file
81
+ ## Service
82
+
83
+ Service 类添加 `@Injectable` 注解,作用域为请求级:
77
84
 
78
85
  ```ts
79
- import { Get } from 'zenweb';
80
- import { HelloService } from '../service/hello';
81
-
82
- export class HelloController {
83
- @Get()
84
- index(service: HelloService) {
85
- const ip = service.getIp();
86
- return `Hello ZenWeb! ${ip}`;
86
+ // service/user.ts
87
+ import { Injectable, Context } from 'zenweb';
88
+
89
+ @Injectable
90
+ export class UserService {
91
+ constructor(private ctx: Context) {}
92
+
93
+ create() {
94
+ return { ip: this.ctx.ip };
87
95
  }
88
96
  }
89
97
  ```
90
98
 
91
- start server:
99
+ ## 全局 Helper
92
100
 
93
- ```bash
94
- npm run dev
101
+ 请求期间无需注入,直接使用:
102
+
103
+ ```ts
104
+ // Body 解析
105
+ await $body.get({ name: '!string', age: 'int' });
106
+
107
+ // Query 参数
108
+ await $query.get({ id: '!int', keyword: 'trim' });
109
+
110
+ // 路由参数
111
+ const { id } = $ctx.params;
112
+
113
+ // 日志
114
+ $log.info('message');
95
115
  ```
96
116
 
97
- ## 内置模块
98
- - [core](https://www.npmjs.com/package/@zenweb/core) 核心
99
- - [meta](https://www.npmjs.com/package/@zenweb/meta) 运行基本信息,例如:请求耗时
100
- - [inject](https://www.npmjs.com/package/@zenweb/inject) 注入支持
101
- - [router](https://www.npmjs.com/package/@zenweb/router) 路由支持
102
- - [log](https://www.npmjs.com/package/@zenweb/log) 日志支持
103
- - [result](https://www.npmjs.com/package/@zenweb/result) 统一结果返回,成功或失败
104
- - [messagecode](https://www.npmjs.com/package/@zenweb/messagecode) 统一错误消息格式化
105
- - 依赖 inject, result
106
- - [controller](https://www.npmjs.com/package/@zenweb/controller) 类控制器支持
107
- - 依赖 inject, router
108
- - [helper](https://www.npmjs.com/package/@zenweb/helper) 输入数据验证助手
109
- - 依赖 inject, messagecode
110
- - [body](https://www.npmjs.com/package/@zenweb/body) 请求主体解析,JSON、Form
111
- - 依赖 inject, helper
112
-
113
- 内置模块默认开启,可以通过设置配置项为 **false** 关闭
117
+ ## 错误处理
114
118
 
119
+ `fail()` 用于预期业务错误:
120
+
121
+ ```ts
122
+ import { fail } from 'zenweb';
123
+
124
+ if (!user) {
125
+ fail('用户不存在'); // 返回错误响应,终止执行
126
+ }
127
+ ```
128
+
129
+ 非预期错误(代码 bug、数据库连接失败等)直接抛出 Error,框架返回 500。
130
+
131
+ ## 集成模块
132
+
133
+ 已集成,无需单独安装:
134
+
135
+ | 模块 | 作用 |
136
+ |------|------|
137
+ | `@zenweb/core` | 核心应用 |
138
+ | `@zenweb/inject` | 依赖注入 |
139
+ | `@zenweb/router` | Trie 路由 |
140
+ | `@zenweb/controller` | 控制器装饰器 |
141
+ | `@zenweb/body` | Body 解析 |
142
+ | `@zenweb/helper` | 参数验证 |
143
+ | `@zenweb/result` | 结果处理 |
144
+ | `@zenweb/log` | 日志 |
145
+ | `@zenweb/meta` | 请求元信息 |
146
+ | `@zenweb/messagecode` | 错误消息格式化 |
147
+
148
+ 集成模块默认开启,可通过配置项设为 `false` 关闭。
115
149
 
116
150
  ## 可选模块
117
- - [cors](https://www.npmjs.com/package/@zenweb/cors) 跨域支持
118
- - [sentry](https://www.npmjs.com/package/@zenweb/sentry) sentry 错误收集
119
- - [metric](https://www.npmjs.com/package/@zenweb/metric) 生产运行健康信息收集
120
- - [validation](https://www.npmjs.com/package/@zenweb/validation) JSONSchema 验证
121
- - [mysql](https://www.npmjs.com/package/@zenweb/mysql) MySQL 数据库支持
122
- - [orm](https://www.npmjs.com/package/@zenweb/orm) ORM 支持
123
- - [template](https://www.npmjs.com/package/@zenweb/template) 模版渲染
124
- - [schedule](https://www.npmjs.com/package/@zenweb/schedule) 定时任务
125
- - [form](https://www.npmjs.com/package/@zenweb/form) 统一表单(多用于后台)
126
- - [grid](https://www.npmjs.com/package/@zenweb/grid) 统一表格(多用于后台)
127
- - [upload](https://www.npmjs.com/package/@zenweb/upload) 文件上传支持
128
- - [xmlBody](https://www.npmjs.com/package/@zenweb/xml-body) XML Body 解析
129
- - [msgpack](https://www.npmjs.com/package/@zenweb/msgpack) MessagePack 输出
151
+
152
+ | 模块 | 作用 |
153
+ |------|------|
154
+ | `@zenweb/cors` | 跨域支持 |
155
+ | `@zenweb/sentry` | Sentry 错误收集 |
156
+ | `@zenweb/metric` | 运行健康信息 |
157
+ | `@zenweb/mysql` | MySQL 数据库 |
158
+ | `@zenweb/tenant` | 多租户数据库连接池 |
159
+ | `@zenweb/orm` | ORM 支持 |
160
+ | `@zenweb/template` | 模版渲染 |
161
+ | `@zenweb/schedule` | 定时任务 |
162
+ | `@zenweb/upload` | 文件上传 |
163
+ | `@zenweb/cache` | Redis 缓存支持 |
164
+ | `@zenweb/cache-opt` | Redis 缓存优化 |
165
+ | `@zenweb/msgpack` | `@zenweb/result` MessagePack 支持 |
166
+ | `@zenweb/ratelimit` | 请求量控制(防CC攻击) |
167
+ | `@zenweb/websocket` | WebSocket 支持(分布式会话共享) |
168
+ | `@zenweb/xml-body` | `@zenweb/body` XML 解析支持 |
169
+ | `@zenweb/form` | 表单构建 |
170
+ | `@zenweb/grid` | 数据表渲染 |
package/TEMPLATE.md ADDED
@@ -0,0 +1,231 @@
1
+ # TEMPLATE.md
2
+
3
+ AI 编程脚手架模板 - 创建 ZenWeb 项目时使用此结构。
4
+
5
+ ---
6
+
7
+ ## 项目结构
8
+
9
+ ```
10
+ project/
11
+ ├── src/
12
+ │ ├── index.ts # 应用入口
13
+ │ ├── controller/ # 控制器目录
14
+ │ │ └── index.ts # 根路由控制器
15
+ │ ├── service/ # 服务目录
16
+ │ ├── message-codes.json # 错误消息定义(可选)
17
+ │ └── types.ts # 类型定义(可选)
18
+ ├── package.json
19
+ ├── tsconfig.json
20
+ ├── .env # 开发环境变量
21
+ └── .gitignore
22
+ ```
23
+
24
+ ---
25
+
26
+ ## package.json
27
+
28
+ ```json
29
+ {
30
+ "name": "myapp",
31
+ "version": "1.0.0",
32
+ "main": "app/index.js",
33
+ "scripts": {
34
+ "build": "rimraf app && tsc",
35
+ "start": "node --enable-source-maps app",
36
+ "dev-start": "node --env-file=.env --enable-source-maps app",
37
+ "dev": "rimraf app && tsc-watch --onSuccess \"npm run dev-start\""
38
+ },
39
+ "dependencies": {
40
+ "zenweb": "^6.5.0"
41
+ },
42
+ "devDependencies": {
43
+ "@types/node": "^16",
44
+ "rimraf": "^6",
45
+ "typescript": "^6",
46
+ "tsc-watch": "^6"
47
+ }
48
+ }
49
+ ```
50
+
51
+ ---
52
+
53
+ ## tsconfig.json
54
+
55
+ ```json
56
+ {
57
+ "compilerOptions": {
58
+ "experimentalDecorators": true,
59
+ "emitDecoratorMetadata": true,
60
+ "target": "ES2020",
61
+ "module": "commonjs",
62
+ "types": ["node"],
63
+ "esModuleInterop": true,
64
+ "strict": true,
65
+ "sourceMap": true,
66
+ "rootDir": "src",
67
+ "outDir": "app"
68
+ },
69
+ "include": ["src/**/*"]
70
+ }
71
+ ```
72
+
73
+ ---
74
+
75
+ ## .env(开发环境)
76
+
77
+ ```bash
78
+ APP_NAME=myapp
79
+ NODE_ENV=development
80
+ DEBUG=*
81
+ LOG_DIR=./logs
82
+ ```
83
+
84
+ ---
85
+
86
+ ## .gitignore
87
+
88
+ ```
89
+ .env
90
+ app/
91
+ logs/
92
+ node_modules/
93
+ ```
94
+
95
+ ---
96
+
97
+ ## src/index.ts(入口文件)
98
+
99
+ ```ts
100
+ import { create } from 'zenweb';
101
+
102
+ create({
103
+ controller: {
104
+ discoverPaths: ['./controller'],
105
+ autoControllerPrefix: true,
106
+ },
107
+ }).start();
108
+ ```
109
+
110
+ ---
111
+
112
+ ## src/controller/index.ts(根路由)
113
+
114
+ ```ts
115
+ export class IndexController {
116
+ index() {
117
+ return 'Hello ZenWeb!';
118
+ }
119
+ }
120
+ ```
121
+
122
+ ---
123
+
124
+ ## src/controller/user.ts(示例控制器)
125
+
126
+ ```ts
127
+ import { Get, Post, Context, $param, $body } from 'zenweb';
128
+ import { UserService } from '../service/user';
129
+
130
+ export class UserController {
131
+ constructor(private ctx: Context) {}
132
+
133
+ @Get()
134
+ list(service: UserService) {
135
+ return service.list();
136
+ }
137
+
138
+ @Get('/:id')
139
+ async detail() {
140
+ const { id } = await $param.get({ id: '!int' });
141
+ return { id };
142
+ }
143
+
144
+ @Post()
145
+ async create(service: UserService) {
146
+ const data = await $body.get({ name: '!string', email: 'string' });
147
+ return service.create(data);
148
+ }
149
+ }
150
+ ```
151
+
152
+ ---
153
+
154
+ ## src/service/user.ts(示例服务)
155
+
156
+ ```ts
157
+ import { Injectable, Context } from 'zenweb';
158
+
159
+ @Injectable
160
+ export class UserService {
161
+ constructor(private ctx: Context) {}
162
+
163
+ list() {
164
+ return [];
165
+ }
166
+
167
+ create(data: { name: string; email?: string }) {
168
+ return { ...data, ip: this.ctx.ip };
169
+ }
170
+ }
171
+ ```
172
+
173
+ ---
174
+
175
+ ## src/message-codes.json(错误消息)
176
+
177
+ ```json
178
+ {
179
+ "user.notfound": "用户不存在",
180
+ "user.login.fail": "登录失败: {reason}"
181
+ }
182
+ ```
183
+
184
+ ---
185
+
186
+ ## 命名规范
187
+
188
+ | 类型 | 文件名 | 导出名 |
189
+ |------|--------|--------|
190
+ | 控制器 | `{name}.ts` | `{Name}Controller` |
191
+ | 服务 | `{name}.ts` | `{Name}Service` |
192
+ | 类型定义 | `types.ts` | 自由命名 |
193
+
194
+ ---
195
+
196
+ ## 路由映射规则(autoControllerPrefix: true)
197
+
198
+ | 文件路径 | 路由前缀 |
199
+ |----------|----------|
200
+ | `controller/index.ts` | `/` |
201
+ | `controller/user.ts` | `/user` |
202
+ | `controller/admin/index.ts` | `/admin` |
203
+ | `controller/admin/user.ts` | `/admin/user` |
204
+
205
+ ---
206
+
207
+ ## 可选模块扩展
208
+
209
+ 询问用户是否需要以下可选模块,如需要则安装并阅读对应模块的 AGENTS.md 文档进行配置:
210
+
211
+ | 模块 | 作用 |
212
+ |------|------|
213
+ | `@zenweb/cors` | 跨域支持 |
214
+ | `@zenweb/sentry` | Sentry 错误收集 |
215
+ | `@zenweb/metric` | 运行健康信息 |
216
+ | `@zenweb/mysql` | MySQL 数据库 |
217
+ | `@zenweb/tenant` | 多租户数据库连接池 |
218
+ | `@zenweb/orm` | ORM 支持 |
219
+ | `@zenweb/template` | 模版渲染 |
220
+ | `@zenweb/schedule` | 定时任务 |
221
+ | `@zenweb/upload` | 文件上传 |
222
+ | `@zenweb/cache` | Redis 缓存支持 |
223
+ | `@zenweb/cache-opt` | Redis 缓存优化 |
224
+ | `@zenweb/msgpack` | MessagePack 输出 |
225
+ | `@zenweb/ratelimit` | 请求量控制(防CC攻击) |
226
+ | `@zenweb/websocket` | WebSocket 支持 |
227
+ | `@zenweb/xml-body` | XML Body 解析 |
228
+ | `@zenweb/form` | 表单构建 |
229
+ | `@zenweb/grid` | 数据表渲染 |
230
+
231
+ **配置指引:** 安装后阅读 `node_modules/{模块名}/AGENTS.md` 获取详细配置说明。
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Core } from '@zenweb/core';
2
- import { CreateOptions } from './types.js';
2
+ import { CreateOptions } from './types';
3
3
  export { Init, Inject, Injectable, $getInstance } from '@zenweb/inject';
4
4
  export { Router, RouterMethod, RouterPath } from '@zenweb/router';
5
5
  export { ResultFail, fail } from '@zenweb/result';
package/dist/index.js CHANGED
@@ -1,46 +1,94 @@
1
- import inject from '@zenweb/inject';
2
- import meta from '@zenweb/meta';
3
- import log from '@zenweb/log';
4
- import router from '@zenweb/router';
5
- import messagecode from '@zenweb/messagecode';
6
- import body from '@zenweb/body';
7
- import result from '@zenweb/result';
8
- import helper from '@zenweb/helper';
9
- import controller from '@zenweb/controller';
10
- import { Core, $initCore } from '@zenweb/core';
11
- export { Init, Inject, Injectable, $getInstance } from '@zenweb/inject';
12
- export { Router } from '@zenweb/router';
13
- export { ResultFail, fail } from '@zenweb/result';
14
- export { Controller, Mapping, Get, Post, Put, Patch, Delete, All, } from '@zenweb/controller';
15
- export { Context, SetupHelper, $getCore, $getContext, $core, $ctx, $debug, createDebug, } from '@zenweb/core';
16
- export { Body, ObjectBody, BodyHelper, RawBody, TextBody, useBodyParser, $body, $getTextBody, $getRawBody, $getObjectBody, } from '@zenweb/body';
17
- export { QueryHelper, TypeCastHelper, ParamHelper, $param, $query, $helperBase, } from '@zenweb/helper';
18
- export { $log, $getLogger, } from '@zenweb/log';
19
- export { Core, };
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Core = exports.$getLogger = exports.$log = exports.$helperBase = exports.$query = exports.$param = exports.ParamHelper = exports.TypeCastHelper = exports.QueryHelper = exports.$getObjectBody = exports.$getRawBody = exports.$getTextBody = exports.$body = exports.useBodyParser = exports.TextBody = exports.RawBody = exports.BodyHelper = exports.ObjectBody = exports.Body = exports.createDebug = exports.$debug = exports.$ctx = exports.$core = exports.$getContext = exports.$getCore = exports.SetupHelper = exports.Context = exports.All = exports.Delete = exports.Patch = exports.Put = exports.Post = exports.Get = exports.Mapping = exports.Controller = exports.fail = exports.ResultFail = exports.Router = exports.$getInstance = exports.Injectable = exports.Inject = exports.Init = void 0;
7
+ exports.create = create;
8
+ const inject_1 = __importDefault(require("@zenweb/inject"));
9
+ const meta_1 = __importDefault(require("@zenweb/meta"));
10
+ const log_1 = __importDefault(require("@zenweb/log"));
11
+ const router_1 = __importDefault(require("@zenweb/router"));
12
+ const messagecode_1 = __importDefault(require("@zenweb/messagecode"));
13
+ const body_1 = __importDefault(require("@zenweb/body"));
14
+ const result_1 = __importDefault(require("@zenweb/result"));
15
+ const helper_1 = __importDefault(require("@zenweb/helper"));
16
+ const controller_1 = __importDefault(require("@zenweb/controller"));
17
+ const core_1 = require("@zenweb/core");
18
+ Object.defineProperty(exports, "Core", { enumerable: true, get: function () { return core_1.Core; } });
19
+ var inject_2 = require("@zenweb/inject");
20
+ Object.defineProperty(exports, "Init", { enumerable: true, get: function () { return inject_2.Init; } });
21
+ Object.defineProperty(exports, "Inject", { enumerable: true, get: function () { return inject_2.Inject; } });
22
+ Object.defineProperty(exports, "Injectable", { enumerable: true, get: function () { return inject_2.Injectable; } });
23
+ Object.defineProperty(exports, "$getInstance", { enumerable: true, get: function () { return inject_2.$getInstance; } });
24
+ var router_2 = require("@zenweb/router");
25
+ Object.defineProperty(exports, "Router", { enumerable: true, get: function () { return router_2.Router; } });
26
+ var result_2 = require("@zenweb/result");
27
+ Object.defineProperty(exports, "ResultFail", { enumerable: true, get: function () { return result_2.ResultFail; } });
28
+ Object.defineProperty(exports, "fail", { enumerable: true, get: function () { return result_2.fail; } });
29
+ var controller_2 = require("@zenweb/controller");
30
+ Object.defineProperty(exports, "Controller", { enumerable: true, get: function () { return controller_2.Controller; } });
31
+ Object.defineProperty(exports, "Mapping", { enumerable: true, get: function () { return controller_2.Mapping; } });
32
+ Object.defineProperty(exports, "Get", { enumerable: true, get: function () { return controller_2.Get; } });
33
+ Object.defineProperty(exports, "Post", { enumerable: true, get: function () { return controller_2.Post; } });
34
+ Object.defineProperty(exports, "Put", { enumerable: true, get: function () { return controller_2.Put; } });
35
+ Object.defineProperty(exports, "Patch", { enumerable: true, get: function () { return controller_2.Patch; } });
36
+ Object.defineProperty(exports, "Delete", { enumerable: true, get: function () { return controller_2.Delete; } });
37
+ Object.defineProperty(exports, "All", { enumerable: true, get: function () { return controller_2.All; } });
38
+ var core_2 = require("@zenweb/core");
39
+ Object.defineProperty(exports, "Context", { enumerable: true, get: function () { return core_2.Context; } });
40
+ Object.defineProperty(exports, "SetupHelper", { enumerable: true, get: function () { return core_2.SetupHelper; } });
41
+ Object.defineProperty(exports, "$getCore", { enumerable: true, get: function () { return core_2.$getCore; } });
42
+ Object.defineProperty(exports, "$getContext", { enumerable: true, get: function () { return core_2.$getContext; } });
43
+ Object.defineProperty(exports, "$core", { enumerable: true, get: function () { return core_2.$core; } });
44
+ Object.defineProperty(exports, "$ctx", { enumerable: true, get: function () { return core_2.$ctx; } });
45
+ Object.defineProperty(exports, "$debug", { enumerable: true, get: function () { return core_2.$debug; } });
46
+ Object.defineProperty(exports, "createDebug", { enumerable: true, get: function () { return core_2.createDebug; } });
47
+ var body_2 = require("@zenweb/body");
48
+ Object.defineProperty(exports, "Body", { enumerable: true, get: function () { return body_2.Body; } });
49
+ Object.defineProperty(exports, "ObjectBody", { enumerable: true, get: function () { return body_2.ObjectBody; } });
50
+ Object.defineProperty(exports, "BodyHelper", { enumerable: true, get: function () { return body_2.BodyHelper; } });
51
+ Object.defineProperty(exports, "RawBody", { enumerable: true, get: function () { return body_2.RawBody; } });
52
+ Object.defineProperty(exports, "TextBody", { enumerable: true, get: function () { return body_2.TextBody; } });
53
+ Object.defineProperty(exports, "useBodyParser", { enumerable: true, get: function () { return body_2.useBodyParser; } });
54
+ Object.defineProperty(exports, "$body", { enumerable: true, get: function () { return body_2.$body; } });
55
+ Object.defineProperty(exports, "$getTextBody", { enumerable: true, get: function () { return body_2.$getTextBody; } });
56
+ Object.defineProperty(exports, "$getRawBody", { enumerable: true, get: function () { return body_2.$getRawBody; } });
57
+ Object.defineProperty(exports, "$getObjectBody", { enumerable: true, get: function () { return body_2.$getObjectBody; } });
58
+ var helper_2 = require("@zenweb/helper");
59
+ Object.defineProperty(exports, "QueryHelper", { enumerable: true, get: function () { return helper_2.QueryHelper; } });
60
+ Object.defineProperty(exports, "TypeCastHelper", { enumerable: true, get: function () { return helper_2.TypeCastHelper; } });
61
+ Object.defineProperty(exports, "ParamHelper", { enumerable: true, get: function () { return helper_2.ParamHelper; } });
62
+ Object.defineProperty(exports, "$param", { enumerable: true, get: function () { return helper_2.$param; } });
63
+ Object.defineProperty(exports, "$query", { enumerable: true, get: function () { return helper_2.$query; } });
64
+ Object.defineProperty(exports, "$helperBase", { enumerable: true, get: function () { return helper_2.$helperBase; } });
65
+ var log_2 = require("@zenweb/log");
66
+ Object.defineProperty(exports, "$log", { enumerable: true, get: function () { return log_2.$log; } });
67
+ Object.defineProperty(exports, "$getLogger", { enumerable: true, get: function () { return log_2.$getLogger; } });
20
68
  /**
21
69
  * 创建应用实例
22
70
  * @param options 模块配置项
23
71
  */
24
- export function create(options) {
72
+ function create(options) {
25
73
  options = options || {};
26
- const core = (options.global !== false) ? $initCore(options.core) : new Core(options.core);
74
+ const core = (options.global !== false) ? (0, core_1.$initCore)(options.core) : new core_1.Core(options.core);
27
75
  if (options.meta !== false)
28
- core.setup(meta(options.meta));
76
+ core.setup((0, meta_1.default)(options.meta));
29
77
  if (options.inject !== false)
30
- core.setup(inject());
78
+ core.setup((0, inject_1.default)());
31
79
  if (options.log !== false)
32
- core.setup(log(options.log));
80
+ core.setup((0, log_1.default)(options.log));
33
81
  if (options.router !== false)
34
- core.setup(router());
82
+ core.setup((0, router_1.default)());
35
83
  if (options.result !== false)
36
- core.setup(result(options.result));
84
+ core.setup((0, result_1.default)(options.result));
37
85
  if (options.messagecode !== false)
38
- core.setup(messagecode(options.messagecode));
86
+ core.setup((0, messagecode_1.default)(options.messagecode));
39
87
  if (options.helper !== false)
40
- core.setup(helper(options.helper));
88
+ core.setup((0, helper_1.default)(options.helper));
41
89
  if (options.body !== false)
42
- core.setup(body(options.body));
90
+ core.setup((0, body_1.default)(options.body));
43
91
  if (options.controller !== false)
44
- core.setup(controller(options.controller));
92
+ core.setup((0, controller_1.default)(options.controller));
45
93
  return core;
46
94
  }
package/dist/types.js CHANGED
@@ -1 +1,2 @@
1
- export {};
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json CHANGED
@@ -1,17 +1,18 @@
1
1
  {
2
2
  "name": "zenweb",
3
- "type": "module",
4
- "version": "6.3.0",
3
+ "version": "6.5.0",
5
4
  "description": "Modular lightweight web framework based on Koa",
6
5
  "main": "dist/index.js",
7
6
  "typings": "./dist/index.d.ts",
8
7
  "files": [
8
+ "AGENTS.md",
9
+ "TEMPLATE.md",
9
10
  "dist"
10
11
  ],
11
12
  "scripts": {
12
- "build": "rimraf dist && tsc",
13
+ "build": "rimraf dist && tsc -p tsconfig.build.json",
13
14
  "prepack": "npm run build",
14
- "dev": "cd example && node --env-file=.env --loader=ts-node/esm index.ts"
15
+ "dev": "cd example && node --env-file=.env -r ts-node/register index.ts"
15
16
  },
16
17
  "author": {
17
18
  "name": "YeFei",
@@ -28,24 +29,24 @@
28
29
  "license": "MIT",
29
30
  "homepage": "https://zenweb.node.ltd",
30
31
  "dependencies": {
31
- "@zenweb/body": "^5.3.0",
32
- "@zenweb/controller": "^6.3.0",
33
- "@zenweb/core": "^5.2.1",
34
- "@zenweb/helper": "^5.3.0",
35
- "@zenweb/inject": "^5.3.0",
36
- "@zenweb/log": "^5.1.0",
37
- "@zenweb/messagecode": "^5.3.0",
38
- "@zenweb/meta": "^5.1.1",
39
- "@zenweb/result": "^5.2.0",
40
- "@zenweb/router": "^6.4.0"
32
+ "@zenweb/body": "^5.5.0",
33
+ "@zenweb/controller": "^6.6.0",
34
+ "@zenweb/core": "^5.4.0",
35
+ "@zenweb/helper": "^5.5.0",
36
+ "@zenweb/inject": "^5.5.0",
37
+ "@zenweb/log": "^5.3.1",
38
+ "@zenweb/messagecode": "^5.6.0",
39
+ "@zenweb/meta": "^5.3.0",
40
+ "@zenweb/result": "^5.4.0",
41
+ "@zenweb/router": "^6.6.0"
41
42
  },
42
43
  "devDependencies": {
43
- "@types/node": "^20.19.39",
44
+ "@types/node": "^16.18.126",
44
45
  "rimraf": "^4.4.1",
45
46
  "ts-node": "^10.9.2",
46
- "typescript": "^5.9.3"
47
+ "typescript": "^6.0.3"
47
48
  },
48
49
  "engines": {
49
- "node": ">=20"
50
+ "node": ">=16"
50
51
  }
51
52
  }