@hd-agent-kit/cli 1.3.1 → 1.4.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.
@@ -15,7 +15,7 @@ description: Analyze bundle size, render performance, and Core Web Vitals with s
15
15
 
16
16
  - **Ölçmeden optimize etme.** Önce darboğazı tespit et, sonra çöz.
17
17
  - **Premature optimization is the root of all evil.** Gerçek sorunlara odaklan.
18
- - **Core Web Vitals odaklı ol.** LCP, INP, CLS metrikleri öncelikli.
18
+ - **Proje tipine göre öncelik belirle:** Frontend → Core Web Vitals; Backend response time + DB; CLI → startup time + memory.
19
19
  - **Bundle size'ı her zaman göz önünde bulundur.** Her KB önemli, özellikle mobilde.
20
20
 
21
21
  ---
@@ -23,16 +23,21 @@ description: Analyze bundle size, render performance, and Core Web Vitals with s
23
23
  ## Kullanım Formatları
24
24
 
25
25
  ```
26
- /performance-check ← Tüm proje analizi
26
+ /performance-check ← Tüm proje analizi (proje tipine göre uyarlanır)
27
27
  /performance-check src/pages/Home.tsx ← Belirli sayfa/component
28
28
  /performance-check bundle ← Sadece bundle analizi
29
- /performance-check render ← Sadece render performansı
29
+ /performance-check render ← Sadece render performansı (frontend)
30
+ /performance-check api ← Sadece API/backend performansı
31
+ /performance-check db ← Sadece veritabanı sorgu analizi
30
32
  ```
31
33
 
32
34
  ---
33
35
 
34
36
  ## Analiz Kategorileri
35
37
 
38
+ > **Proje tipine göre uygula:** Frontend/Fullstack → Kategori 1-5; Backend API → Kategori 6-7; CLI/Araç → Kategori 8.
39
+ > Karma projeler (fullstack) için tüm ilgili kategorileri uygula.
40
+
36
41
  ### Kategori 1: Bundle Analizi
37
42
 
38
43
  Projenin bundle yapısını incele:
@@ -198,24 +203,120 @@ Component render davranışını analiz et:
198
203
 
199
204
  ---
200
205
 
