agent-workflow-kit-cli 1.3.2 → 1.3.4

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.
Files changed (51) hide show
  1. package/dist/cli/commands/add.js +3 -1
  2. package/dist/cli/commands/doctor.js +145 -47
  3. package/dist/cli/commands/init.js +6 -0
  4. package/dist/core/analyzer.js +70 -0
  5. package/dist/core/detector.js +22 -0
  6. package/package.json +1 -1
  7. package/templates/common/AGENTS.md.hbs +4 -0
  8. package/templates/common/GLOBAL_RULES.md +101 -0
  9. package/templates/devops/AGENTS.md.hbs +32 -0
  10. package/templates/devops/skills/devops/SKILL.md +477 -0
  11. package/templates/diagram/AGENTS.md.hbs +30 -0
  12. package/templates/diagram/skills/drawio-diagram/SKILL.md +427 -0
  13. package/templates/dotnet/AGENTS.md.hbs +38 -34
  14. package/templates/dotnet/rules/api-structure.md +15 -15
  15. package/templates/dotnet/rules/csharp-style.md +17 -17
  16. package/templates/dotnet/rules/dependency-injection.md +12 -12
  17. package/templates/dotnet/rules/error-handling-validation.md +15 -15
  18. package/templates/dotnet/skills/dotnet-controller/SKILL.md +16 -16
  19. package/templates/express/AGENTS.md.hbs +37 -33
  20. package/templates/express/rules/error-handling.md +18 -18
  21. package/templates/express/rules/express-style.md +19 -19
  22. package/templates/express/rules/router-controller.md +16 -16
  23. package/templates/express/skills/express-endpoint/SKILL.md +14 -14
  24. package/templates/fastapi/AGENTS.md.hbs +25 -3
  25. package/templates/fastapi/rules/api-testing.md +24 -0
  26. package/templates/fastapi/rules/database-async.md +26 -0
  27. package/templates/golang/AGENTS.md.hbs +42 -0
  28. package/templates/golang/rules/concurrency.md +71 -0
  29. package/templates/golang/rules/error-handling.md +42 -0
  30. package/templates/golang/rules/golang-style.md +24 -0
  31. package/templates/golang/rules/project-layout.md +39 -0
  32. package/templates/golang/skills/golang-db/SKILL.md +27 -0
  33. package/templates/golang/skills/golang-feature/SKILL.md +42 -0
  34. package/templates/nestjs/AGENTS.md.hbs +33 -29
  35. package/templates/nestjs/rules/module-architecture.md +14 -14
  36. package/templates/nestjs/rules/nestjs-style.md +12 -12
  37. package/templates/nestjs/rules/validation-errors.md +15 -15
  38. package/templates/nestjs/skills/nestjs-module/SKILL.md +15 -15
  39. package/templates/next-js/AGENTS.md.hbs +39 -35
  40. package/templates/next-js/rules/data-fetching-mutations.md +17 -17
  41. package/templates/next-js/rules/next-style.md +17 -17
  42. package/templates/next-js/rules/seo-metadata.md +18 -18
  43. package/templates/next-js/rules/server-client-components.md +17 -17
  44. package/templates/next-js/skills/next-feature/SKILL.md +16 -16
  45. package/templates/rust/AGENTS.md.hbs +41 -0
  46. package/templates/rust/rules/error-handling.md +36 -0
  47. package/templates/rust/rules/memory-concurrency.md +47 -0
  48. package/templates/rust/rules/project-layout.md +49 -0
  49. package/templates/rust/rules/rust-style.md +26 -0
  50. package/templates/rust/skills/rust-db/SKILL.md +27 -0
  51. package/templates/rust/skills/rust-feature/SKILL.md +34 -0
@@ -1,27 +1,27 @@
1
- # Quy Ước Viết Mã C# (C# Coding Style & Conventions)
1
+ # C# Coding Style & Conventions
2
2
 
3
- Tài liệu này đặc tả quy chuẩn coding style, đặt tên biến, tên lớp và cách tổ chức file nguồn trong dự án .NET.
3
+ This document specifies standard coding styles, naming patterns, and source file organization conventions in .NET projects.
4
4
 
5
5
  ---
6
6
 
7
- ## 🏷️ Quy Ước Đặt Tên (Naming Conventions)
7
+ ## 🏷️ Naming Conventions
8
8
 
9
- ### Quy tắc đặt tên Lớp và Thành phần
10
- - **PascalCase:** Áp dụng cho Class, Struct, Record, Enum, Interface, Method, Public Properties.
11
- - * dụ:* `UserService`, `GetActiveUsers()`, `CreatedDate`.
12
- - **Interface Prefix:** Tên Interface bắt buộc phải bắt đầu bằng chữ cái `I`.
13
- - * dụ:* `IUserService`, `IUserRepository`.
14
- - **camelCase:** Áp dụng cho tham số đầu vào của hàm (method arguments) các biến cục bộ (local variables).
15
- - * dụ:* `userId`, `requestPayload`.
16
- - **Private Fields Prefix:** Các trường dữ liệu private trong Class phải viết bằng camelCase bắt đầu bằng dấu gạch dưới `_`.
17
- - * dụ:* `private readonly IUserRepository _userRepository;`.
9
+ ### Class & Component Naming Rules
10
+ - **PascalCase:** Use for Classes, Structs, Records, Enums, Interfaces, Methods, and Public Properties.
11
+ - *Examples:* `UserService`, `GetActiveUsers()`, `CreatedDate`.
12
+ - **Interface Prefix:** Interface names must start with the uppercase letter `I`.
13
+ - *Examples:* `IUserService`, `IUserRepository`.
14
+ - **camelCase:** Use for method arguments and local variables.
15
+ - *Examples:* `userId`, `requestPayload`.
16
+ - **Private Fields Prefix:** Private fields inside classes must use `camelCase` and start with an underscore `_`.
17
+ - *Example:* `private readonly IUserRepository _userRepository;`.
18
18
 
