# aifei-ts **Repository Path**: xiaobo88/aifei-ts ## Basic Information - **Project Name**: aifei-ts - **Description**: Aifei 框架 TypeScript 极简移植 — Just Service for AI Coding。砍掉 Controller/DTO/Mapper,单层 @Path Service 即接口。装饰器/反射 DI/声明式 SQL/事务自动回滚/WS推送/multipart/MCP 工具自动注册。 - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-05-06 - **Last Updated**: 2026-05-06 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # aifei-ts > Aifei 框架的 TypeScript 极简移植 — **Just Service**,为 AI Coding 设计。 > 单层抽象、零样板、声明式 SQL。NestJS 是"轻量 Spring";本项目是"AI 时代的极简框架"。 --- ## 设计目标 把 Aifei (Java) 的 **17 项灵魂用法** 用 TS 等价表达: | Aifei (Java) | aifei-ts | 状态 | |---|---|---| | `@Path("/vip")` 注解 | `@Path('/vip')` 装饰器 | ✅ | | `@Inject` 字段注入 | `@Inject` PropertyDecorator | ✅ | | `@Before(Interceptor.class)` | `@Before(fn)` ClassDecorator | ✅ | | `@RequireRole` | `@RequireRole('admin')` | ✅ | | `@NoPath` | `@NoPath` 排除路由 | ✅ | | `@Para('keyword')` | `@Para('keyword')` ParameterDecorator | ✅ | | AifeiConfig 三段配置 | `Config { configSettings/Routes/Plugins }` | ✅ | | HIO 三件套 | `Input/Output/Handler` interfaces | ✅ | | 4 层拦截器 | Routes / Global / Class / Method 全保留 | ✅ | | 方法级 DI | 反射 + 参数名解析(fn.toString) | ✅ | | 自定义 Argument | `registerArgument(Type, resolver)` | ✅ | | 路径参数 | `input.pathPara(s)` + `getStrAt(i)` | ✅ | | Out + RollbackDecision | `Out.fail()` + `shouldRollback()` 自动回滚 | ✅ | | `#where/#and/#orderBy` | 自实现预处理器(含白名单) | ✅ | | `#para(name)` | ✅ | ✅ | | Plugin 生命周期 | `Plugin { start; stop }` | ✅ | | `setOnActionCreated` | 启动期自动收集所有 Action | ✅ | | Action 重载(同 path 多方法) | ❌ 不支持(TS 无方法重载) | — | | cglib 字节码代理 | ❌ 不需要(TS 用接口装饰,Action 拦截器走链) | — | --- ## 安装运行 ```bash cd aifei-ts npm install npm run demo # 启动 demo @ http://localhost:3000 ``` 或编译后跑: ```bash npm run build node dist/examples/demo/index.js ``` --- ## 5 行 Hello World ```ts import { start, Path, Config, Settings, Routes, Plugins } from 'aifei-ts'; @Path('/') class HelloService { @Path('hello') hello() { return 'Hello Aifei-TS!'; } } class AppConfig implements Config { configSettings(s: Settings) { s.setPort(3000); } configRoutes(r: Routes) { r.scan(new HelloService()); } configPlugins(_p: Plugins) {} } start(new AppConfig()); ``` `curl http://localhost:3000/hello` → `{"code":0,"msg":"ok","data":"Hello Aifei-TS!"}` --- ## CRUD 范例(体现 Just Service) ```ts @Path('/vip') class VipService { /** GET /vip?keyword=&pageNum=1&pageSize=10 */ index(filter: any, pageNum?: number, pageSize?: number) { const sql = `select * from vip #where(name, 'like', kw) #and(level, '=', levelId) #orderBy(id, balance, created)`; if (filter.keyword) filter.kw = `%${filter.keyword}%`; return Db.sql(sql, filter).paginate(pageNum ?? 1, pageSize ?? 10); } get(id: number) { return Db.sql('select * from vip where id = ?', [id]).findFirst(); } @RequireRole('admin') save(@Body vip: Vip) { if (!vip.id) Db.insert('vip', vip); else { Db.deleteWhere('vip', r => r.id === vip.id); Db.insert('vip', vip); } return Out.ok('保存成功', vip); } @RequireRole('admin') delete(id: number) { return Db.transaction(() => { const n = Db.deleteWhere('vip', r => r.id === id); return n === 1 ? Out.ok('删除成功') : Out.fail('会员不存在'); // ← Out.fail 触发回滚 }); } } ``` 整个 CRUD = **1 个 class + 4 个方法**。无 Controller、无 DTO、无 Mapper。 --- ## 与 NestJS 对比 | 维度 | NestJS | aifei-ts | |---|---|---| | 层级 | Controller + Service + DTO + Module | **只有 @Path Service** | | 依赖注入 | @Module imports/providers/exports 拓扑 | `@Inject` 字段、容器自动 | | 数据访问 | TypeORM/Prisma 多套 ORM | `Db.sql(...)` + `#where` 单一入口 | | 事务回滚 | 手动 `try/catch + rollback()` | `Out.fail()` 自动 | | 路由声明 | @Controller + @Get/@Post + @Param/@Body | `@Path + 公开方法` | | 启动 | NestFactory.create + listen | `start(new AppConfig())` | | 注意力浓度 | ~30%(大量框架仪式) | ~80%(只剩业务) | --- ## 项目结构 ``` aifei-ts/ ├─ package.json / tsconfig.json ├─ src/ │ ├─ aifei.ts # start/stop 入口(30 行) │ ├─ config.ts # AifeiConfig + Settings + Routes + Plugins(80 行) │ ├─ context.ts # Input / Output / Out / BizException(70 行) │ ├─ decorators.ts # @Path/@Inject/@Before/@Para/@Body/@RequireRole/@NoPath(80 行) │ ├─ router.ts # Action + Router + scanner(150 行) │ ├─ argument.ts # 方法级 DI(80 行) │ ├─ handler.ts # ActionHandler + ExceptionHandler + chain(80 行) │ ├─ interceptor.ts # Invocation + 拦截器链(40 行) │ ├─ plugin.ts # Plugin interface(5 行) │ ├─ aop.ts # 简易 IoC 容器(30 行) │ ├─ http-server.ts # Node http + WebIn + WebOut(160 行) │ ├─ db.ts # Db.sql + #where 预处理 + 内存表(150 行) │ └─ index.ts # public exports(25 行) └─ examples/demo/ ├─ index.ts # 入口 AppConfig ├─ services/ # HelloService + VipService └─ models/ # Vip POJO ``` **核心代码量:~960 行 TS**,零运行时依赖(仅 `reflect-metadata`)。 --- ## #where / #and / #orderBy 语义 ```ts const sql = `select * from user #where(name, 'like', kw) -- kw 为 null 时整条不输出 #and(age, '>=', minAge) -- 同上 #orderBy(id, name, age) -- 白名单防注入 `; Db.sql(sql, { kw: '%james%', minAge: 18, orderBy: { field: 'age', order: 'desc' } }).find(); // 实际生成: // select * from user where name like ? and age >= ? order by age desc // values: ['%james%', 18] ``` 第一个真正生成的条件输出 `where`,其余 `and`。`orderBy` 字段必须在白名单内才生效——天然防 SQL 注入。 --- ## 扩展点速览 ```ts // 1) 自定义 Argument 注入器(如登录账号) import { registerArgument, Input } from 'aifei-ts'; registerArgument(Account, (action, idx, input: Input) => { const token = input.header('Token'); return resolveAccount(token); }); // Service 直接接收: @Path('/order') class OrderService { create(order: Order, loginUser: Account) { /* loginUser 自动注入 */ } } // 2) MCP 工具自动注册(setOnActionCreated) s.setOnActionCreated(action => { mcpServer.registerTool({ name: action.path.replace(/\//g, '_'), parameters: action.paramNames, }); }); // 3) Plugin 接入第三方(如 Redis) class RedisPlugin implements Plugin { start() { this.client = createClient(...); /* ping */ } stop() { this.client.quit(); } } ``` --- ## 限制与未做 | 项 | 说明 | |---|---| | Action 重载 | TS 无方法重载,同 path 多方法不支持(启动期报错) | | 真实数据库 | `db.ts` 是内存版;接 sqlite/pg 直接替换 `InMemoryStore` | | WebSocket | 未实现,可参照 Aifei 加 ws 依赖 | | 文件上传 | WebIn 仅支持 JSON body | | 事务真回滚 | 内存版仅打日志;真实 DB 实现需在 Db.transaction 里 BEGIN/COMMIT/ROLLBACK | | 测试 | 无单测(demo 即冒烟) | --- ## License Apache 2.0(与 Aifei 保持一致) --- ## 哲学 > "极简不是目标,而是结果。当你把所有不必要的东西都去掉之后,剩下的就是极简的。" —— 詹波 NestJS 是 TS 圈的"轻量 Spring";aifei-ts 是 TS 圈的"AI 时代答卷"。两者面向不同未来。