206
+ ### Kategori 6: Backend & API Performansı *(Standalone API / Fullstack backend için)*
207
+
208
+ ```
209
+ ⚡ Backend Performansı:
210
+
211
+ 1. Response Time Analizi:
212
+ ├── Yavaş endpoint'ler tespit edilmiş mi? (>200ms P95)
213
+ ├── Logging/monitoring var mı? (pino, morgan, Datadog vs.)
214
+ ├── Timeout değerleri uygun mu?
215
+ └── Async işlemler non-blocking mı?
216
+
217
+ 2. Veritabanı Sorgu Optimizasyonu:
218
+ ├── N+1 sorgu riski: [var/yok — ORM include/join kullanımı]
219
+ ├── Index kullanımı: [sorgu planları incelendi mi?]
220
+ ├── Bağlantı havuzu (connection pool): [yapılandırılmış mı?]
221
+ ├── Büyük veri setleri cursor/stream ile mi işleniyor?
222
+ └── Migration'lar optimize mi? (büyük tablo değişimleri)
223
+
224
+ 3. Caching Stratejisi:
225
+ ├── HTTP Cache-Control header'ları: [var/yok]
226
+ ├── Uygulama seviyesi cache (Redis, in-memory): [var/yok]
227
+ ├── Cache invalidation stratejisi: [var/yok]
228
+ └── Duplicate API çağrılarını önleme: [var/yok]
229
+
230
+ 4. Eşzamanlılık & Ölçeklenebilirlik:
231
+ ├── Rate limiting: [var/yok — hangi endpoint'lerde]
232
+ ├── Concurrency limitler uygun mu?
233
+ ├── CPU-yoğun işlemler worker_threads ile mi?
234
+ └── Horizontal scaling engelleyen state var mı? (in-memory session vs.)
235
+ ```
236
+
237
+ **Kontrol Listesi:**
238
+
239
+ | # | Kontrol | Durum | Etki |
240
+ |---|---------|-------|------|
241
+ | 1 | N+1 sorgu riski var mı? | ✅/❌ | Yüksek |
242
+ | 2 | DB connection pool yapılandırılmış mı? | ✅/❌ | Yüksek |
243
+ | 3 | Yavaş sorgular için index var mı? | ✅/❌ | Yüksek |
244
+ | 4 | Rate limiting aktif mi? | ✅/❌ | Orta |
245
+ | 5 | Caching katmanı var mı? | ✅/❌ | Orta |
246
+ | 6 | CPU-yoğun işlemler event loop'u bloke ediyor mu? | ✅/❌ | Yüksek |
247
+ | 7 | Response time izleniyor mu? | ✅/❌ | Orta |
248
+
249
+ ---
250
+
251
+ ### Kategori 7: Bellek & Process Yönetimi *(Node.js projeleri için)*
252
+
253
+ ```
254
+ 🧠 Bellek & Process:
255
+
256
+ 1. Bellek Kullanımı:
257
+ ├── Bellek sızıntısı riski: [event listener temizleme, büyük closure'lar]
258
+ ├── Stream kullanımı: [büyük dosyalar için createReadStream/createWriteStream]
259
+ ├── --max-old-space-size limiti: [tanımlı mı?]
260
+ └── Buffer kullanımı: [gereksiz kopyalama var mı?]
261
+
262
+ 2. Event Loop Sağlığı:
263
+ ├── Senkron bloke eden işlemler: [var/yok — fs.readFileSync, execSync gibi]
264
+ ├── setInterval/setTimeout temizleme: [clearInterval/clearTimeout çağrılıyor mu?]
265
+ └── Uzun süren hesaplamalar: [ana thread'i bloke ediyor mu?]
266
+
267
+ 3. Graceful Shutdown:
268
+ ├── SIGTERM/SIGINT handler'ları: [var/yok]
269
+ ├── Açık DB bağlantıları kapatılıyor mu?
270
+ └── In-flight request'ler tamamlanıyor mu?
271
+ ```
272
+
273
+ ---
274
+
275
+ ### Kategori 8: CLI & Build Araçları Performansı *(CLI / Tooling projeleri için)*
276
+
277
+ ```
278
+ 🛠️ CLI Performansı:
279
+
280
+ 1. Startup Time:
281
+ ├── Gereksiz require/import var mı? (lazy load edilebilir mi?)
282
+ ├── Ağır modüller conditional import ile yükleniyor mu?
283
+ └── --version ve --help hızlı mı? (<100ms)
284
+
285
+ 2. Dosya İşleme Performansı:
286
+ ├── Büyük dosyalar stream ile işleniyor mu?
287
+ ├── Paralel işlemler Promise.all ile mi?
288
+ └── Gereksiz dosya okuma/yazma döngüsü var mı?
289
+
290
+ 3. Bellek Kullanımı:
291
+ ├── Büyük JSON/veri setleri bellekte tutuluyor mu?
292
+ └── İşlem sonrası geçici dosyalar temizleniyor mu?
293
+ ```
294
+
295
+ ---
296
+
201
297
  ## Puanlama Sistemi
202
298
 
203
299
  Her kategori için 0-100 puan ver:
204
300
 