19
19
  ---
20
20
 
21
- ## 📦 Tổ Chức Mã Nguồn & Định Dạng
22
- - **Namespaces:** Đặt namespace phản ánh cấu trúc thư mục của dự án để đảm bảo tính dễ tìm kiếm.
23
- - * dụ:* `ProjectName.Application.Services`.
24
- - **File Scoped Namespaces:** Sử dụng cú pháp namespace phạm vi file (File-scoped namespace) của C# 10+ để giảm cấp thụt lề thụt dòng không cần thiết:
21
+ ## 📦 File Structure & Formatting
22
+ - **Namespaces:** Match namespaces with the physical directory structure to ensure easy discovery.
23
+ - *Example:* `ProjectName.Application.Services`.
24
+ - **File-Scoped Namespaces:** Use C# 10+ file-scoped namespaces to reduce unnecessary indentation levels:
25
25
  ```csharp
26
26
  namespace ProjectName.Application.Services;
27
27
 
@@ -30,4 +30,4 @@ Tài liệu này đặc tả quy chuẩn coding style, đặt tên biến, tên
30
30
  // ...
31
31
  }
32
32
  ```
33
- - **Sắp xếp Usings:** Đặt các chỉ thị `using` hệ thống (`System.*`) lên trước, tiếp theo các thư viện bên thứ ba, cuối cùng các dự án nội bộ.
33
+ - **Sorting Usings:** Organize `using` directives by placing system namespaces (`System.*`) first, followed by third-party packages, and internal project dependencies last.
@@ -1,14 +1,14 @@
1
- # Đăng Ký & Sử Dụng Dependency Injection (DI)
1
+ # Dependency Injection (DI) Configurations
2
2
 
3
- Tài liệu này hướng dẫn cách cấu hình tiêm phụ thuộc trong các ứng dụng .NET Core.
3
+ This document details guidelines for configuring and consuming dependency injection in .NET Core applications.
4
4
 
5
5
  ---
6
6
 
7
- ## 💉 Constructor Injection (Tiêm qua Hàm khởi tạo)
8
- - **Quy tắc bắt buộc:** Luôn luôn giải quyết các phụ thuộc của Class thông qua Constructor. Gán chúng vào các trường private readonly tiền tố gạch dưới `_`.
9
- - Tuyệt đối không dùng Service Locator (không gọi `app.Services.GetService<T>()` hay tiêm `IServiceProvider` để lấy service động tại runtime).
7
+ ## 💉 Constructor Injection
8
+ - **Mandatory Rule:** Always resolve class dependencies using constructor parameters. Assign them to private readonly fields prefixed with an underscore `_`.
9
+ - Never use the Service Locator pattern (do not call `app.Services.GetService<T>()` or inject `IServiceProvider` to dynamically resolve services at runtime).
10
10
 
11
- * **Không hợp lệ (❌ Nghiêm cấm):**
11
+ * **Invalid (❌ Prohibited):**
12
12
  ```csharp
13
13
  public class OrderService
14
14
  {
@@ -26,7 +26,7 @@ Tài liệu này hướng dẫn cách cấu hình và tiêm phụ thuộc trong
26
26
  }
27
27
  }
28
28
  ```
29
- * **Hợp lệ (✔️ Khuyến khích):**
29
+ * **Valid (✔️ Recommended):**
30
30
  ```csharp
31
31
  public class OrderService : IOrderService
32
32
  {
@@ -47,8 +47,8 @@ Tài liệu này hướng dẫn cách cấu hình và tiêm phụ thuộc trong
47
47
 
48
48
  ---
49
49
 
50
- ## ⚙️ Đăng Ký Vòng Đời Dịch Vụ (Service Lifetimes)
51
- Lựa chọn đúng vòng đời khi đăng dịch vụ trong `Program.cs`:
52
- 1. **Transient (`AddTransient<I, T>()`):** Tạo mới mỗi khi được yêu cầu. Dành cho các dịch vụ nhẹ, không lưu trạng thái (Stateless Services).
53
- 2. **Scoped (`AddScoped<I, T>()`):** Tạo mới một lần cho mỗi HTTP Request. Thích hợp cho Repository, Database Context (`DbContext`), các dịch vụ nghiệp vụ.
54
- 3. **Singleton (`AddSingleton<I, T>()`):** Tạo một lần duy nhất cho toàn bộ vòng đời ứng dụng. Dành cho caching in-memory, cấu hình hệ thống, helper dùng chung.
50
+ ## ⚙️ Service Lifetimes Registration
51
+ Register dependencies with the appropriate lifetime scopes inside `Program.cs`:
52
+ 1. **Transient (`AddTransient<I, T>()`):** Instantiated every time they are requested. Use for lightweight, stateless services.
53
+ 2. **Scoped (`AddScoped<I, T>()`):** Instantiated once per HTTP request context. Recommended for repositories, database contexts (`DbContext`), and business services.
54
+ 3. **Singleton (`AddSingleton<I, T>()`):** Instantiated once and shared across the entire application lifetime. Use for in-memory caching, system configurations, and thread-safe helper services.
@@ -1,15 +1,15 @@
1
- # Xử Ngoại Lệ Tập Trung & Xác Thực Tự Động (FluentValidation)
1
+ # Unified Exception Handling & Automated Validation (FluentValidation)
2
2
 
3
- Tài liệu này quy định cấu hình xử ngoại lệ tập trung qua Middleware xác thực dữ liệu đầu vào bằng thư viện FluentValidation trong ứng dụng .NET.
3
+ This document defines configurations for centralized exception handling using Middleware and incoming request validation using the FluentValidation library in .NET applications.
4
4
 
5
5
  ---
6
6
 
7
- ## 🛡️ Xác Thực Dữ Liệu Tự Động Với FluentValidation
8
- - **Quy tắc:** Mọi API Request nhận dữ liệu phức tạp phải đi kèm một Validator kế thừa từ `AbstractValidator<T>` để định nghĩa các ràng buộc dữ liệu.
9
- - Cấu hình FluentValidation để tự động kiểm duyệt trả về lỗi 400 Bad Request cho Client nếu dữ liệu không khớp, tránh viết các câu lệnh `if` lặp lại.
7
+ ## 🛡️ Automated Validation with FluentValidation
8
+ - **Rule:** Every API request representing complex input data payloads must have a corresponding validator class inheriting from `AbstractValidator<T>` to declare validation rules.
9
+ - Configure FluentValidation to automatically intercept invalid requests and return an HTTP `400 Bad Request` payload to the client, preventing repetitive manual validation checks inside Controllers.
10
10
 
11
11
  ```csharp
