@atlashub/smartstack-cli 3.35.0 → 3.37.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.
@@ -0,0 +1,440 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Extract Business Rules from SmartStack Domain Entities and Unit Tests
4
+ *
5
+ * Usage:
6
+ * node extract-business-rules.ts --module users --app-path "D:/01 - projets/SmartStack.app/02-Develop"
7
+ *
8
+ * Output: JSON array of DocBusinessRule objects
9
+ */
10
+
11
+ import * as fs from 'fs';
12
+ import * as path from 'path';
13
+ import { glob } from 'glob';
14
+
15
+ interface DocBusinessRule {
16
+ id: string; // e.g., "BR-001"
17
+ name: string; // e.g., "Email requis"
18
+ category: string; // e.g., "Validation", "Sécurité", "Logique métier"
19
+ statement: string; // Human-readable business rule description
20
+ }
21
+
22
+ interface ExtractedRule {
23
+ source: 'domain' | 'test';
24
+ exception: string; // Exception message
25
+ context: string; // Method or test name
26
+ category?: string;
27
+ }
28
+
29
+ /**
30
+ * Parse command line arguments
31
+ */
32
+ function parseArgs(): { module: string; appPath: string } {
33
+ const args = process.argv.slice(2);
34
+ const moduleIndex = args.indexOf('--module');
35
+ const appPathIndex = args.indexOf('--app-path');
36
+
37
+ if (moduleIndex === -1 || appPathIndex === -1) {
38
+ console.error('Usage: node extract-business-rules.ts --module <module-name> --app-path <path-to-app>');
39
+ process.exit(1);
40
+ }
41
+
42
+ return {
43
+ module: args[moduleIndex + 1],
44
+ appPath: args[appPathIndex + 1],
45
+ };
46
+ }
47
+
48
+ /**
49
+ * Find domain entity file for given module
50
+ * Tries both singular and plural forms (e.g., users → User.cs)
51
+ */
52
+ async function findEntityFile(appPath: string, module: string): Promise<string | null> {
53
+ const domainPath = path.join(appPath, 'src/SmartStack.Domain');
54
+
55
+ // Try singular form first (most common: users → User.cs)
56
+ const singularForm = capitalize(singularize(module));
57
+ const singularPattern = `**/${singularForm}.cs`;
58
+
59
+ try {
60
+ let files = await glob(singularPattern, { cwd: domainPath, absolute: true });
61
+ if (files.length > 0) {
62
+ return files[0];
63
+ }
64
+
65
+ // Fallback to plural form
66
+ const pluralForm = capitalize(module);
67
+ const pluralPattern = `**/${pluralForm}.cs`;
68
+ files = await glob(pluralPattern, { cwd: domainPath, absolute: true });
69
+ return files.length > 0 ? files[0] : null;
70
+ } catch (error) {
71
+ console.error('Error finding entity:', error);
72
+ return null;
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Find unit test file for given entity
78
+ * Tries both singular and plural forms (e.g., users → UserTests.cs)
79
+ */
80
+ async function findTestFile(appPath: string, module: string): Promise<string | null> {
81
+ const testsPath = path.join(appPath, 'tests/SmartStack.Tests.Unit/Domain');
82
+
83
+ // Try singular form first (most common: users → UserTests.cs)
84
+ const singularForm = capitalize(singularize(module));
85
+ const singularPattern = `**/${singularForm}Tests.cs`;
86
+
87
+ try {
88
+ let files = await glob(singularPattern, { cwd: testsPath, absolute: true });
89
+ if (files.length > 0) {
90
+ return files[0];
91
+ }
92
+
93
+ // Fallback to plural form
94
+ const pluralForm = capitalize(module);
95
+ const pluralPattern = `**/${pluralForm}Tests.cs`;
96
+ files = await glob(pluralPattern, { cwd: testsPath, absolute: true });
97
+ return files.length > 0 ? files[0] : null;
98
+ } catch (error) {
99
+ console.error('Error finding test file:', error);
100
+ return null;
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Extract business rules from domain entity
106
+ * Looks for:
107
+ * - Guard clauses with thrown DomainExceptions
108
+ * - Validation logic in Create/Update methods
109
+ */
110
+ function extractFromDomainEntity(entityPath: string): ExtractedRule[] {
111
+ const content = fs.readFileSync(entityPath, 'utf-8');
112
+ const lines = content.split('\n');
113
+ const rules: ExtractedRule[] = [];
114
+
115
+ let currentMethod = '';
116
+
117
+ for (let i = 0; i < lines.length; i++) {
118
+ const line = lines[i];
119
+
120
+ // Track current method for context
121
+ const methodMatch = line.match(/public\s+(?:static\s+)?(?:\w+\??)\s+(\w+)\s*\(/);
122
+ if (methodMatch) {
123
+ currentMethod = methodMatch[1];
124
+ }
125
+
126
+ // Look for throw statements with DomainException
127
+ // Example: throw new DomainException("Email is required");
128
+ const throwMatch = line.match(/throw\s+new\s+(?:\w+\.)?DomainException\s*\(\s*"([^"]+)"\s*\)/);
129
+ if (throwMatch) {
130
+ const exception = throwMatch[1];
131
+ rules.push({
132
+ source: 'domain',
133
+ exception,
134
+ context: currentMethod,
135
+ category: inferCategory(exception, currentMethod),
136
+ });
137
+ continue;
138
+ }
139
+
140
+ // Look for guard clauses (if ... throw pattern)
141
+ // Example: if (string.IsNullOrWhiteSpace(email))
142
+ const guardMatch = line.match(/if\s*\((.+)\)/);
143
+ if (guardMatch && i + 1 < lines.length) {
144
+ const nextLine = lines[i + 1].trim();
145
+ const guardThrow = nextLine.match(/throw\s+new\s+(?:\w+\.)?DomainException\s*\(\s*"([^"]+)"\s*\)/);
146
+ if (guardThrow) {
147
+ const condition = guardMatch[1].trim();
148
+ const exception = guardThrow[1];
149
+ rules.push({
150
+ source: 'domain',
151
+ exception,
152
+ context: `${currentMethod} (${condition})`,
153
+ category: inferCategory(exception, currentMethod),
154
+ });
155
+ }
156
+ }
157
+ }
158
+
159
+ return rules;
160
+ }
161
+
162
+ /**
163
+ * Extract business rules from unit tests
164
+ * Looks for test methods that assert DomainExceptions
165
+ */
166
+ function extractFromTests(testPath: string): ExtractedRule[] {
167
+ const content = fs.readFileSync(testPath, 'utf-8');
168
+ const lines = content.split('\n');
169
+ const rules: ExtractedRule[] = [];
170
+
171
+ let currentTestName = '';
172
+
173
+ for (let i = 0; i < lines.length; i++) {
174
+ const line = lines[i];
175
+
176
+ // Track current test method
177
+ // Example: public void Create_WithEmptyEmail_ThrowsDomainException()
178
+ const testMatch = line.match(/public\s+(?:void|Task)\s+(\w+)\s*\(/);
179
+ if (testMatch) {
180
+ currentTestName = testMatch[1];
181
+ }
182
+
183
+ // Look for assertion patterns
184
+ // Example: .Should().Throw<DomainException>().WithMessage("*email*")
185
+ const assertMatch = line.match(/Should\(\)\.Throw<DomainException>\(\)(?:\.WithMessage\("([^"]+)"\))?/);
186
+ if (assertMatch && currentTestName) {
187
+ const message = assertMatch[1] || '';
188
+ const exception = extractExceptionFromTestName(currentTestName, message);
189
+
190
+ rules.push({
191
+ source: 'test',
192
+ exception,
193
+ context: currentTestName,
194
+ category: inferCategoryFromTestName(currentTestName),
195
+ });
196
+ }
197
+ }
198
+
199
+ return rules;
200
+ }
201
+
202
+ /**
203
+ * Infer business rule exception message from test name
204
+ * Example: Create_WithEmptyEmail_ThrowsDomainException → "Email is required"
205
+ */
206
+ function extractExceptionFromTestName(testName: string, messageHint: string): string {
207
+ // Parse test name pattern: Method_With{Condition}_{ExpectedBehavior}
208
+ const parts = testName.split('_');
209
+
210
+ if (parts.length >= 3) {
211
+ const condition = parts[1].replace(/^With/, '');
212
+
213
+ // Handle common patterns
214
+ if (condition.includes('Empty')) {
215
+ const field = condition.replace('Empty', '').toLowerCase();
216
+ return `${capitalize(field)} is required`;
217
+ }
218
+
219
+ if (condition.includes('Invalid')) {
220
+ const field = condition.replace('Invalid', '').toLowerCase();
221
+ return `Invalid ${field}`;
222
+ }
223
+
224
+ if (condition.includes('Duplicate')) {
225
+ const field = condition.replace('Duplicate', '').toLowerCase();
226
+ return `${capitalize(field)} must be unique`;
227
+ }
228
+ }
229
+
230
+ // Fallback to message hint or test name
231
+ return messageHint.replace(/\*/g, '') || testName;
232
+ }
233
+
234
+ /**
235
+ * Infer category from exception message or method context
236
+ */
237
+ function inferCategory(exception: string, context: string): string {
238
+ const lower = exception.toLowerCase();
239
+
240
+ if (lower.includes('required') || lower.includes('empty') || lower.includes('null')) {
241
+ return 'Validation';
242
+ }
243
+
244
+ if (lower.includes('unique') || lower.includes('duplicate') || lower.includes('exist')) {
245
+ return 'Validation';
246
+ }
247
+
248
+ if (lower.includes('password') || lower.includes('token') || lower.includes('auth')) {
249
+ return 'Sécurité';
250
+ }
251
+
252
+ if (lower.includes('permission') || lower.includes('role') || lower.includes('access')) {
253
+ return 'Autorisation';
254
+ }
255
+
256
+ if (lower.includes('tenant') || lower.includes('isolation')) {
257
+ return 'Multi-tenant';
258
+ }
259
+
260
+ if (lower.includes('email') || lower.includes('notification')) {
261
+ return 'Communication';
262
+ }
263
+
264
+ if (lower.includes('audit') || lower.includes('log') || lower.includes('track')) {
265
+ return 'Audit';
266
+ }
267
+
268
+ if (context.includes('Create') || context.includes('Update') || context.includes('Delete')) {
269
+ return 'Logique métier';
270
+ }
271
+
272
+ return 'Autre';
273
+ }
274
+
275
+ /**
276
+ * Infer category from test name
277
+ */
278
+ function inferCategoryFromTestName(testName: string): string {
279
+ if (testName.includes('Empty') || testName.includes('Invalid') || testName.includes('Required')) {
280
+ return 'Validation';
281
+ }
282
+
283
+ if (testName.includes('Password') || testName.includes('Token')) {
284
+ return 'Sécurité';
285
+ }
286
+
287
+ if (testName.includes('Permission') || testName.includes('Role')) {
288
+ return 'Autorisation';
289
+ }
290
+
291
+ if (testName.includes('Unique') || testName.includes('Duplicate')) {
292
+ return 'Validation';
293
+ }
294
+
295
+ return 'Logique métier';
296
+ }
297
+
298
+ /**
299
+ * Merge and deduplicate rules from domain and tests
300
+ */
301
+ function mergeRules(domainRules: ExtractedRule[], testRules: ExtractedRule[]): ExtractedRule[] {
302
+ const merged: ExtractedRule[] = [...domainRules];
303
+ const existingExceptions = new Set(domainRules.map((r) => r.exception.toLowerCase()));
304
+
305
+ for (const testRule of testRules) {
306
+ // Only add test rule if not already covered by domain rule
307
+ if (!existingExceptions.has(testRule.exception.toLowerCase())) {
308
+ merged.push(testRule);
309
+ existingExceptions.add(testRule.exception.toLowerCase());
310
+ }
311
+ }
312
+
313
+ return merged;
314
+ }
315
+
316
+ /**
317
+ * Convert extracted rules to DocBusinessRule format
318
+ */
319
+ function formatAsBusinessRules(rules: ExtractedRule[]): DocBusinessRule[] {
320
+ return rules.map((rule, index) => {
321
+ // Generate BR-XXX ID
322
+ const id = `BR-${String(index + 1).padStart(3, '0')}`;
323
+
324
+ // Generate short name from exception
325
+ const name = generateRuleName(rule.exception);
326
+
327
+ // Generate full statement
328
+ const statement = rule.exception;
329
+
330
+ return {
331
+ id,
332
+ name,
333
+ category: rule.category || 'Autre',
334
+ statement,
335
+ };
336
+ });
337
+ }
338
+
339
+ /**
340
+ * Generate short rule name from exception message
341
+ * Example: "Email is required" → "Email requis"
342
+ * Example: "Password must be at least 8 characters" → "Mot de passe fort"
343
+ */
344
+ function generateRuleName(exception: string): string {
345
+ const lower = exception.toLowerCase();
346
+
347
+ if (lower.includes('required') || lower.includes('is required')) {
348
+ const field = exception.split(' ')[0];
349
+ return `${field} requis`;
350
+ }
351
+
352
+ if (lower.includes('unique') || lower.includes('must be unique')) {
353
+ const field = exception.split(' ')[0];
354
+ return `Unicité ${field.toLowerCase()}`;
355
+ }
356
+
357
+ if (lower.includes('password') && (lower.includes('least') || lower.includes('strong'))) {
358
+ return 'Mot de passe fort';
359
+ }
360
+
361
+ if (lower.includes('email') && lower.includes('valid')) {
362
+ return 'Email valide';
363
+ }
364
+
365
+ // Fallback: Take first 3-4 words
366
+ const words = exception.split(' ').slice(0, 4).join(' ');
367
+ return words.length > 50 ? words.substring(0, 47) + '...' : words;
368
+ }
369
+
370
+ /**
371
+ * Capitalize first letter
372
+ */
373
+ function capitalize(str: string): string {
374
+ return str.charAt(0).toUpperCase() + str.slice(1);
375
+ }
376
+
377
+ /**
378
+ * Simple singularize function for common English plurals
379
+ */
380
+ function singularize(str: string): string {
381
+ if (str.endsWith('ies')) {
382
+ return str.slice(0, -3) + 'y';
383
+ }
384
+ if (str.endsWith('sses') || str.endsWith('shes') || str.endsWith('ches') || str.endsWith('xes')) {
385
+ return str.slice(0, -2);
386
+ }
387
+ if (str.endsWith('s') && !str.endsWith('ss')) {
388
+ return str.slice(0, -1);
389
+ }
390
+ return str;
391
+ }
392
+
393
+ /**
394
+ * Main execution
395
+ */
396
+ async function main() {
397
+ const { module, appPath } = parseArgs();
398
+
399
+ console.error(`Extracting business rules for module: ${module}`);
400
+ console.error(`App path: ${appPath}`);
401
+
402
+ // Find entity file
403
+ const entityPath = await findEntityFile(appPath, module);
404
+ if (!entityPath) {
405
+ console.error(`Entity not found for module: ${module}`);
406
+ process.exit(1);
407
+ }
408
+
409
+ console.error(`Found entity: ${entityPath}`);
410
+
411
+ // Extract rules from domain
412
+ const domainRules = extractFromDomainEntity(entityPath);
413
+ console.error(`Extracted ${domainRules.length} rules from domain entity`);
414
+
415
+ // Find and extract from tests (optional)
416
+ const testPath = await findTestFile(appPath, module);
417
+ let testRules: ExtractedRule[] = [];
418
+
419
+ if (testPath) {
420
+ console.error(`Found test file: ${testPath}`);
421
+ testRules = extractFromTests(testPath);
422
+ console.error(`Extracted ${testRules.length} rules from unit tests`);
423
+ } else {
424
+ console.error(`No test file found for ${module}`);
425
+ }
426
+
427
+ // Merge and format
428
+ const merged = mergeRules(domainRules, testRules);
429
+ const businessRules = formatAsBusinessRules(merged);
430
+
431
+ console.error(`Total business rules: ${businessRules.length}`);
432
+
433
+ // Output JSON to stdout
434
+ console.log(JSON.stringify(businessRules, null, 2));
435
+ }
436
+
437
+ main().catch((error) => {
438
+ console.error('Fatal error:', error);
439
+ process.exit(1);
440
+ });