205
301
  ```
206
- 📊 Performans Raporu:
207
-
208
- ┌──────────────────────┬───────┬──────────┐
209
- │ Kategori │ Puan │ Seviye │
210
- ├──────────────────────┼───────┼──────────┤
211
- Bundle Size XX/100 🟢/🟡/🔴│
212
- │ Render Performansı │ XX/100│ 🟢/🟡/🔴│
213
- Core Web Vitals │ XX/100│ 🟢/🟡/🔴│
214
- Network & Caching │ XX/100│ 🟢/🟡/🔴│
215
- Asset Optimizasyonu │ XX/100│ 🟢/🟡/🔴│
216
- ├──────────────────────┼───────┼──────────┤
217
- GENEL │ XX/100│ 🟢/🟡/🔴│
218
- └──────────────────────┴───────┴──────────┘
302
+ 📊 Performans Raporu: [Proje Adı] — [Frontend / Backend / CLI]
303
+
304
+ Sadece proje tipine uygun kategorileri ekle:
305
+
306
+ ┌──────────────────────────────┬───────┬──────────┐
307
+ Kategori │ Puan Seviye
308
+ ├──────────────────────────────┼───────┼──────────┤
309
+ Bundle Size (FE) │ XX/100│ 🟢/🟡/🔴│ ← Frontend/Fullstack
310
+ Render Performansı (FE) │ XX/100│ 🟢/🟡/🔴│ ← Frontend/Fullstack
311
+ Core Web Vitals (FE) │ XX/100│ 🟢/🟡/🔴│ ← Frontend/Fullstack
312
+ │ Network & Caching │ XX/100│ 🟢/🟡/🔴│ ← Tüm tipler
313
+ Asset Optimizasyonu (FE) │ XX/100│ 🟢/🟡/🔴│ ← Frontend/Fullstack
314
+ │ Backend & API Perf (BE) │ XX/100│ 🟢/🟡/🔴│ ← Backend/Fullstack
315
+ │ Bellek & Process (BE) │ XX/100│ 🟢/🟡/🔴│ ← Backend/CLI
316
+ │ CLI Performansı (CLI) │ XX/100│ 🟢/🟡/🔴│ ← CLI/Tooling
317
+ ├──────────────────────────────┼───────┼──────────┤
318
+ │ GENEL │ XX/100│ 🟢/🟡/🔴│
319
+ └──────────────────────────────┴───────┴──────────┘
219
320
 
220
321
  🟢 90-100: Mükemmel
221
322
  🟡 60-89: İyileştirme alanı var
@@ -1,12 +1,12 @@
1
1
  ---
2
2
  name: security-scan
3
- description: Run dependency audit, detect XSS/CSRF risks, check env variables, and report security issues
3
+ description: Run dependency audit, detect OWASP Top 10 risks, check auth/env/injection vulnerabilities, and report security issues for any project type
4
4
  ---
5
5
 
6
6
  # /security-scan — Güvenlik Tarama Skill'i
7
7
 
8
8
  > **Tetikleyici:** `/security-scan`
9
- > **Amaç:** Dependency audit, XSS/CSRF risk tespiti, env variable kontrolü ve güvenlik best practice'lerine uyum raporu oluşturmak.
9
+ > **Amaç:** Dependency audit, OWASP Top 10 risk tespiti, auth güvenliği, env variable kontrolü ve proje tipine göre güvenlik analizi.
10
10
  > **Çıktı:** Kategorize edilmiş güvenlik raporu + düzeltme önerileri
11
11
 
12
12
  ---
@@ -219,7 +219,55 @@ description: Run dependency audit, detect XSS/CSRF risks, check env variables, a
219
219
  └── Rate limiting: [var/yok]
220
220
  ```
221
221
 