12
- // dụ về một Validator
12
+ // Example of a Validator class
13
13
  using FluentValidation;
14
14
 
15
15
  public class CreateCourseRequestValidator : AbstractValidator<CreateCourseRequestDto>
@@ -17,32 +17,32 @@ Tài liệu này quy định cấu hình xử lý ngoại lệ tập trung qua M
17
17
  public CreateCourseRequestValidator()
18
18
  {
19
19
  RuleFor(x => x.Title)
20
- .NotEmpty().WithMessage("Tiêu đề khóa học không được để trống.")
21
- .MaximumLength(150).WithMessage("Tiêu đề không được vượt quá 150 ký tự.");
20
+ .NotEmpty().WithMessage("Course title cannot be empty.")
21
+ .MaximumLength(150).WithMessage("Title must not exceed 150 characters.");
22
22
 
23
23
  RuleFor(x => x.Price)
24
- .GreaterThanOrEqualTo(0).WithMessage("Giá khóa học không được nhỏ hơn 0.");
24
+ .GreaterThanOrEqualTo(0).WithMessage("Course price cannot be less than 0.");
25
25
  }
26
26
  }
27
27
  ```
28
28
 
29
29
  ---
30
30
 
31
- ## 🚨 Xử Lỗi Tập Trung (Global Exception Middleware)
32
- - **Quy tắc:** Tuyệt đối không để lộ các ngoại lệ thô của hệ thống (lỗi DB, stack traces) cho Client với lỗi 500.
33
- - Xây dựng một Middleware toàn cục (`ExceptionHandlingMiddleware`) hoặc sử dụng tính năng `IExceptionHandler` trong .NET 8+ để bắt toàn bộ các lỗi xảy ra trong ứng dụng và định dạng lại thành cấu trúc JSON chuẩn:
31
+ ## 🚨 Centralized Exception Handling (Global Exception Middleware)
32
+ - **Rule:** Never expose raw system exceptions (such as database faults, file system errors, or stack traces) directly to clients as HTTP 500 errors.
33
+ - Build a global middleware (`ExceptionHandlingMiddleware`) or implement `IExceptionHandler` in .NET 8+ to intercept all unhandled exceptions and format them into a standard JSON payload:
34
34
 
35
35
  ```json
36
36
  {
37
37
  "success": false,
38
38
  "statusCode": 500,
39
39
  "timestamp": "2026-06-13T07:42:00.000Z",
40
- "message": "Đã xảy ra lỗi hệ thống. Vui lòng liên hệ quản trị viên."
40
+ "message": "An internal server error occurred. Please contact the administrator."
41
41
  }
42
42
  ```
43
43
 
44
44
  ```csharp
45
- // Cấu trúc Exception Handling Middleware tiêu chuẩn
45
+ // Standard Global Exception Handling Middleware
46
46
  public class ExceptionHandlingMiddleware
47
47
  {
48
48
  private readonly RequestDelegate _next;
@@ -77,7 +77,7 @@ Tài liệu này quy định cấu hình xử lý ngoại lệ tập trung qua M
77
77
  success = false,
78
78
  statusCode = context.Response.StatusCode,
79
79
  timestamp = DateTime.UtcNow,
80
- message = "Đã xảy ra lỗi hệ thống. Vui lòng liên hệ quản trị viên."
80
+ message = "An internal server error occurred. Please contact the administrator."
81
81
  };
82
82
 
83
83
  return context.Response.WriteAsJsonAsync(response);
@@ -1,24 +1,24 @@
1
1
  ---
2
2
  name: dotnet-controller
3
- description: Sinh hoặc mở rộng một API Controller ASP.NET Core mới cùng DTOs, FluentValidation Service interface tương ứng
3
+ description: Scaffold or extend an ASP.NET Core API Controller with corresponding DTOs, FluentValidation, and Service interfaces
4
4
  ---
5
5
 
