c4-gen 1.5.2 → 1.6.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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/generator.js +365 -201
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "c4-gen",
3
- "version": "1.5.2",
3
+ "version": "1.6.0",
4
4
  "description": "Công cụ tự động sinh tài liệu kiến trúc C4 Model từ source code sử dụng AI",
5
5
  "main": "index.js",
6
6
  "type": "module",
package/src/generator.js CHANGED
@@ -122,10 +122,11 @@ export async function generateC4Documentation({ sourcePath, outputPath, apiKey,
122
122
  }
123
123
 
124
124
  async function generateContextDiagram(model, codeStructure) {
125
- // Chia nhỏ data để tránh vượt quá context limit
126
- const filesList = codeStructure.files.slice(0, 30).map(f => f.path).join('\n');
125
+ // Tăng context để phân tích chi tiết hơn
126
+ const filesList = codeStructure.files.slice(0, 50).map(f => f.path).join('\n'); // Tăng từ 30 lên 50
127
127
  const structureSummary = summarizeStructure(codeStructure.structure);
128
- const sampleCode = truncateText(codeStructure.sampleCode, 3000);
128
+ const sampleCode = truncateText(codeStructure.sampleCode, 5000); // Tăng từ 3000 lên 5000
129
+ const filesByFolder = groupFilesByFolder(codeStructure.files);
129
130
 
130
131
  const prompt = `
131
132
  Phân tích source code sau và tạo C4 LEVEL 1: CONTEXT DIAGRAM (System Overview):
@@ -134,7 +135,10 @@ Phân tích source code sau và tạo C4 LEVEL 1: CONTEXT DIAGRAM (System Overvi
134
135
  - Total Files: ${codeStructure.files.length}
135
136
  - Project Structure: ${structureSummary}
136
137
 
137
- 📁 KEY FILES (30 first files):
138
+ 📁 FILES BY FOLDER:
139
+ ${filesByFolder}
140
+
141
+ 📁 KEY FILES (50 first files):
138
142
  ${filesList}
139
143
 
140
144
  💻 SAMPLE CODE:
@@ -144,89 +148,127 @@ ${sampleCode}
144
148
  ${formatDependencies(codeStructure.dependencies)}
145
149
 
146
150
  ---
147
- 🎯 HƯỚNG DẪN PHÂN TÍCH:
148
-
149
- QUAN TRỌNG: Chỉ phân tích dựa trên CODE THỰC TẾ được cung cấp, KHÔNG tự nghĩ ra hoặc dùng ví dụ.
150
-
151
- 1. BUSINESS CONTEXT:
152
- - Đọc package.json name/description
153
- - Phân tích folder structure (ecommerce/cms/crm/pos/blog...)
154
- - Xem code để hiểu domain nghiệp vụ
155
-
156
- 2. STAKEHOLDERS:
157
- - Tìm trong code: roles, permissions, user types
158
- - Xem routes/controllers để hiểu ai dùng hệ thống
159
-
160
- 3. EXTERNAL SYSTEMS:
161
- - Phân tích DEPENDENCIES để tìm third-party services
162
- - Tìm API keys, SDK imports (stripe, firebase, aws-sdk, nodemailer...)
163
- - Xem imports để phát hiện integrations
151
+ 🎯 HƯỚNG DẪN PHÂN TÍCH CHI TIẾT:
152
+
153
+ QUAN TRỌNG: Phải phân tích TOÀN DIỆN CHI TIẾT, KHÔNG tự nghĩ ra hoặc dùng ví dụ.
154
+
155
+ 1. BUSINESS CONTEXT - PHÂN TÍCH SÂU:
156
+ - Đọc package.json name/description để hiểu domain
157
+ - Phân tích folder structure: pos/ → Point of Sale, ecommerce/ → E-commerce, etc.
158
+ - Scan routes/controllers để hiểu business features
159
+ - Identify domain entities từ models/schemas
160
+ - Phát hiện business flows từ service layer
161
+
162
+ 2. STAKEHOLDERS - TÌM TẤT CẢ:
163
+ - Scan ALL files chứa "role", "permission", "user", "admin"
164
+ - Đọc authentication/authorization code
165
+ - Tìm trong migrations/seeds cho user roles
166
+ - Check middleware cho role-based access
167
+ - List ĐẦY ĐỦ mọi loại người dùng hệ thống
164
168
 
165
- 4. COMMUNICATION PROTOCOLS:
166
- - Xem express/fastify HTTP/REST
167
- - socket.io WebSocket
168
- - amqplib AMQP
169
- - grpc → gRPC
170
-
171
- 5. TECHNOLOGIES:
172
- - Frontend: Tìm react, vue, angular, next.js trong dependencies
173
- - Backend: Xem runtime (node.js, python, java từ files)
174
- - Database: Tìm pg, mysql2, mongodb, sequelize, prisma...
175
- - Infrastructure: Tìm Dockerfile, docker-compose.yml, kubernetes yaml
176
-
177
- Hãy trả về JSON với format:
169
+ 3. EXTERNAL SYSTEMS - LIỆT KÊ TẤT CẢ:
170
+ - Scan TOÀN BỘ dependencies cho third-party services:
171
+ * Payment: stripe, paypal, vnpay, momo
172
+ * Email: nodemailer, sendgrid, mailgun
173
+ * SMS: twilio, nexmo
174
+ * Storage: aws-s3, cloudinary, firebase-storage
175
+ * Auth: passport, jwt, oauth
176
+ * Analytics: google-analytics, mixpanel
177
+ * Monitoring: sentry, newrelic
178
+ * Search: elasticsearch, algolia
179
+ * Cache: redis, memcached
180
+ - Tìm API integrations trong code (axios calls, fetch to external URLs)
181
+ - Check config files cho external service endpoints
182
+ - PHẢI liệt kê TẤT CẢ integrations tìm được
183
+
184
+ 4. USERS - PHÂN LOẠI CHI TIẾT:
185
+ - Scan routes để identify user journeys:
186
+ * /api/admin/* → Admin users
187
+ * /api/customer/* → Customers
188
+ * /api/vendor/* → Vendors
189
+ * /api/staff/* → Staff members
190
+ - Phân tích permissions/roles cho từng loại user
191
+ - List ĐẦY ĐỦ interactions của từng user type
192
+ - Identify access channels (Web App, Mobile App, API)
193
+
194
+ 5. COMMUNICATION PROTOCOLS:
195
+ - HTTP/REST: express, fastify, koa
196
+ - WebSocket: socket.io, ws
197
+ - GraphQL: apollo, graphql
198
+ - gRPC: @grpc/grpc-js
199
+ - Message Queue: amqplib (RabbitMQ), kafkajs (Kafka)
200
+ - Database protocols: postgres, mysql, mongodb
201
+
202
+ 6. TECHNOLOGIES - LIỆT KÊ ĐẦY ĐỦ:
203
+ - Frontend: React, Vue, Angular, Next.js, Nuxt, Svelte...
204
+ - Backend: Node.js, Python, Java, Go, .NET...
205
+ - Database: PostgreSQL, MySQL, MongoDB, Redis, Elasticsearch...
206
+ - Infrastructure: Docker, Kubernetes, AWS, GCP, Azure...
207
+
208
+ Hãy trả về JSON với format CHI TIẾT:
178
209
  {
179
- "systemName": "Tên từ package.json hoặc suy ra từ folder structure",
180
- "description": "Mô tả dựa trên phân tích code structure",
181
- "businessContext": "Domain nghiệp vụ phát hiện từ code",
182
- "purpose": "Mục đích chính suy ra từ features",
210
+ "systemName": "Tên CHÍNH XÁC từ package.json",
211
+ "description": "Mô tả ĐẦY ĐỦ dựa trên phân tích code (3-5 câu)",
212
+ "businessContext": "Domain nghiệp vụ CHI TIẾT (VD: Restaurant POS system with inventory management, order processing, and payment integration)",
213
+ "purpose": "Mục đích CỤTH (liệt 3-5 mục đích chính)",
183
214
  "stakeholders": [
184
215
  {
185
- "role": "Vai trò TÌM ĐƯỢC trong code (Admin/User/...)",
186
- "description": "Mô tả dựa trên permissions/roles trong code",
187
- "concerns": "Concerns suy ra từ features họ dùng"
216
+ "role": "Vai trò CHÍNH XÁC từ code",
217
+ "description": "Mô tả CHI TIẾT responsibilities",
218
+ "concerns": "Concerns CỤ THỂ (security, performance, usability...)"
188
219
  }
189
220
  ],
190
221
  "users": [
191
222
  {
192
- "name": "User type TÌM ĐƯỢC trong code",
193
- "type": "Internal/External (dựa vào phân tích)",
194
- "description": "Mô tả dựa trên routes/controllers",
223
+ "name": "User type TỪ CODE (Admin, Customer, Vendor, Staff...)",
224
+ "type": "Internal/External",
225
+ "description": "Mô tả ĐẦY ĐỦ role và responsibilities",
195
226
  "interactions": [
196
- "Interactions TÌM ĐƯỢC từ API endpoints",
197
- "VÍ DỤ: Nếu có /api/products → 'Quản lý sản phẩm'"
227
+ "LIST TẤT CẢ interactions từ routes (Manage products, Process orders, View reports...)"
198
228
  ],
199
- "access": "Phát hiện từ code (Web nếu có React, Mobile nếu React Native...)"
229
+ "access": "Access method CHI TIẾT (Web Dashboard, Mobile App, REST API...)"
200
230
  }
201
231
  ],
202
232
  "externalSystems": [
203
233
  {
204
- "name": "Tên service TÌM ĐƯỢC trong dependencies (stripe, firebase, aws-sdk...)",
205
- "category": "Category dựa vào tên package (stripe→Payment, nodemailer→Email...)",
206
- "description": "Mô tả service",
207
- "purpose": "Purpose suy từ cách dùng",
208
- "protocol": "Protocol phát hiện từ code",
209
- "direction": "Inbound/Outbound (phân tích từ code flow)",
210
- "dataFlow": "Data type từ code"
234
+ "name": "Service name CHÍNH XÁC từ dependencies",
235
+ "category": "Category CỤ THỂ (Payment Gateway, Email Service, Cloud Storage...)",
236
+ "description": "Mô tả CHI TIẾT service và version",
237
+ "purpose": "Purpose CỤ THỂ (Process payments, Send notifications...)",
238
+ "protocol": "Protocol (HTTPS/REST, SMTP, S3...)",
239
+ "direction": "Inbound/Outbound/Bidirectional",
240
+ "dataFlow": "Data type CỤ THỂ (Payment data, Email content, File uploads...)"
211
241
  }
212
242
  ],
213
- "architectureStyle": "Style phát hiện từ structure (1 app→Monolithic, nhiều services→Microservices)",
214
- "deploymentModel": "Dựa vào Dockerfile/cloud config",
243
+ "architectureStyle": "Architecture CHI TIẾT (Monolithic with modular structure, Microservices...)",
244
+ "deploymentModel": "Deployment CỤ THỂ (Docker containers, Kubernetes, Serverless...)",
215
245
  "technologies": {
216
- "frontend": ["Technologies TÌM ĐƯỢC trong package.json devDependencies"],
217
- "backend": ["Technologies TÌM ĐƯỢC trong dependencies + file extensions"],
218
- "database": ["Databases TÌM ĐƯỢC từ imports/dependencies"],
219
- "infrastructure": ["Infrastructure TÌM ĐƯỢC từ Dockerfile, k8s files..."]
246
+ "frontend": ["TẤT CẢ frontend tech + versions"],
247
+ "backend": ["TẤT CẢ backend tech + versions"],
248
+ "database": ["TẤT CẢ databases + versions"],
249
+ "infrastructure": ["TẤT CẢ infrastructure tools"],
250
+ "devOps": ["CI/CD tools, monitoring..."],
251
+ "security": ["Auth methods, encryption..."]
220
252
  },
221
253
  "keyPrinciples": [
222
- "Principles SUY RA từ code structure patterns"
254
+ "LIST principles từ code (RESTful API, Microservices, DDD, CQRS...)"
255
+ ],
256
+ "businessFlows": [
257
+ "KEY business flows từ code (Order Processing, Inventory Management...)"
223
258
  ]
224
259
  }
225
260
 
261
+ YÊU CẦU ĐẦY ĐỦ:
262
+ ✅ Stakeholders: PHẢI có ít nhất 3-5 stakeholder types
263
+ ✅ Users: PHẢI liệt kê TẤT CẢ user types tìm được
264
+ ✅ External Systems: PHẢI liệt kê TẤT CẢ dependencies/integrations
265
+ ✅ Technologies: PHẢI đầy đủ tất cả tech stack
266
+ ✅ Business Flows: PHẢI liệt kê các flows chính
267
+
226
268
  LƯU Ý:
227
- - Nếu KHÔNG TÌM THẤY thông tin → để mảng rỗng [] hoặc "Not detected"
228
- - KHÔNG tự nghĩ ra data không có trong code
229
- - Nếu không chắc ghi "Detected from code analysis" thay vì bịa
269
+ - Nếu KHÔNG TÌM THẤY → để mảng rỗng [], KHÔNG bịa
270
+ - PHẢI CHI TIẾT ĐẦY ĐỦ
271
+ - Ưu tiên QUALITY over QUANTITY nhưng KHÔNG bỏ sót
230
272
  `;
231
273
 
232
274
  checkPromptSize(prompt);
@@ -240,8 +282,9 @@ LƯU Ý:
240
282
  async function generateContainerDiagram(model, codeStructure) {
241
283
  // Tăng context để AI hiểu rõ hơn
242
284
  const filesByType = groupFilesByType(codeStructure.files);
285
+ const filesByFolder = groupFilesByFolder(codeStructure.files);
243
286
  const structureSummary = summarizeStructure(codeStructure.structure);
244
- const sampleCode = truncateText(codeStructure.sampleCode, 5000); // Tăng từ 2000 lên 5000
287
+ const sampleCode = truncateText(codeStructure.sampleCode, 8000); // Tăng từ 5000 lên 8000
245
288
 
246
289
  const prompt = `
247
290
  Phân tích source code và tạo C4 LEVEL 2: CONTAINER DIAGRAM (System Components):
@@ -252,112 +295,165 @@ ${structureSummary}
252
295
  📁 FILES BY TYPE:
253
296
  ${filesByType}
254
297
 
255
- 📦 DEPENDENCIES:
298
+ FILES BY FOLDER:
299
+ ${filesByFolder}
300
+
301
+ �📦 DEPENDENCIES:
256
302
  ${formatDependencies(codeStructure.dependencies)}
257
303
 
258
304
  💻 SAMPLE CODE:
259
305
  ${sampleCode}
260
306
 
261
307
  ---
262
- 🎯 HƯỚNG DẪN PHÂN TÍCH:
263
-
264
- QUAN TRỌNG: Chỉ dựa trên CODE và DEPENDENCIES thực tế, KHÔNG dùng dụ mẫu.
265
-
266
- 1. IDENTIFY CONTAINERS:
267
- - Frontend: Tìm React/Vue/Angular trong dependencies → Web Application container
268
- - Backend: Tìm Express/Fastify/NestJSAPI Server container
269
- - Database: Tìm pg/mysql2/mongodb Database container
270
- - Cache: Tìm redis/ioredis Cache container
271
- - Message Queue: Tìm amqplib/kafkajs → MQ container
272
- - Search: Tìm @elastic/elasticsearchSearch Engine container
308
+ 🎯 HƯỚNG DẪN PHÂN TÍCH CHI TIẾT:
309
+
310
+ QUAN TRỌNG: Chỉ dựa trên CODE và DEPENDENCIES thực tế, PHẢI CHI TIẾT ĐẦY ĐỦ.
311
+
312
+ 1. IDENTIFY ALL CONTAINERS - LIỆT KÊ TẤT CẢ:
313
+ - Frontend Containers:
314
+ * React/Vue/AngularWeb Application
315
+ * React NativeMobile App
316
+ * Next.jsSSR Application
317
+ - Backend Containers:
318
+ * Express/Fastify/NestJSAPI Server
319
+ * GraphQL Server → GraphQL API
320
+ * WebSocket Server → Realtime Service
321
+ - Data Containers:
322
+ * PostgreSQL/MySQL → Primary Database
323
+ * MongoDB → Document Store
324
+ * Redis → Cache Layer
325
+ * Elasticsearch → Search Engine
326
+ - Infrastructure Containers:
327
+ * Nginx → Reverse Proxy
328
+ * RabbitMQ/Kafka → Message Broker
329
+ * Worker processes → Background Jobs
330
+
331
+ 2. TECHNOLOGY STACK - CHÍNH XÁC:
332
+ - Đọc package.json cho EXACT versions
333
+ - VD: "express": "^4.18.2" → "Express.js 4.18.2"
334
+ - List ALL major dependencies với versions
273
335
 
274
- 2. TECHNOLOGY & VERSION:
275
- - Đọc package.json để lấy version CHÍNH XÁC
276
- - VÍ DỤ: "react": "^18.2.0" ghi "React 18.2"
336
+ 3. CONTAINER SPECIFICATIONS:
337
+ - Ports: Scan code cho app.listen(), PORT, env variables
338
+ - Environment: Development, Staging, Production configs
339
+ - Scaling: Replicas từ docker-compose hoặc k8s
340
+ - Resources: Memory/CPU limits từ deployment configs
341
+ - Health checks: Tìm /health, /ping endpoints
277
342
 
278
- 3. CONTAINER SPECS:
279
- - Ports: Tìm trong code (app.listen(3000), PORT env...)
280
- - Replicas: Mặc định 1, trừ khi thấy docker-compose scale
281
- - Resources: Đọc từ Dockerfile/k8s manifests nếu có
343
+ 4. COMMUNICATION PATTERNS:
344
+ - Synchronous:
345
+ * HTTP/REST express routes
346
+ * GraphQL apollo-server
347
+ * gRPC → @grpc/grpc-js
348
+ - Asynchronous:
349
+ * Message Queue → amqplib, kafkajs
350
+ * WebSocket → socket.io, ws
351
+ * Event Bus → eventemitter2
352
+ - Caching:
353
+ * Redis → ioredis
354
+ * In-memory → node-cache
282
355
 
283
- 4. PROTOCOLS:
284
- - express HTTP/REST
285
- - socket.io WebSocket
286
- - import amqp AMQP
287
- - @grpc gRPC
288
-
289
- 5. DATA STORES:
290
- - Sequelize/TypeORM/Prisma Relational DB
291
- - Mongoose MongoDB (NoSQL)
292
- - ioredis Redis (Cache)
293
- - @elastic Elasticsearch (Search)
294
-
295
- Hãy trả về JSON với format:
356
+ 5. CONTAINER INTERACTIONS - CHI TIẾT:
357
+ - API Server Database: Query patterns, connection pooling
358
+ - API Server Cache: Cache strategies (read-through, write-through)
359
+ - API Server Message Queue: Pub/Sub patterns
360
+ - Frontend API Server: REST endpoints, WebSocket connections
361
+ - Workers ↔ Queue: Job processing patterns
362
+
363
+ 6. DATA STORES - LIỆT TẤT CẢ:
364
+ - Primary DB: Main data storage với schema
365
+ - Cache: Redis cho session, caching
366
+ - Search: Elasticsearch cho full-text search
367
+ - File Storage: S3, Cloudinary cho uploads
368
+ - Analytics: Time-series DB nếu
369
+
370
+ Hãy trả về JSON CHI TIẾT:
296
371
  {
297
- "architectureStyle": "Phát hiện từ structure (1 app→Monolithic, nhiều services→Microservices)",
372
+ "architectureStyle": "Architecture CỤ THỂ (Monolithic, Microservices, Modular Monolith...)",
298
373
  "containers": [
299
374
  {
300
- "name": "Tên TỰ ĐẶT dựa vào technology (React App, Node API, PostgreSQL DB...)",
301
- "type": "Type dựa vào phát hiện (Web Application/API Server/Database/Cache...)",
302
- "technology": "Technology + version TÌM ĐƯỢC (Express.js 4.18, PostgreSQL 14...)",
303
- "description": "Mô tả dựa trên responsibilities",
375
+ "name": "Tên CHÍNH XÁC (API Server, Web Dashboard, Mobile App, PostgreSQL DB...)",
376
+ "type": "Type CỤ THỂ (Web Application/API Server/Database/Cache/Message Queue...)",
377
+ "technology": "Tech + version CHÍNH XÁC (Express.js 4.18.2, React 18.2.0, PostgreSQL 14.5...)",
378
+ "description": "Mô tả ĐẦY ĐỦ responsibilities và purpose",
304
379
  "responsibilities": [
305
- "Responsibility SUY RA từ code (Nếu Frontend→UI rendering, routing...)",
306
- "Nếu Backend→Business logic, API endpoints..."
380
+ "LIST TẤT CẢ responsibilities từ code (Handle API requests, Process payments, Manage inventory...)"
307
381
  ],
308
- "port": "Port TÌM ĐƯỢC từ code hoặc 'Not specified'",
309
- "replicas": "1 hoặc số TÌM ĐƯỢC trong docker-compose",
382
+ "port": "Port CHÍNH XÁC hoặc 'Not specified'",
383
+ "replicas": "Số instances (1, 3, auto-scale...)",
310
384
  "resources": {
311
- "memory": "TÌM từ Dockerfile/k8s hoặc 'Not specified'",
312
- "cpu": "TÌM từ Dockerfile/k8s hoặc 'Not specified'"
385
+ "memory": "Memory limit (512MB, 1GB, 2GB...)",
386
+ "cpu": "CPU limit (0.5, 1.0, 2.0...)"
313
387
  },
314
- "storage": "TÌM từ volumes hoặc 'Not applicable'",
315
- "protocols": ["Protocols PHÁT HIỆN từ code"],
316
- "dependencies": ["Dependencies THỰC TẾ từ imports"],
388
+ "storage": "Storage type size",
389
+ "protocols": ["TẤT CẢ protocols (HTTP/1.1, HTTP/2, WebSocket, gRPC...)"],
390
+ "dependencies": ["TẤT CẢ runtime dependencies"],
317
391
  "interactions": [
318
392
  {
319
- "to": "Container đích THỰC SỰ connect tới",
320
- "description": "Mô tả TỪ code",
321
- "protocol": "Protocol PHÁT HIỆN",
322
- "direction": "Direction dựa vào code flow",
323
- "dataExchanged": "Data type TỪ code",
324
- "isAsync": "true nếu có await/Promise, false nếu sync"
393
+ "to": "Target container CHÍNH XÁC",
394
+ "description": "Mô tả CHI TIẾT interaction",
395
+ "protocol": "Protocol CỤ THỂ",
396
+ "direction": "Inbound/Outbound/Bidirectional",
397
+ "dataExchanged": "Data type CHI TIẾT",
398
+ "isAsync": "true/false",
399
+ "frequency": "Request frequency (high/medium/low)"
325
400
  }
326
401
  ],
327
402
  "endpoints": [
328
- "API endpoints TÌM ĐƯỢC từ routes/controllers"
329
- ]
403
+ "TẤT CẢ endpoints/routes phục vụ"
404
+ ],
405
+ "healthCheck": "Health check endpoint",
406
+ "logging": "Logging strategy",
407
+ "monitoring": "Monitoring tools"
330
408
  }
331
409
  ],
332
410
  "dataStores": [
333
411
  {
334
- "name": "Tên DB TỪ dependencies",
335
- "type": "Type dựa vào package (pg→Relational, mongodb→NoSQL, redis→Cache)",
336
- "technology": "Technology + version từ package.json",
337
- "purpose": "Purpose suy từ code usage",
338
- "dataModel": "Model TỪ code (Multi-tenant nếu thấy schema separation...)",
339
- "port": "Port TỪ config hoặc default"
412
+ "name": "Store name CHÍNH XÁC",
413
+ "type": "Type CỤ THỂ (Relational/NoSQL/Cache/Search/File Storage...)",
414
+ "technology": "Tech + version CHÍNH XÁC",
415
+ "purpose": "Purpose CHI TIẾT",
416
+ "dataModel": "Data model description",
417
+ "port": "Port hoặc connection string",
418
+ "replication": "Replication strategy",
419
+ "backup": "Backup strategy"
340
420
  }
341
421
  ],
342
422
  "messagingLayer": {
343
- "technology": "Technology TÌM ĐƯỢC (RabbitMQ từ amqplib, Kafka từ kafkajs...)",
344
- "queues": ["Queue names TÌM ĐƯỢC trong code"],
345
- "purpose": "Purpose SUY từ usage"
423
+ "technology": "Technology CHÍNH XÁC (RabbitMQ 3.11, Kafka 3.3...)",
424
+ "queues": ["TẤT CẢ queue names"],
425
+ "exchanges": ["Exchange names nếu "],
426
+ "purpose": "Purpose CHI TIẾT",
427
+ "patterns": ["Pub/Sub, Work Queue, RPC..."]
346
428
  },
347
429
  "infrastructureComponents": [
348
430
  {
349
- "name": "Component TÌM ĐƯỢC (Nginx từ nginx.conf, Docker từ Dockerfile...)",
350
- "technology": "Technology từ config files",
351
- "purpose": "Purpose từ config"
431
+ "name": "Component name (Nginx, API Gateway, Load Balancer...)",
432
+ "technology": "Technology + version",
433
+ "purpose": "Purpose CHI TIẾT",
434
+ "configuration": "Key configurations"
352
435
  }
353
- ]
436
+ ],
437
+ "networkingAndSecurity": {
438
+ "loadBalancing": "Load balancing strategy",
439
+ "ssl": "SSL/TLS configuration",
440
+ "authentication": "Auth methods",
441
+ "rateLimit": "Rate limiting strategy"
442
+ }
354
443
  }
355
444
 
445
+ YÊU CẦU ĐẦY ĐỦ:
446
+ ✅ Containers: PHẢI liệt kê TẤT CẢ containers (API, DB, Cache, Queue...)
447
+ ✅ Technology: PHẢI có version CHÍNH XÁC từ package.json
448
+ ✅ Interactions: PHẢI mô tả CHI TIẾT mọi connection
449
+ ✅ Endpoints: PHẢI list routes/APIs của container
450
+ ✅ Data Stores: PHẢI liệt kê TẤT CẢ storage systems
451
+
356
452
  LƯU Ý:
357
- - Nếu KHÔNG có Frontend dependencies KHÔNG tạo Frontend container
358
- - Nếu KHÔNG có Database package KHÔNG tạo DB container
359
- - Chỉ tạo containers CHO CÁI CÓ TRONG CODE
360
- - Nếu không tìm thấy để "Not detected" hoặc mảng rỗng []
453
+ - Nếu KHÔNG có Frontend → không tạo Frontend container
454
+ - Nếu KHÔNG có QueuemessagingLayer null
455
+ - CHỈ những CÓ TRONG CODE
456
+ - PHẢI CHI TIẾT ĐẦY ĐỦ
361
457
  `;
362
458
 
363
459
  checkPromptSize(prompt);
@@ -371,8 +467,9 @@ LƯU Ý:
371
467
  async function generateComponentDiagram(model, codeStructure) {
372
468
  // Tăng context để đọc nhiều files hơn
373
469
  const filesByFolder = groupFilesByFolder(codeStructure.files);
470
+ const filesByType = groupFilesByType(codeStructure.files);
374
471
  const structureSummary = summarizeStructure(codeStructure.structure);
375
- const sampleCode = truncateText(codeStructure.sampleCode, 8000); // Tăng từ 2500 lên 8000
472
+ const sampleCode = truncateText(codeStructure.sampleCode, 10000); // Tăng từ 8000 lên 10000
376
473
 
377
474
  const prompt = `
378
475
  Phân tích source code và tạo C4 LEVEL 3: COMPONENT DIAGRAM (Internal Structure):
@@ -383,119 +480,186 @@ ${structureSummary}
383
480
  📁 FILES BY FOLDER (${codeStructure.files.length} total):
384
481
  ${filesByFolder}
385
482
 
386
- 📦 DEPENDENCIES:
483
+ FILES BY TYPE:
484
+ ${filesByType}
485
+
486
+ �📦 DEPENDENCIES:
387
487
  ${formatDependencies(codeStructure.dependencies)}
388
488
 
389
489
  💻 SAMPLE CODE:
390
490
  ${sampleCode}
391
491
 
392
492
  ---
393
- 🎯 HƯỚNG DẪN PHÂN TÍCH:
394
-
395
- QUAN TRỌNG: Chỉ liệt kê components TÌM ĐƯỢC trong code, KHÔNG tự nghĩ ra.
396
-
397
- 1. SCAN FILES ĐỂ TÌM COMPONENTS:
398
- - Controllers: Tìm files chứa "Controller", "controller", "*Controller.js", "routes/*.js"
399
- - Services: Tìm files chứa "Service", "service", "*Service.js"
400
- - Repositories: Tìm files chứa "Repository", "Repo", "DAO", "models/*.js"
401
- - Middleware: Tìm files trong "middleware/", "middlewares/"
402
- - Utils: Tìm files trong "utils/", "helpers/", "lib/"
493
+ 🎯 HƯỚNG DẪN PHÂN TÍCH CHI TIẾT:
494
+
495
+ QUAN TRỌNG: Chỉ liệt kê components TÌM ĐƯỢC trong code, PHẢI ĐẦY ĐỦ và CHI TIẾT.
496
+
497
+ 1. SCAN ALL FILES ĐỂ TÌM TẤT CẢ COMPONENTS:
498
+ - Controllers:
499
+ * Scan ALL files matching: *Controller.js, *controller.ts, routes/*.js
500
+ * Extract class names route handlers
501
+ - Services:
502
+ * Scan ALL files matching: *Service.js, *service.ts, services/*.js
503
+ * Identify business logic components
504
+ - Repositories/DAOs:
505
+ * Scan ALL files matching: *Repository.js, *Repo.js, *DAO.js, models/*.js
506
+ * Map database access layers
507
+ - Middleware:
508
+ * List ALL files in middleware/, middlewares/
509
+ * Identify auth, validation, logging middleware
510
+ - Utilities:
511
+ * List ALL files in utils/, helpers/, lib/
512
+ * Categorize by function
403
513
 
404
- 2. PHÁT HIỆN ARCHITECTURE LAYERS:
405
- - Presentation: Nếu có controllers/, routes/, views/
406
- - Business: Nếu services/, business/, domain/
407
- - Data: Nếu repositories/, models/, data-access/
408
- - Infrastructure: Nếu có config/, infrastructure/, lib/
409
-
410
- 3. API ENDPOINTS - SCAN ROUTES:
411
- - Đọc files trong routes/ hoặc controllers/
412
- - Tìm app.get(), router.post(), @Get(), @Post()...
413
- - Lấy path VÀ method CHÍNH XÁC từ code
514
+ 2. IDENTIFY ARCHITECTURE LAYERS - CHI TIẾT:
515
+ - Presentation Layer:
516
+ * Routes, Controllers, API handlers
517
+ * Input validation, request mapping
518
+ - Business Logic Layer:
519
+ * Services, Use cases, Domain logic
520
+ * Business rules, calculations
521
+ - Data Access Layer:
522
+ * Repositories, ORMs, Query builders
523
+ * Database operations, caching
524
+ - Infrastructure Layer:
525
+ * Config, External integrations
526
+ * Logging, monitoring, error handling
527
+ - Cross-Cutting Concerns:
528
+ * Authentication, Authorization
529
+ * Logging, Caching, Error handling
530
+
531
+ 3. API ENDPOINTS - SCAN TẤT CẢ ROUTES:
532
+ - Đọc TOÀN BỘ route files
533
+ - Extract:
534
+ * Method: GET, POST, PUT, DELETE, PATCH
535
+ * Path: /api/users, /api/products/:id
536
+ * Handler: Controller method name
537
+ * Middleware: Auth, validation middleware
538
+ - PHẢI liệt kê ĐẦY ĐỦ TẤT CẢ endpoints
414
539
 
415
- 4. COMPONENT DEPENDENCIES:
416
- - Xem imports/require trong từng file
417
- - Nếu ProductController import ProductService → dependency
540
+ 4. COMPONENT DEPENDENCIES - MAP TOÀN BỘ:
541
+ - Scan imports/require trong MỌI file
542
+ - Build dependency graph:
543
+ * Controller → Service
544
+ * Service → Repository
545
+ * Repository → Database
546
+ - Identify circular dependencies
418
547
 
419
- 5. DESIGN PATTERNS:
420
- - Controller + Service MVC pattern
421
- - Repository Repository pattern
422
- - inject/DI container Dependency Injection
423
-
424
- Hãy trả về JSON:
548
+ 5. DESIGN PATTERNS - PHÁT HIỆN:
549
+ - MVC: Controller + Model + View/Routes
550
+ - Repository: Data access abstraction
551
+ - Service Layer: Business logic separation
552
+ - Dependency Injection: IoC containers
553
+ - Factory: Object creation patterns
554
+ - Singleton: Shared instances
555
+ - Observer: Event emitters
556
+ - Strategy: Pluggable algorithms
557
+
558
+ 6. MIDDLEWARE CHAIN - LIỆT KÊ:
559
+ - Global middleware
560
+ - Route-specific middleware
561
+ - Error handling middleware
562
+ - Execution order
563
+
564
+ Hãy trả về JSON CHI TIẾT:
425
565
  {
426
566
  "architectureLayers": [
427
567
  {
428
- "name": "Tên layer PHÁT HIỆN từ folder structure",
429
- "purpose": "Purpose SUY RA từ files trong layer",
430
- "components": ["Component names TÌM ĐƯỢC trong layer này"]
568
+ "name": "Layer name CỤ THỂ (Presentation, Business Logic, Data Access, Infrastructure)",
569
+ "purpose": "Purpose CHI TIẾT",
570
+ "components": ["TẤT CẢ component names trong layer"],
571
+ "responsibilities": ["Chi tiết responsibilities"],
572
+ "patterns": ["Design patterns used"]
431
573
  }
432
574
  ],
433
575
  "components": [
434
576
  {
435
- "name": "Tên component TỪ FILENAME (VD: ProductController từ ProductController.js)",
436
- "type": "Type DỰA VÀO file name và location (Controller/Service/Repository...)",
437
- "layer": "Layer PHÁT HIỆN từ folder path",
438
- "technology": "Technology TỪ imports (express, sequelize...)",
439
- "description": "Mô tả DỰA VÀO code trong file",
577
+ "name": "Component name CHÍNH XÁC từ filename",
578
+ "type": "Type CỤ THỂ (Controller/Service/Repository/Middleware/Utility...)",
579
+ "layer": "Layer CỤ THỂ",
580
+ "technology": "Technology stack (Express, Sequelize, TypeORM...)",
581
+ "description": "Mô tả ĐẦY ĐỦ purpose functionality",
440
582
  "responsibilities": [
441
- "Responsibilities SUY RA từ methods trong file"
583
+ "LIST TẤT CẢ responsibilities từ methods"
442
584
  ],
443
585
  "files": [
444
- "File paths CHÍNH XÁC từ scan"
586
+ "TẤT CẢ file paths liên quan"
445
587
  ],
446
588
  "apiEndpoints": [
447
589
  {
448
- "method": "HTTP method TÌM ĐƯỢC (GET/POST/PUT/DELETE)",
449
- "path": "Path CHÍNH XÁC từ route definition",
450
- "description": "Description TỪ comments hoặc suy từ path",
451
- "authentication": "Required nếu thấy auth middleware, None nếu không",
452
- "authorization": "Authorization level TỪ middleware/decorators"
590
+ "method": "HTTP method CHÍNH XÁC",
591
+ "path": "Path CHÍNH XÁC từ route",
592
+ "description": "Description CHI TIẾT",
593
+ "handler": "Handler function name",
594
+ "authentication": "Auth requirement (Required/Optional/None)",
595
+ "authorization": "Role/Permission requirements",
596
+ "validation": "Input validation rules",
597
+ "requestBody": "Request body schema",
598
+ "responseType": "Response type"
453
599
  }
454
600
  ],
455
601
  "dependencies": [
456
602
  {
457
603
  "component": "Component name TỪ IMPORTS",
458
- "purpose": "Purpose SUY từ cách dùng",
459
- "type": "Type TỪ file path của dependency"
604
+ "purpose": "Purpose CHI TIẾT",
605
+ "type": "Dependency type (Import/Injection/Composition)"
460
606
  }
461
607
  ],
462
- "designPatterns": ["Patterns PHÁT HIỆN từ code structure"],
463
608
  "methods": [
464
609
  {
465
610
  "name": "Method name TỪ CODE",
466
- "purpose": "Purpose TỪ function name hoặc comments",
467
- "parameters": ["Params TỪ function signature"],
468
- "returnType": "Return type TỪ code hoặc TypeScript types"
611
+ "purpose": "Purpose CHI TIẾT",
612
+ "parameters": ["TẤT CẢ params với types"],
613
+ "returnType": "Return type CHÍNH XÁC",
614
+ "async": "true/false",
615
+ "visibility": "public/private/protected"
469
616
  }
470
- ]
617
+ ],
618
+ "designPatterns": ["Patterns PHÁT HIỆN được"]
471
619
  }
472
620
  ],
473
621
  "middlewareChain": [
474
622
  {
475
623
  "name": "Middleware name TỪ FILES",
476
- "order": "Order number NẾUPHÁT HIỆN được",
477
- "purpose": "Purpose TỪ middleware code",
478
- "appliesTo": "Routes THẤY middleware được apply"
624
+ "order": "Execution order number",
625
+ "purpose": "Purpose CHI TIẾT",
626
+ "appliesTo": "Routes áp dụng (Global/Specific routes)",
627
+ "type": "Middleware type (Auth/Validation/Logging/ErrorHandling...)"
479
628
  }
480
629
  ],
481
630
  "dataFlow": {
482
- "requestFlow": "Flow PHÁT HIỆN từ code (Client → Middleware → Controller → Service...)",
483
- "responseFlow": "Response flow TỪ code"
631
+ "requestFlow": "Flow CHI TIẾT (Client → Route → Middleware → Controller → Service → Repository → Database)",
632
+ "responseFlow": "Response flow (Database → Repository → Service → Controller → Response)",
633
+ "errorFlow": "Error handling flow"
484
634
  },
485
635
  "crossCuttingConcerns": [
486
636
  {
487
- "name": "Concern TÌM ĐƯỢC (Logging/Caching/ErrorHandling...)",
488
- "implementation": "Implementation type TỪ code",
489
- "components": ["Components THỰC SỰ implement concern này"]
637
+ "name": "Concern name (Logging/Caching/ErrorHandling/Security/Monitoring...)",
638
+ "implementation": "Implementation CHI TIẾT",
639
+ "components": ["TẤT CẢ components liên quan"],
640
+ "strategy": "Strategy used"
490
641
  }
491
- ]
642
+ ],
643
+ "securityMeasures": {
644
+ "authentication": "Auth methods CHI TIẾT",
645
+ "authorization": "Authorization strategy",
646
+ "inputValidation": "Validation approach",
647
+ "encryption": "Encryption methods"
648
+ }
492
649
  }
493
650
 
651
+ YÊU CẦU ĐẦY ĐỦ:
652
+ ✅ Components: PHẢI liệt kê TẤT CẢ components từ files scan
653
+ ✅ API Endpoints: PHẢI có TẤT CẢ routes (50+, 100+, 200+...)
654
+ ✅ Dependencies: PHẢI map TẤT CẢ imports/dependencies
655
+ ✅ Middleware: PHẢI liệt kê TẤT CẢ middleware và order
656
+ ✅ Layers: PHẢI phân loại components vào layers
657
+
494
658
  LƯU Ý:
495
- - Nếu KHÔNG TÌM THẤY controllers → components array sẽ rỗng hoặc chỉ có những cái TÌM ĐƯỢC
496
- - Nếu KHÔNG có routes → apiEndpoints sẽ rỗng []
659
+ - Nếu KHÔNG TÌM THẤY controllers → components array rỗng cho layer đó
660
+ - Nếu KHÔNG có routes → apiEndpoints rỗng []
497
661
  - CHỈ liệt kê những gì CÓ TRONG CODE
498
- - Nếu không chắc ghi "Detected from code" thay vì bịa
662
+ - PHẢI CHI TIẾT ĐẦY ĐỦ
499
663
  `;
500
664
 
501
665
  const result = await model.generateContent(prompt);