222
- ### Kategori 7: Frontend-Specific Güvenlik
222
+ ### Kategori 7: Backend-Specific Güvenlik *(Standalone API / Fullstack backend için)*
223
+
224
+ ```
225
+ 🖥️ Backend Güvenlik:
226
+
227
+ 1. Path Traversal & Dosya Sistemi:
228
+ ├── Kullanıcı girdisi dosya yolunda kullanılıyor mu?: [var/yok]
229
+ ├── path.resolve() + allowlist kontrolü: [var/yok]
230
+ ├── Upload dosya adları sanitize ediliyor mu?: [var/yok]
231
+ └── Sembolik link takibi engelleniyor mu?: [var/yok]
232
+
233
+ 2. Mass Assignment:
234
+ ├── ORM modellerine doğrudan req.body aktarılıyor mu?: [var/yok — risk]
235
+ ├── Whitelist (allowedFields) kontrolü: [var/yok]
236
+ ├── Hassas alanlar (role, isAdmin) otomatik güncellenebiliyor mu?: [var/yok]
237
+ └── Zod/validation şeması ile alan kısıtlaması: [var/yok]
238
+
239
+ 3. Server-Side Request Forgery (SSRF):
240
+ ├── Kullanıcı girdisinden URL oluşturuluyor mu?: [var/yok]
241
+ ├── İzin verilen domain allowlist'i: [var/yok]
242
+ ├── Internal IP/localhost erişimi engelleniyor mu?: [var/yok]
243
+ └── Metadata endpoint'lerine erişim (cloud): [var/yok]
244
+
245
+ 4. Process & Komut Enjeksiyonu:
246
+ ├── child_process / exec'e kullanıcı girdisi geçiyor mu?: [var/yok — KRİTİK]
247
+ ├── Shell=true ile spawn kullanımı: [var/yok — riskli]
248
+ ├── eval() / new Function() kullanımı: [var/yok]
249
+ └── Template engine injection riski: [var/yok]
250
+
251
+ 5. Güvenli Yanıt Başlıkları:
252
+ ├── helmet.js veya manuel header'lar: [var/yok]
253
+ ├── X-Powered-By gizlenmiş mi?: [Evet/Hayır]
254
+ ├── Server header gizlenmiş mi?: [Evet/Hayır]
255
+ └── Error response'larda stack trace sızıyor mu?: [var/yok — KRİTİK]
256
+ ```
257
+
258
+ **Kontrol Listesi:**
259
+
260
+ | # | Kontrol | Durum | Etki |
261
+ |---|---------|-------|------|
262
+ | 1 | Path traversal koruması var mı? | ✅/❌ | Kritik |
263
+ | 2 | Mass assignment koruması var mı? | ✅/❌ | Yüksek |
264
+ | 3 | SSRF koruması var mı? | ✅/❌ | Yüksek |
265
+ | 4 | exec/shell'e kullanıcı girdisi geçiyor mu? | ✅/❌ | Kritik |
266
+ | 5 | Stack trace production'da gizleniyor mu? | ✅/❌ | Orta |
267
+
268
+ ---
269
+
270
+ ### Kategori 8: Frontend-Specific Güvenlik *(Frontend / Fullstack UI için)*
223
271
 
224
272
  ```
225
273
  🖥️ Frontend Güvenlik:
@@ -250,19 +298,22 @@ description: Run dependency audit, detect XSS/CSRF risks, check env variables, a
250
298
  ```
251
299
  🔒 Güvenlik Raporu:
252
300
 
253
- ┌──────────────────────────┬───────┬──────────┐
254
- │ Kategori │ Puan │ Seviye │
255
- ├──────────────────────────┼───────┼──────────┤
256
- Dependency Güvenliği XX/100 🟢/🟡/🔴│
257
- │ XSS Koruması │ XX/100│ 🟢/🟡/🔴│
258
- CSRF & Request Security │ XX/100│ 🟢/🟡/🔴│
259
- Auth & Authorization │ XX/100│ 🟢/🟡/🔴│
260
- Environment & Secrets │ XX/100│ 🟢/🟡/🔴│
261
- Input Validation │ XX/100│ 🟢/🟡/🔴│
262
- Frontend Security │ XX/100│ 🟢/🟡/🔴│
263
- ├──────────────────────────┼───────┼──────────┤
264
- GENEL │ XX/100│ 🟢/🟡/🔴│
265
- └──────────────────────────┴───────┴──────────┘
301
+ Sadece proje tipine uygun kategorileri tabloya ekle:
302
+
303
+ ┌─────────────────────────────────┬───────┬──────────┐
304
+ Kategori │ Puan Seviye
305
+ ├─────────────────────────────────┼───────┼──────────┤
306
+ Dependency Güvenliği │ XX/100│ 🟢/🟡/🔴│ ← Tüm tipler
307
+ XSS Koruması (FE) │ XX/100│ 🟢/🟡/🔴│ ← Frontend/Fullstack
308
+ CSRF & Request Security (FE) │ XX/100│ 🟢/🟡/🔴│ ← Frontend/Fullstack
309
+ Auth & Authorization │ XX/100│ 🟢/🟡/🔴│ ← Tüm tipler
310
+ Environment & Secrets │ XX/100│ 🟢/🟡/🔴│ ← Tüm tipler
311
+ │ Input Validation │ XX/100│ 🟢/🟡/🔴│ ← Tüm tipler
312
+ Backend Security (BE) │ XX/100│ 🟢/🟡/🔴│ ← Backend/Fullstack
313
+ │ Frontend Security (FE) │ XX/100│ 🟢/🟡/🔴│ ← Frontend/Fullstack
314
+ ├─────────────────────────────────┼───────┼──────────┤
315
+ │ GENEL │ XX/100│ 🟢/🟡/🔴│
316
+ └─────────────────────────────────┴───────┴──────────┘
266
317
 