6
- Tuân thủ quy trình này để tạo mới một API Endpoint hoặc Controller trong .NET (C#).
6
+ Follow this process to generate a new API Endpoint or Controller in .NET (C#).
7
7
 
8
- Đầu vào (Inputs):
9
- - controllerName: Tên của Controller ( dụ: `CoursesController`)
10
- - routePath: Tuyến định tuyến HTTP ( dụ: `api/v1/courses`)
11
- - requestDtoName: Tên lớp Request DTO ( dụ: `CreateCourseRequestDto`)
12
- - functionality: Tóm tắt yêu cầu nghiệp vụ các phương thức cần xử lý
8
+ Inputs:
9
+ - controllerName: Name of the Controller (e.g., `CoursesController`)
10
+ - routePath: HTTP route mapping (e.g., `api/v1/courses`)
11
+ - requestDtoName: Class name of the request DTO (e.g., `CreateCourseRequestDto`)
12
+ - functionality: Summary of the business requirements and methods to process
13
13
 
14
- Các bước thực hiện (Steps):
15
- 1. Khai báo các lớp Request/Response DTOs tương ứng bên trong tầng Application (hoặc thư mục `DTOs` của dự án).
16
- 2. Xây dựng một lớp Validator kế thừa từ `AbstractValidator<T>` bằng FluentValidation bên dưới Application layer để kiểm tra ràng buộc dữ liệu.
17
- 3. Định nghĩa Service Interface ( dụ: `ICourseService`) lớp triển khai cụ thể (`CourseService`) tầng Application/Core để xử business logic.
18
- 4. Đăng Service nghiệp vụ vừa tạo vào Dependency Injection container (Scoped lifetime) trong file `Program.cs`.
19
- 5. Tạo lớp Controller kế thừa từ `ControllerBase` được đánh dấu bằng các attribute `[ApiController]` `[Route]`.
20
- 6. Sử dụng Constructor Injection để tiêm Service Interface vào Controller gọi phương thức xử lý thích hợp, ánh xạ kết quả trả về thông qua các `IActionResult` (như `Ok()`, `Created()`, `BadRequest()`).
21
- 7. Viết unit test cho Service Controller bằng xUnit Moq.
22
- 8. Chạy kiểm tra lỗi biên dịch cục bộ:
14
+ Steps:
15
+ 1. Declare the corresponding Request/Response DTO classes inside the Application layer (or the project's `DTOs` directory).
16
+ 2. Create a Validator class inheriting from FluentValidation's `AbstractValidator<T>` in the Application layer to define data constraints.
17
+ 3. Define the Service Interface (e.g., `ICourseService`) and its concrete implementation class (`CourseService`) in the Application layer to handle business logic.
18
+ 4. Register the new Service in the Dependency Injection container (using Scoped lifetime) inside the `Program.cs` configuration file.
19
+ 5. Create the Controller class inheriting from `ControllerBase`, decorated with `[ApiController]` and `[Route]` attributes.
20
+ 6. Use Constructor Injection to inject the Service Interface into the Controller, delegate request processing, and map responses to appropriate `IActionResult` objects (e.g., `Ok()`, `Created()`, `BadRequest()`).
21
+ 7. Write unit tests for the Service and Controller using xUnit and Moq.
22
+ 8. Execute compilation and testing:
23
23
  - `dotnet build`
24
24
  - `dotnet test`
@@ -1,41 +1,45 @@
1
- ## 🗺️ Hướng Dẫn Phát Triển Express.js (Node.js Backend)
2
-
3
- ### 🔄 Vòng Đời Phát Triển Tác Nhân (Agent Development Lifecycle)
4
- Tác nhân AI phải thực hiện tất cả các nhiệm vụ Express.js theo quy trình 5 bước sau:
5
- 1. **Thiết kế & Lập trình:** Phân tách nguồn theo cấu trúc 3 lớp ràng (3-Tier Architecture). Tuyệt đối cấm viết mã nguồn lộn xộn (Spaghetti Code).
6
- 2. **Kiểm thử Toàn diện:** Viết unit test cho các Service sử dụng Jest kiểm thử tích hợp API sử dụng Supertest.
7
- 3. **Chất lượng Mã nguồn:** Chạy các lệnh kiểm tra lỗi pháp kiểu dữ liệu:
8
- - Kiểm tra Lint: `{{runCommand}} lint`
9
- - Kiểm tra Kiểu dữ liệu: `{{runCommand}} typecheck`
10
- - Chạy Kiểm thử: `{{runCommand}} test` (hoặc `{{runCommand}} test -- --run` cho môi trường CI/CD)
11
- - Chạy Build thử nghiệm: `{{runCommand}} build`
12
- 4. **Quản lý Thư viện:** Cài đặt các thư viện mới bằng lệnh: `{{packageManager}} add [tên_thư_viện]`. Tuyệt đối cấm sửa thủ công file lock `{{lockFile}}`.
1
+ ## 🗺️ Express.js Development Guide (Node.js Backend)
2
+
3
+ ### 🔄 Agent Development Lifecycle
4
+ The AI Agent must execute all Express.js tasks following this structured 5-stage lifecycle:
5
+ 1. **Design & Code:** Organize code according to a clean 3-tier architecture as detailed in `@router-controller.md`. Spaghetti code is strictly prohibited.
6
+ 2. **Comprehensive Testing:** Write unit tests for Services using Jest, and test API integrations using Supertest.
7
+ 3. **Troubleshooting & Debugging:** When debugging async router handlers or validation payloads, verify error forwarding is properly configured.
8
+ 4. **Code Quality & Review:** Perform self-review using `@error-handling.md` to ensure errors are captured globally and validation uses Zod schemas. Check style rules in `@express-style.md`.
9
+ 5. **Production Readiness:** Verify compilation and static analysis checks pass without errors.
13
10
 
14
11
  ---
15
12
 
16
- ### 🏗️ Kiến Trúc Hệ Thống Bản Mẫu (Template Blueprint)
17
- Vui lòng tham khảo các tài liệu quy tắc chi tiết dưới đây:
18
- - Quy ước viết sạch, định nghĩa kiểu dữ liệu tường minh bằng TypeScript trong môi trường Express: `@express-style.md`
19
- - Phân định ranh giới trách nhiệm: Router nhận diện đường dẫn $\rightarrow$ Controller điều phối $\rightarrow$ Service xử lý core logic: `@router-controller.md`
20
- - Chiến lược xử lý lỗi bất đồng bộ (Async Error Catching) chế vận hành Middleware xử lý lỗi tập trung: `@error-handling.md`
21
- - Workflow chuẩn hóa giúp sinh mới một cụm API Endpoint an toàn, đầy đủ từ Router, Controller đến Validator: `@SKILL.md`
13
+ ### 🏗️ Template Blueprint
14
+ Refer to the detailed rules below:
15
+ - Clean coding style and type safety using TypeScript in Express: `@express-style.md`
16
+ - Separation of concerns: Router mappings $\rightarrow$ Controller delegation $\rightarrow$ Service execution: `@router-controller.md`
17
+ - Async error catching strategies and centralized global error handling middleware: `@error-handling.md`
18
+ - Process to scaffold new API endpoints cleanly from Routers to Validators: `@express-endpoint`
22
19
 
23
20
  ---
24
21
 
25
- ### 🏛️ Quy Tắc Phát Triển Nghiêm Ngặt
22
+ ### 🏛️ Strict Development Rules
26
23
 
27
- #### 1. Phân Tách Lớp Tuyệt Đối (Strict Layer Separation)
28
- Tác nhân phải tuân thủ nghiêm ngặt chuỗi truyền dẫn dữ liệu:
24
+ #### 1. Strict Layer Separation
25
+ Strictly comply with the data flow chain:
29
26
  $$\text{Client} \longrightarrow \text{Router} \longrightarrow \text{Middleware} \longrightarrow \text{Controller} \longrightarrow \text{Service} \longrightarrow \text{Model/Database}$$
30
- - **Router:** Tuyệt đối không chứa logic xử lý, chỉ ánh xạ HTTP Method + Path liên kết middleware xác thực/kiểm duyệt.
31
- - **Controller:** Chỉ bóc tách dữ liệu từ `req` (req.body, req.query, req.params), gọi lớp Service xử lý, nhận kết quả và trả về thông qua `res.status().json()`. Không làm việc trực tiếp với cơ sở dữ liệu.
32
- - **Service:** Nơi chứa logic nghiệp vụ, tính toán thuật toán, tương tác với lớp DB Model. Tuyệt đối không được tiếp xúc hay phụ thuộc vào các đối tượng `req` hay `res` của Express để đảm bảo tính độc lập khi viết Unit Test.
33
-
34
- #### 2. Bẫy Lỗi Bất Đồng Bộ (Async Error Handling)
35
- - **Không dùng try/catch thủ công tại Controller:** Việc viết try/catch mọi hàm trong tất cả các controller gây loãng mã nguồn.
36
- - **Sử dụng Wrapper Tự động:** Toàn bộ các hàm controller bất đồng bộ phải được bọc bằng một hàm tiện ích tự động bắt lỗi (như `express-async-handler`) để tự động chuyển tiếp tất cả các ngoại lệ phát sinh sang cấu phần `next()`.
37
- - **Middleware xử lý lỗi tập trung (Global Error Handler):** Bắt buộc phải khai báo middleware xử lỗi đủ 4 tham số ở cuối tệp cấu hình server (sau khi khai báo tất cả các routes) để định dạng lại toàn bộ phản hồi lỗi.
38
-
39
- #### 3. Kiểm Thử Dữ Liệu Tự Động Với Zod Middleware
40
- - **Cấm Validate thủ công bằng câu lệnh điều kiện:** Không viết các đoạn code `if (!req.body.email)`.
41
- - **Xây dựng Middleware Validate Schema:** Phát triển một middleware dùng chung nhận vào một Schema của Zod để tự động kiểm duyệt toàn bộ dữ liệu đầu vào (body, query, params) trước khi cho phép dữ liệu đi sâu vào tầng Controller.
27
+ - **Router:** Must not contain processing logic. Only maps HTTP methods + paths and registers auth/validation middlewares.
28
+ - **Controller:** Only extracts inputs from the request object (`req.body`, `req.query`, `req.params`), invokes the target Service, and returns the response using `res.status().json()`. Never execute database queries directly here.
29
+ - **Service:** Houses business logic, calculations, and database model interactions. Must not reference or depend on Express `req` or `res` objects to ensure testability.
30
+
31
+ #### 2. Async Error Handling
32
+ - **No Manual Try/Catch in Controllers:** Avoid wrapping every controller method in manual try/catch blocks.
33
+ - **Use Async Handlers:** Wrap all async controller functions with an automatic error-catching wrapper (such as `express-async-handler`) to forward exceptions to the `next()` function automatically.
34
+ - **Centralized Global Error Middleware:** Declare a 4-parameter error-handling middleware at the end of the server bootstrap chain (after all route registrations) to format error payloads.
35
+
36
+ #### 3. Request Validation with Zod Middleware
37
+ - **No Manual Conditional Validation:** Do not write scattered `if` blocks to check input parameters.
38
+ - **Zod Schema Middleware:** Implement a shared validation middleware that accepts a Zod schema to validate request segments (`body`, `query`, `params`) before they reach the Controller.
39
+
40
+ ### 🧪 Verification & Testing
41
+ Before completing a task, run the following verification pipeline:
42
+ - **Linting:** `{{runCommand}} lint`
43
+ - **Type Checking:** `{{runCommand}} typecheck`
44
+ - **Testing:** `{{runCommand}} test`
45
+ - **Build Validation:** `{{runCommand}} build`
@@ -1,36 +1,36 @@
1
- # Bẫy Lỗi Bất Đồng Bộ & Xác Thực Dữ Liệu Tự Động (Zod Middleware)
1
+ # Async Error Handling & Automated Validation (Zod Middleware)
2
2
 
3
- Tài liệu này quy định chiến lược xử lý lỗi bất đồng bộ (Async Error Catching), cấu hình Middleware xử lý lỗi tập trung, tự động kiểm tra dữ liệu bằng Zod.
3
+ This document defines standard practices for asynchronous error catching, centralized global error handling middleware, and automated schema validations using Zod.
4
4
 
5
5
  ---
6
6
 
7
- ## 🚨 Bẫy Lỗi Bất Đồng Bộ (Async Error Handling Architecture)
8
- - **Không dùng try/catch thủ công tại Controller:** Việc viết try/catch mọi hàm trong tất cả các controller gây loãng mã nguồn.
9
- - **Sử dụng Wrapper Tự động:** Toàn bộ các hàm controller bất đồng bộ phải được bọc bằng một hàm tiện ích tự động bắt lỗi (như `asyncHandler`) để tự động chuyển tiếp tất cả các ngoại lệ phát sinh sang cấu phần `next()`.
7
+ ## 🚨 Async Error Handling Architecture
8
+ - **No Manual Try/Catch in Controllers:** Wrapping every controller method in manual try/catch blocks is prohibited.
9
+ - **Use Async Handlers:** Wrap all async controller functions with an automatic error-catching wrapper (such as `asyncHandler`) to automatically forward exceptions to Express's `next()` function.
10
10
 
11
11
  ```typescript
12
12
  import { Request, Response, NextFunction } from 'express';
13
13
 
14
- // Hàm Wrapper bắt lỗi bất đồng bộ tự động
15
- export const asyncHandler = (fn: Function) => (req: Request, res: Response, next: NextFunction) => {
14
+ // Automated async error catcher wrapper
15
+ const asyncHandler = (fn: Function) => (req: Request, res: Response, next: NextFunction) => {
16
16
  Promise.resolve(fn(req, res, next)).catch(next);
17
17
  };
18
18
 
19
- // Cách triển khai thực tế tại Controller
19
+ // Controller usage example
20
20
  export const getUserProfile = asyncHandler(async (req: Request, res: Response) => {
21
21
  const userId = req.user.id;
22
- const profile = await userService.getProfile(userId); // Nếu ném lỗi bên trong service, asyncHandler sẽ tự catch
22
+ const profile = await userService.getProfile(userId); // Errors thrown inside the service are automatically caught
23
23
  return res.status(200).json({ success: true, data: profile });
24
24
  });
25
25
  ```
26
26
 
27
27
  ---
28
28
 
29
- ## 🔌 Middleware Xử Lý Lỗi Tập Trung (Global Error Handler)
30
- - **Khai báo bộ lọc:** Bắt buộc phải khai báo một middleware xử lỗi đủ 4 tham số ở cuối tệp cấu hình server (sau khi khai báo tất cả các routes) để định dạng lại toàn bộ phản hồi lỗi trước khi trả về cho Client.
29
+ ## 🔌 Centralized Global Error Handler Middleware
30
+ - **Register Error Middleware:** You must register a 4-parameter error-handling middleware at the end of the server bootstrap chain (after all route registrations) to parse and return clean error responses.
31
31
 
32
32
  ```typescript
33
- // Trong file app.ts hoặc server.ts
33
+ // Inside app.ts or server.ts
34
34
  app.use((err: any, req: Request, res: Response, next: NextFunction) => {
35
35
  const statusCode = err.statusCode || 500;
36
36
  const message = err.message || 'Internal Server Error';
@@ -46,9 +46,9 @@ Tài liệu này quy định chiến lược xử lý lỗi bất đồng bộ (
46
46
 
47
47
  ---
48
48
 
49
- ## 🛡️ Kiểm Thử Dữ Liệu Tự Động Với Zod Middleware
50
- - **Cấm Validate thủ công bằng câu lệnh điều kiện:** Không viết các đoạn code `if (!req.body.email)`.
51
- - **Xây dựng Middleware Validate Schema:** Phát triển một middleware dùng chung nhận vào một Schema của Zod để tự động kiểm duyệt toàn bộ dữ liệu đầu vào (`body`, `query`, `params`) trước khi cho phép dữ liệu đi sâu vào tầng Controller.
49
+ ## 🛡️ Automated Validation with Zod Middleware
50
+ - **No Manual Conditional Checks:** Do not write scattered `if (!req.body.email)` conditionals inside controllers.
51
+ - **Zod Schema Middleware:** Implement a shared validation middleware that accepts a Zod schema to validate request segments (`body`, `query`, `params`) before they reach the Controller.
52
52
 
53
53
  ```typescript
54
54
  import { AnyZodObject, ZodError } from 'zod';
@@ -57,14 +57,14 @@ Tài liệu này quy định chiến lược xử lý lỗi bất đồng bộ (
57
57
  export const validateSchema = (schema: AnyZodObject) => {
58
58
  return async (req: Request, res: Response, next: NextFunction): Promise<any> => {
59
59
  try {
60
- // Xác thực đồng thời cả body, query, và params thông qua cấu trúc schema của Zod
60
+ // Validate incoming request segments concurrently
61
61
  const parsed = await schema.parseAsync({
62
62
  body: req.body,
63
63
  query: req.query,
64
64
  params: req.params,
65
65
  });
66
66
 
67
- // Gán lại dữ liệu đã được parse sạch (và ép kiểu nếu có) vào hệ thống request
67
+ // Re-assign parsed and sanitized payloads
68
68
  req.body = parsed.body;
69
69
  req.query = parsed.query;
70
70
  req.params = parsed.params;
@@ -74,7 +74,7 @@ Tài liệu này quy định chiến lược xử lý lỗi bất đồng bộ (
74
74
  if (error instanceof ZodError) {
75
75
  return res.status(400).json({
76
76
  success: false,
77
- message: 'Dữ liệu đầu vào không hợp lệ',
77
+ message: 'Invalid input payload parameters',
78
78
  errors: error.errors.map((err) => ({
79
79
  field: err.path.join('.'),
80
80
  message: err.message,
@@ -1,28 +1,28 @@
1
- # Quy Ước Đặt Tên & Coding Style cho Express.js
1
+ # Express.js Naming Conventions & Coding Style
2
2
 
3
- Tài liệu này hướng dẫn coding style sạch, định nghĩa kiểu dữ liệu tường minh bằng TypeScript trong môi trường Express.js.
3
+ This document defines coding conventions, directory layout, and TypeScript configurations for Express.js applications.
4
4
 
5
5
  ---
6
6
 
7
- ## 🏷️ Quy Ước Đặt Tên (Naming Conventions)
7
+ ## 🏷️ Naming Conventions
8
8
 
9
- ### Thư mục Phân lớp (Architecture Folders)
10
- nguồn phải được tách biệt hoàn toàn theo kiến trúc 3 lớp (3-Tier Architecture):
9
+ ### Directory Layout (3-Tier Architecture)
10
+ The codebase must be structured cleanly according to a 3-tier architecture layout:
11
11
  ```bash
12
12
  src/
13
- ├── config/ # Cấu hình biến môi trường, kết nối Database
14
- ├── middlewares/ # Các hàm Middleware (Auth, Log, Validation)
15
- ├── models/ # Schema sở dữ liệu (Mongoose, Sequelize ORM, Prisma)
16
- ├── routes/ # Định tuyến HTTP, cấu hình gắn kết middleware đầu vào
17
- ├── controllers/ # Điều phối Request, định dạng Response đầu ra
18
- ├── services/ # Chứa 100% logic nghiệp vụ xử lý dữ liệu và tính toán
19
- ├── utils/ # Các hàm bổ trợ dùng chung
20
- └── app.ts # File khởi tạo cấu hình Express App
13
+ ├── config/ # Environment configurations, DB initializations
14
+ ├── middlewares/ # Express middleware functions (Auth, Log, Validation)
15
+ ├── models/ # Database Schemas (Mongoose, Sequelize, or Prisma client)
16
+ ├── routes/ # HTTP Route definitions and input middleware binding
17
+ ├── controllers/ # Request parameter extraction, response formatting
18
+ ├── services/ # Houses 100% of business logic and computations
19
+ ├── utils/ # Standalone utility helper functions
20
+ └── app.ts # Express App setup and server bootstrapping
21
21
  ```
22
22
 
23
- ### Quy ước Tên Tệp tin (File Naming)
24
- - **Tính đồng nhất:** Toàn bộ dự án phải chọn tuân thủ duy nhất định dạng `kebab-case.ts`.
25
- - **Hậu tố định danh:** Tên file phải đi kèm vai trò kiến trúc của nó làm hậu tố:
23
+ ### Filename Notation
24
+ - **Consistency:** Use `kebab-case.ts` across all filenames in the repository.
25
+ - **Suffix Declarations:** Filenames must end with a suffix representing their architectural role:
26
26
  - Controller: `user-controller.ts`
27
27
  - Service: `user-service.ts`
28
28
  - Route: `user-route.ts`
@@ -31,9 +31,9 @@ src/
31
31
 
32
32
  ---
33
33
 
34
- ## 📦 Định Nghĩa Kiểu Dữ Liệu & Quy Chuẩn TypeScript
35
- - **Khai báo kiểu dữ liệu tường minh:** Không dùng kiểu ngầm định. Luôn định nghĩa ràng kiểu cho tham số `req`, `res`, `next` lấy từ thư viện `express`:
34
+ ## 📦 TypeScript & Type Declarations
35
+ - **Explicit Type Declarations:** Avoid implicit type inference. Always define types for `req`, `res`, and `next` parameters imported from `express`:
36
36
  ```typescript
37
37
  import { Request, Response, NextFunction } from 'express';
38
38
  ```
39
- - **Không lạm dụng `any`:** Định nghĩa đầy đủ các interface hoặc type cho các cấu trúc dữ liệu gửi lên và trả về cho Client.
39
+ - **Strictly Ban the `any` Keyword:** Declare interfaces or types for all request bodies and API response structures.
@@ -1,27 +1,27 @@
1
- # Phân Tách Lớp Trách Nhiệm (Router vs Controller vs Service)
1
+ # Architectural Boundaries (Router vs Controller vs Service)
2
2
 
3
- Tài liệu này đặc tả ranh giới trách nhiệm giữa các lớp trong Express.js: Router nhận diện đường dẫn $\rightarrow$ Controller điều phối $\rightarrow$ Service xử lý core logic.
3
+ This document establishes boundaries and responsibilities for routers, controllers, and services in Express.js projects.
4
4
 
5
5
  ---
6
6
 
7
- ## 🏛️ Chuỗi Truyền Dẫn Dữ Liệu
8
- nguồn dự án phải tuân thủ nghiêm ngặt hình luồng dữ liệu 3 lớp:
7
+ ## 🏛️ Data Flow Chain
8
+ All features in the repository must comply with the standard 3-tier architecture data flow:
9
9
  $$\text{Client} \longrightarrow \text{Router} \longrightarrow \text{Middleware} \longrightarrow \text{Controller} \longrightarrow \text{Service} \longrightarrow \text{Model/Database}$$
10
10
 
11
11
  ---
12
12
 
13
- ## 🚦 Trách Nhiệm Chi Tiết Của Từng Lớp
13
+ ## 🚦 Layer Responsibilities
14
14
 
15
- ### 1. Lớp Định Tuyến (Router Layer - `routes/`)
16
- - **Vai trò:** Chỉ làm nhiệm vụ map HTTP Method + Path, liên kết các middleware xác thực (Auth) hoặc kiểm duyệt định dạng đầu vào (Zod validate schema).
17
- - **Quy tắc:** Tuyệt đối không chứa bất kỳ logic xử nghiệp vụ hay điều phối dữ liệu nào. Chỉ định hướng luồng sang Controller tương ứng.
15
+ ### 1. Router Layer (`routes/`)
16
+ - **Role:** Exclusively responsible for mapping HTTP methods + paths and binding authentication or payload validation middlewares (e.g., Zod schemas).
17
+ - **Rule:** Under no circumstances should the Router layer house business calculations or database operations. It must only forward requests to the target Controller.
18
18
 
19
- ### 2. Lớp Điều Phối (Controller Layer - `controllers/`)
20
- - **Vai trò:** Làm nhiệm vụ bóc tách dữ liệu đầu vào từ đối tượng `req` (req.body, req.query, req.params, req.user), chuyển tiếp các tham số đó sang tầng Service, nhận kết quả trả về cho Client bằng lệnh `res.status().json()`.
21
- - **Quy tắc:**
22
- - Không truy vấn sở dữ liệu hoặc làm việc trực tiếp với ORM Models trong Controller.
23
- - Không bắt lỗi try/catch thủ công (sử dụng asyncHandler để ủy thác cho bộ bắt lỗi toàn cục).
19
+ ### 2. Controller Layer (`controllers/`)
20
+ - **Role:** Responsible for extracting input payloads from the Express `req` object (`req.body`, `req.query`, `req.params`, `req.user`), forwarding these arguments to the Service layer, receiving outcomes, and responding to the client via `res.status().json()`.
21
+ - **Rules:**
22
+ - Never query database models or call ORM clients inside the Controller.
23
+ - Never write manual try/catch blocks (delegate errors to the global error handler using async wrappers).
24
24
 
25
- ### 3. Lớp Nghiệp Vụ (Service Layer - `services/`)
26
- - **Vai trò:** Chứa 100% logic nghiệp vụ xử lý dữ liệu, thực hiện tính toán thuật toán, tương tác với Database thông qua ORM Models.
27
- - **Quy tắc:** Tuyệt đối không được tiếp xúc hay phụ thuộc vào các đối tượng `req`, `res`, hay `next` của Express. Lớp Service phải độc lập hoàn toàn với framework để dễ dàng viết các bài kiểm thử Unit Test.
25
+ ### 3. Service Layer (`services/`)
26
+ - **Role:** Houses 100% of the core business logic, coordinates data mutations, executes algorithms, and interacts with Database models.
27
+ - **Rule:** Never import, reference, or access Express-specific objects (`req`, `res`, or `next`) inside Services. The Service layer must remain completely decoupled from the web framework to maintain isolated testability.
@@ -1,23 +1,23 @@
1
1
  ---
2
2
  name: express-endpoint
3
- description: Sinh hoặc mở rộng một API Endpoint Express.js + TypeScript an toàn, đầy đủ từ Router, Controller đến Validator
3
+ description: Scaffold or extend a secure Express.js + TypeScript API endpoint including Router, Controller, and Validator
4
4
  ---
5
5
 
6
- Tuân thủ quy trình này để tạo mới một API Endpoint Express.js hoặc mở rộng tuyến định tuyến hiện có.
6
+ Follow this process to generate a new Express.js API Endpoint or extend an existing route.
7
7
 
8
- Đầu vào (Inputs):
9
- - endpointName: Tên của API Endpoint cần tạo ( dụ: `user-profile`)
10
- - routePath: Đường dẫn tuyến HTTP của API ( dụ: `/api/v1/users/profile`)
11
- - httpMethod: Phương thức HTTP (GET, POST, PUT, DELETE)
12
- - targetPath: Thư mục gốc chứa nguồn của mô-đun để đặt tệp tin
8
+ Inputs:
9
+ - endpointName: Name of the API Endpoint to create (e.g., `user-profile`)
10
+ - routePath: HTTP route path of the API (e.g., `/api/v1/users/profile`)
11
+ - httpMethod: HTTP method (GET, POST, PUT, DELETE)
12
+ - targetPath: The destination path to place the code files
13
13
 
14
- Các bước thực hiện (Steps):
15
- 1. Định nghĩa Zod Validation Schema dưới thư mục `middlewares/` hoặc bên cạnh controller để kiểm duyệt các trường dữ liệu đầu vào.
16
- 2. Xây dựng hàm Service tương ứng bên dưới thư mục `services/` để đảm nhiệm 100% logic xử nghiệp vụ, truy vấn dữ liệu ORM.
17
- 3. Triển khai Controller điều phối trong thư mục `controllers/` sử dụng tiện ích bọc `asyncHandler` để giải phóng việc try/catch thủ công, nhận tham số từ request và gửi phản hồi dạng JSON sạch.
18
- 4. Đăng Controller gắn middleware `validateSchema(zodSchema)` vào file định tuyến Route tương ứng bên dưới thư mục `routes/`.
19
- 5. Bổ sung các test suite kiểm thử đơn vị cho Service kiểm thử tích hợp (E2E) qua Supertest.
20
- 6. Chạy kiểm tra lỗi cục bộ:
14
+ Steps:
15
+ 1. Define a Zod Validation Schema under the `middlewares/` directory or alongside the controller to validate input payloads.
16
+ 2. Implement the corresponding Service function under the `services/` directory to handle 100% of the business logic and ORM queries.
17
+ 3. Implement the Controller dispatcher in the `controllers/` directory using the `asyncHandler` wrapper to forward errors automatically, extract inputs, and send JSON responses.
18
+ 4. Register the Controller and mount the `validateSchema(zodSchema)` middleware on the target Route file under the `routes/` directory.
19
+ 5. Create unit test suites for the Service and integration test suites (E2E) using Supertest.
20
+ 6. Execute local validation:
21
21
  - `{{runCommand}} lint`
22
22
  - `{{runCommand}} typecheck`
23
23
  - `{{runCommand}} test`