267
318
  🟢 90-100: Güvenli
268
319
  🟡 60-89: İyileştirme gerekli
@@ -1,19 +1,19 @@
1
1
  ---
2
2
  name: write-tests
3
- description: Generate comprehensive test files for components, hooks, and utilities following project conventions
3
+ description: Generate comprehensive test files for components, hooks, utilities, API endpoints, services, and CLI tools following project conventions
4
4
  ---
5
5
 
6
6
  # /write-tests — Test Yazma Skill'i
7
7
 
8
8
  > **Tetikleyici:** `/write-tests [dosya/modül]`
9
- > **Amaç:** Belirtilen component, hook veya utility için kapsamlı test dosyası üretmek.
9
+ > **Amaç:** Belirtilen component, hook, utility, API endpoint, service veya CLI araç için kapsamlı test dosyası üretmek.
10
10
  > **Çıktı:** Proje convention'ına uygun test dosyası
11
11
 
12
12
  ---
13
13
 
14
14
  ## Temel İlkeler
15
15
 
16
- - **Kullanıcı davranışını test et, implementation detail'leri değil.** Testing Library felsefesi.
16
+ - **Davranışı test et, implementasyonu değil.** Neyin yapıldığını test et, nasıl yapıldığını değil.
17
17
  - **Her test bağımsız (isolated) olmalı.** Testler arası paylaşılan state olmamalı.
18
18
  - **Mock'ları minimum tut.** Gerçek modülleri mümkün olduğunca kullan.
19
19
  - **Test piramidini uygula.** Çok unit test, az integration test, minimal E2E test.
@@ -43,13 +43,13 @@ Hedef dosyayı oku ve şunları tespit et:
43
43
  ```
44
44
  📋 Test Hedefi Analizi:
45
45
  ├── Hedef dosya: [dosya yolu]
46
- ├── Dosya tipi: [component / hook / util / service / page]
47
- ├── Export'lar: [fonksiyon/component listesi]
48
- ├── Bağımlılıklar: [import edilen modüller]
46
+ ├── Dosya tipi: [component / hook / util / service / route / middleware / controller / CLI command]
47
+ ├── Export'lar: [fonksiyon/class/component listesi]
48
+ ├── Bağımlılıklar: [import edilen modüller — mock edilmesi gerekenler]
49
49
  ├── Props/Parametreler: [tip bilgileri]
50
- ├── Side effect'ler: [API çağrısı, localStorage, timer vs.]
50
+ ├── Side effect'ler: [API çağrısı, DB sorgusu, dosya I/O, timer, env var vs.]
51
51
  ├── Mevcut test: [var/yok, dosya yolu]
52
- └── Test runner: [Vitest / Jest / projeden tespit et]
52
+ └── Test runner: [Vitest / Jest / node:test — projeden tespit et]
53
53
  ```
54
54
 
55
55
  ### Adım 2: Proje Test Convention Tespiti
@@ -71,9 +71,9 @@ Projede mevcut testleri inceleyerek convention belirle:
71
71
 
72
72
  ### Adım 3: Test Senaryoları Planlama
73
73
 
74
- Her dosya tipi için farklı senaryo stratejisi:
74
+ Her dosya tipi için farklı senaryo stratejisi. **Proje tipine göre uygun bölümü uygula.**
75
75
 
76
- #### Component Test Senaryoları
76
+ #### Component Test Senaryoları *(Frontend / Fullstack UI için)*
77
77
  ```
78
78
  📝 Test Planı — [ComponentName]:
79
79
 
@@ -114,7 +114,7 @@ Her dosya tipi için farklı senaryo stratejisi:
114
114
  □ Screen reader uyumlu mu?
115
115
  ```
116
116
 
117
- #### Hook Test Senaryoları
117
+ #### Hook Test Senaryoları *(Frontend / Fullstack UI için)*
118
118
  ```
119
119
  📝 Test Planı — [useHookName]:
120
120
 
@@ -144,7 +144,8 @@ Her dosya tipi için farklı senaryo stratejisi:
144
144
  □ Invalid parametre geçilmesi
145
145
  ```
146
146
 
147
- #### Utility/Service Test Senaryoları
147
+ #### Utility/Service Test Senaryoları *(Tüm proje tipleri için)*
148
+
148
149
  ```
149
150
  📝 Test Planı — [functionName]:
150
151
 
@@ -167,6 +168,183 @@ Her dosya tipi için farklı senaryo stratejisi:
167
168
  □ Return tipi doğru çıkarılıyor mu?
168
169
  ```
169
170
 
171
+ #### API Endpoint Test Senaryoları *(Backend / Fullstack API için)*
172
+
173
+ ```
174
+ 📝 Test Planı — [METHOD /path]:
175
+
176
+ 1. Başarılı İstek (Happy Path):
177
+ □ Geçerli payload ile doğru response kodu (200/201/204)
178
+ □ Response body şeması doğru mu?
179
+ □ Response header'ları doğru mu? (Content-Type, Location vs.)
180
+
181
+ 2. Kimlik Doğrulama & Yetkilendirme:
182
+ □ Token/session olmadan → 401 Unauthorized
183
+ □ Yetersiz yetki ile → 403 Forbidden
184
+ □ Geçerli token ile → beklenen response
185
+
186
+ 3. Validasyon Hataları:
187
+ □ Eksik zorunlu alan → 400 Bad Request + açıklayıcı hata
188
+ □ Hatalı veri tipi → 400 + alan bazlı hata mesajı
189
+ □ Sınır değer ihlali (çok uzun string, negatif sayı) → 400
190
+
191
+ 4. Kaynak Bulunamadı:
192
+ □ Var olmayan ID ile → 404 Not Found
193
+ □ Silinmiş kaynak → 404 veya 410 Gone
194
+
195
+ 5. Çakışma Durumları:
196
+ □ Duplicate kayıt → 409 Conflict
197
+ □ Eşzamanlı güncelleme → 409 veya optimistic lock
198
+
199
+ 6. Hata Senaryoları:
200
+ □ DB bağlantısı kesilirse → 503 Service Unavailable (mock ile)
201
+ □ Harici servis yanıt vermezse → timeout ve fallback davranışı
202
+
203
+ 7. Edge Case'ler:
204
+ □ Büyük payload → boyut limiti kontrolü
205
+ □ SQL/NoSQL injection girişimi → sanitize edilmiş mi?
206
+ □ Rate limit aşımı → 429 Too Many Requests
207
+ ```
208
+
209
+ **Supertest ile endpoint testi:**
210
+
211
+ ```typescript
212
+ import request from 'supertest';
213
+ import { app } from '../app';
214
+ import { db } from '../db/client';
215
+
216
+ describe('POST /api/users', () => {
217
+ beforeEach(async () => {
218
+ await db.user.deleteMany(); // test izolasyonu
219
+ });
220
+
221
+ it('should create a user and return 201', async () => {
222
+ const res = await request(app)
223
+ .post('/api/users')
224
+ .send({ name: 'Test User', email: 'test@example.com' })
225
+ .expect(201);
226
+
227
+ expect(res.body).toMatchObject({
228
+ id: expect.any(String),
229
+ name: 'Test User',
230
+ email: 'test@example.com',
231
+ });
232
+ });
233
+
234
+ it('should return 400 for missing email', async () => {
235
+ const res = await request(app)
236
+ .post('/api/users')
237
+ .send({ name: 'Test User' })
238
+ .expect(400);
239
+
240
+ expect(res.body.code).toBe('VALIDATION_ERROR');
241
+ expect(res.body.details).toHaveProperty('email');
242
+ });
243
+
244
+ it('should return 401 without auth token', async () => {
245
+ await request(app)
246
+ .post('/api/users')
247
+ .send({ name: 'Test', email: 'a@b.com' })
248
+ .expect(401);
249
+ });
250
+ });
251
+ ```
252
+
253
+ #### Middleware Test Senaryoları *(Backend için)*
254
+
255
+ ```
256
+ 📝 Test Planı — [middlewareName]:
257
+
258
+ 1. Geçerli istek → next() çağrılıyor mu?
259
+ 2. Geçersiz/yetersiz veri → next() çağrılmadan hata response'u
260
+ 3. Request nesnesini doğru şekilde zenginleştiriyor mu? (req.user vs.)
261
+ 4. Loglama/metrik side effect'leri doğru tetikleniyor mu?
262
+ 5. Asenkron hata → next(err) ile iletiliyor mu?
263
+ ```
264
+
265
+ ```typescript
266
+ import { authMiddleware } from '../middleware/auth';
267
+
268
+ describe('authMiddleware', () => {
269
+ const mockNext = vi.fn();
270
+ const mockRes = { status: vi.fn().mockReturnThis(), json: vi.fn() } as any;
271
+
272
+ it('should call next() with valid token', async () => {
273
+ const req = { headers: { authorization: 'Bearer valid-token' } } as any;
274
+ vi.mocked(verifyToken).mockResolvedValue({ userId: '123' });
275
+
276
+ await authMiddleware(req, mockRes, mockNext);
277
+
278
+ expect(req.user).toEqual({ userId: '123' });
279
+ expect(mockNext).toHaveBeenCalledWith(); // hatasız
280
+ });
281
+
282
+ it('should return 401 without token', async () => {
283
+ const req = { headers: {} } as any;
284
+
285
+ await authMiddleware(req, mockRes, mockNext);
286
+
287
+ expect(mockRes.status).toHaveBeenCalledWith(401);
288
+ expect(mockNext).not.toHaveBeenCalled();
289
+ });
290
+ });
291
+ ```
292
+
293
+ #### CLI Araç Test Senaryoları *(CLI / Tooling için)*
294
+
295
+ ```
296
+ 📝 Test Planı — [komut adı]:
297
+
298
+ 1. Happy Path:
299
+ □ Beklenen argümanlarla → beklenen çıktı ve exit code 0
300
+ □ Oluşturulan dosyalar doğru içeriğe sahip mi?
301
+ □ Yan etkiler (dosya oluşturma, git komutu) gerçekleşiyor mu?
302
+
303
+ 2. Flag Davranışı:
304
+ □ --force flag'i ile onay sorulmadan devam ediyor mu?
305
+ □ --dry-run ile gerçek değişiklik yapılmıyor mu?
306
+ □ --help ile yardım metni gösteriliyor mu?
307
+
308
+ 3. Hata Durumları:
309
+ □ Bilinmeyen komut → açıklayıcı hata + exit code 1
310
+ □ Dosya zaten varken (--force olmadan) → onay soruluyor mu?
311
+ □ İzin hatası (erişilemeyen dizin) → anlamlı hata mesajı
312
+
313
+ 4. Cross-Platform:
314
+ □ Windows ve Unix yol separator'ları doğru işleniyor mu?
315
+ ```
316
+
317
+ ```typescript
318
+ import { execSync } from 'child_process';
319
+ import * as fs from 'fs';
320
+ import * as path from 'path';
321
+ import * as os from 'os';
322
+
323
+ describe('cli init --force', () => {
324
+ let testDir: string;
325
+
326
+ beforeEach(() => {
327
+ testDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cli-test-'));
328
+ });
329
+
330
+ afterEach(() => {
331
+ fs.rmSync(testDir, { recursive: true, force: true });
332
+ });
333
+
334
+ it('should create AGENTS.md in target directory', () => {
335
+ execSync(`node bin/cli.js init --force`, { cwd: testDir });
336
+
337
+ expect(fs.existsSync(path.join(testDir, 'AGENTS.md'))).toBe(true);
338
+ });
339
+
340
+ it('should exit with code 1 for unknown command', () => {
341
+ expect(() => {
342
+ execSync(`node bin/cli.js unknown-cmd`, { stdio: 'pipe' });
343
+ }).toThrow();
344
+ });
345
+ });
346
+ ```
347
+
170
348
  ### Adım 4: Test Dosyası Oluşturma
171
349
 
172
350
  Test planını onaylandıktan sonra, proje convention'ına uygun test dosyası yaz: