@webpieces/code-rules 0.0.1

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,579 @@
1
+ /**
2
+ * Validate Modified Files Executor
3
+ *
4
+ * Validates that modified files don't exceed a maximum line count (default 900).
5
+ * This encourages keeping files small and focused - when you touch a file,
6
+ * you must bring it under the limit.
7
+ *
8
+ * Usage:
9
+ * nx affected --target=validate-modified-files --base=origin/main
10
+ *
11
+ * Escape hatch: Add webpieces-disable max-lines-modified-files comment with date and justification
12
+ * Format: // webpieces-disable max-lines-modified-files 2025/01/15 -- [reason]
13
+ * The disable expires after 1 month from the date specified.
14
+ */
15
+
16
+ import { execSync } from 'child_process';
17
+ import * as fs from 'fs';
18
+ import * as path from 'path';
19
+
20
+ export type FileMaxLimitMode = 'OFF' | 'MODIFIED_FILES';
21
+
22
+ export interface ValidateModifiedFilesOptions {
23
+ limit?: number;
24
+ mode?: FileMaxLimitMode;
25
+ disableAllowed?: boolean;
26
+ }
27
+
28
+ export interface ExecutorResult {
29
+ success: boolean;
30
+ }
31
+
32
+ interface FileViolation {
33
+ file: string;
34
+ lines: number;
35
+ expiredDisable?: boolean;
36
+ expiredDate?: string;
37
+ }
38
+
39
+ const TMP_DIR = '.webpieces/instruct-ai';
40
+ const TMP_MD_FILE = 'webpieces.filesize.md';
41
+
42
+ const FILESIZE_DOC_CONTENT = `# AI Agent Instructions: File Too Long
43
+
44
+ **READ THIS FILE to fix files that are too long**
45
+
46
+ ## Core Principle
47
+
48
+ With **stateless systems + dependency injection, refactor is trivial**.
49
+ Pick a method or a few and move to new class XXXXX, then inject XXXXX
50
+ into all users of those methods via the constructor.
51
+ Delete those methods from original class.
52
+
53
+ **99% of files can be less than the configured max lines of code.**
54
+
55
+ Files should contain a SINGLE COHESIVE UNIT.
56
+ - One class per file (Java convention)
57
+ - If class is too large, extract child responsibilities
58
+ - Use dependency injection to compose functionality
59
+
60
+ ## Command: Reduce File Size
61
+
62
+ ### Step 1: Check for Multiple Classes
63
+ If the file contains multiple classes, **SEPARATE each class into its own file**.
64
+
65
+ \`\`\`typescript
66
+ // BAD: UserController.ts (multiple classes)
67
+ export class UserController { /* ... */ }
68
+ export class UserValidator { /* ... */ }
69
+ export class UserNotifier { /* ... */ }
70
+
71
+ // GOOD: Three separate files
72
+ // UserController.ts
73
+ export class UserController { /* ... */ }
74
+
75
+ // UserValidator.ts
76
+ export class UserValidator { /* ... */ }
77
+
78
+ // UserNotifier.ts
79
+ export class UserNotifier { /* ... */ }
80
+ \`\`\`
81
+
82
+ ### Step 2: Extract Child Responsibilities (if single class is too large)
83
+
84
+ #### Pattern: Create New Service Class with Dependency Injection
85
+
86
+ \`\`\`typescript
87
+ // BAD: UserController.ts (800 lines, single class)
88
+ @provideSingleton()
89
+ @Controller()
90
+ export class UserController {
91
+ // 200 lines: CRUD operations
92
+ // 300 lines: validation logic
93
+ // 200 lines: notification logic
94
+ // 100 lines: analytics logic
95
+ }
96
+
97
+ // GOOD: Extract validation service
98
+ // 1. Create UserValidationService.ts
99
+ @provideSingleton()
100
+ export class UserValidationService {
101
+ validateUserData(data: UserData): ValidationResult {
102
+ // 300 lines of validation logic moved here
103
+ }
104
+
105
+ validateEmail(email: string): boolean { /* ... */ }
106
+ validatePassword(password: string): boolean { /* ... */ }
107
+ }
108
+
109
+ // 2. Inject into UserController.ts
110
+ @provideSingleton()
111
+ @Controller()
112
+ export class UserController {
113
+ constructor(
114
+ @inject(TYPES.UserValidationService)
115
+ private validator: UserValidationService
116
+ ) {}
117
+
118
+ async createUser(data: UserData): Promise<User> {
119
+ const validation = this.validator.validateUserData(data);
120
+ if (!validation.isValid) {
121
+ throw new ValidationError(validation.errors);
122
+ }
123
+ // ... rest of logic
124
+ }
125
+ }
126
+ \`\`\`
127
+
128
+ ## AI Agent Action Steps
129
+
130
+ 1. **ANALYZE** the file structure:
131
+ - Count classes (if >1, separate immediately)
132
+ - Identify logical responsibilities within single class
133
+
134
+ 2. **IDENTIFY** "child code" to extract:
135
+ - Validation logic -> ValidationService
136
+ - Notification logic -> NotificationService
137
+ - Data transformation -> TransformerService
138
+ - External API calls -> ApiService
139
+ - Business rules -> RulesEngine
140
+
141
+ 3. **CREATE** new service file(s):
142
+ - Start with temporary name: \`XXXX.ts\` or \`ChildService.ts\`
143
+ - Add \`@provideSingleton()\` decorator
144
+ - Move child methods to new class
145
+
146
+ 4. **UPDATE** dependency injection:
147
+ - Add to \`TYPES\` constants (if using symbol-based DI)
148
+ - Inject new service into original class constructor
149
+ - Replace direct method calls with \`this.serviceName.method()\`
150
+
151
+ 5. **RENAME** extracted file:
152
+ - Read the extracted code to understand its purpose
153
+ - Rename \`XXXX.ts\` to logical name (e.g., \`UserValidationService.ts\`)
154
+
155
+ 6. **VERIFY** file sizes:
156
+ - Original file should now be under the limit
157
+ - Each extracted file should be under the limit
158
+ - If still too large, extract more services
159
+
160
+ ## Examples of Child Responsibilities to Extract
161
+
162
+ | If File Contains | Extract To | Pattern |
163
+ |-----------------|------------|---------|
164
+ | Validation logic (200+ lines) | \`XValidator.ts\` or \`XValidationService.ts\` | Singleton service |
165
+ | Notification logic (150+ lines) | \`XNotifier.ts\` or \`XNotificationService.ts\` | Singleton service |
166
+ | Data transformation (200+ lines) | \`XTransformer.ts\` | Singleton service |
167
+ | External API calls (200+ lines) | \`XApiClient.ts\` | Singleton service |
168
+ | Complex business rules (300+ lines) | \`XRulesEngine.ts\` | Singleton service |
169
+ | Database queries (200+ lines) | \`XRepository.ts\` | Singleton service |
170
+
171
+ ## WebPieces Dependency Injection Pattern
172
+
173
+ \`\`\`typescript
174
+ // 1. Define service with @provideSingleton
175
+ import { provideSingleton } from '@webpieces/http-routing';
176
+
177
+ @provideSingleton()
178
+ export class MyService {
179
+ doSomething(): void { /* ... */ }
180
+ }
181
+
182
+ // 2. Inject into consumer
183
+ import { inject } from 'inversify';
184
+ import { TYPES } from './types';
185
+
186
+ @provideSingleton()
187
+ @Controller()
188
+ export class MyController {
189
+ constructor(
190
+ @inject(TYPES.MyService) private service: MyService
191
+ ) {}
192
+ }
193
+ \`\`\`
194
+
195
+ ## Escape Hatch
196
+
197
+ If refactoring is genuinely not feasible (generated files, complex algorithms, etc.),
198
+ add a disable comment at the TOP of the file (within first 5 lines) with a DATE:
199
+
200
+ \`\`\`typescript
201
+ // webpieces-disable max-lines-modified-files 2025/01/15 -- Complex generated file, refactoring would break generation
202
+ \`\`\`
203
+
204
+ **IMPORTANT**: The date format is yyyy/mm/dd. The disable will EXPIRE after 1 month from this date.
205
+ After expiration, you must either fix the file or update the date to get another month.
206
+ This ensures that disable comments are reviewed periodically.
207
+
208
+ Remember: Find the "child code" and pull it down into a new class. Once moved, the code's purpose becomes clear, making it easy to rename to a logical name.
209
+ `;
210
+
211
+ /**
212
+ * Write the instructions documentation to tmp directory
213
+ */
214
+ function writeTmpInstructions(workspaceRoot: string): string {
215
+ const tmpDir = path.join(workspaceRoot, TMP_DIR);
216
+ const mdPath = path.join(tmpDir, TMP_MD_FILE);
217
+
218
+ fs.mkdirSync(tmpDir, { recursive: true });
219
+ fs.writeFileSync(mdPath, FILESIZE_DOC_CONTENT);
220
+
221
+ return mdPath;
222
+ }
223
+
224
+ /**
225
+ * Get changed TypeScript files between base and head (or working tree if head not specified).
226
+ * Uses `git diff base [head]` to match what `nx affected` does.
227
+ * When head is NOT specified, also includes untracked files (matching nx affected behavior).
228
+ */
229
+ function getChangedTypeScriptFiles(workspaceRoot: string, base: string, head?: string): string[] {
230
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
231
+ try {
232
+ // If head is specified, diff base to head; otherwise diff base to working tree
233
+ const diffTarget = head ? `${base} ${head}` : base;
234
+ const output = execSync(`git diff --name-only ${diffTarget} -- '*.ts' '*.tsx'`, {
235
+ cwd: workspaceRoot,
236
+ encoding: 'utf-8',
237
+ });
238
+ const changedFiles = output
239
+ .trim()
240
+ .split('\n')
241
+ .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
242
+
243
+ // When comparing to working tree (no head specified), also include untracked files
244
+ // This matches what nx affected does: "All modified files not yet committed or tracked will also be added"
245
+ if (!head) {
246
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
247
+ try {
248
+ const untrackedOutput = execSync(`git ls-files --others --exclude-standard '*.ts' '*.tsx'`, {
249
+ cwd: workspaceRoot,
250
+ encoding: 'utf-8',
251
+ });
252
+ const untrackedFiles = untrackedOutput
253
+ .trim()
254
+ .split('\n')
255
+ .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
256
+ // Merge and dedupe
257
+ const allFiles = new Set([...changedFiles, ...untrackedFiles]);
258
+ return Array.from(allFiles);
259
+ } catch (err: unknown) {
260
+ //const error = toError(err);
261
+ // If ls-files fails, just return the changed files
262
+ return changedFiles;
263
+ }
264
+ }
265
+
266
+ return changedFiles;
267
+ } catch (err: unknown) {
268
+ //const error = toError(err);
269
+ return [];
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Parse a date string in yyyy/mm/dd format and return a Date object.
275
+ * Returns null if the format is invalid.
276
+ */
277
+ function parseDisableDate(dateStr: string): Date | null {
278
+ // Match yyyy/mm/dd format
279
+ const match = dateStr.match(/^(\d{4})\/(\d{2})\/(\d{2})$/);
280
+ if (!match) return null;
281
+
282
+ const year = parseInt(match[1], 10);
283
+ const month = parseInt(match[2], 10) - 1; // JS months are 0-indexed
284
+ const day = parseInt(match[3], 10);
285
+
286
+ const date = new Date(year, month, day);
287
+
288
+ // Validate the date is valid (e.g., not Feb 30)
289
+ if (date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) {
290
+ return null;
291
+ }
292
+
293
+ return date;
294
+ }
295
+
296
+ /**
297
+ * Check if a date is within the last month (not expired).
298
+ */
299
+ function isDateWithinMonth(date: Date): boolean {
300
+ const now = new Date();
301
+ const oneMonthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
302
+ return date >= oneMonthAgo;
303
+ }
304
+
305
+ interface DisableStatus {
306
+ hasDisable: boolean;
307
+ isValid: boolean;
308
+ isExpired: boolean;
309
+ date?: string;
310
+ }
311
+
312
+ /**
313
+ * Check if a file has a valid, non-expired disable comment at the top (within first 5 lines).
314
+ * Returns status object with details about the disable comment.
315
+ */
316
+ // webpieces-disable max-lines-new-methods -- Date validation logic requires checking multiple conditions
317
+ function checkDisableComment(content: string): DisableStatus {
318
+ const lines = content.split('\n').slice(0, 5);
319
+
320
+ for (const line of lines) {
321
+ if (line.includes('webpieces-disable') && line.includes('max-lines-modified-files')) {
322
+ // Found disable comment, now check for date
323
+ // Format: // webpieces-disable max-lines-modified-files yyyy/mm/dd -- reason
324
+ const dateMatch = line.match(/max-lines-modified-files\s+(\d{4}\/\d{2}\/\d{2}|XXXX\/XX\/XX)/);
325
+
326
+ if (!dateMatch) {
327
+ // No date found - invalid disable comment
328
+ return { hasDisable: true, isValid: false, isExpired: false };
329
+ }
330
+
331
+ const dateStr = dateMatch[1];
332
+
333
+ // Secret permanent disable
334
+ if (dateStr === 'XXXX/XX/XX') {
335
+ return { hasDisable: true, isValid: true, isExpired: false, date: dateStr };
336
+ }
337
+
338
+ const date = parseDisableDate(dateStr);
339
+ if (!date) {
340
+ // Invalid date format
341
+ return { hasDisable: true, isValid: false, isExpired: false, date: dateStr };
342
+ }
343
+
344
+ if (!isDateWithinMonth(date)) {
345
+ // Date is expired (older than 1 month)
346
+ return { hasDisable: true, isValid: true, isExpired: true, date: dateStr };
347
+ }
348
+
349
+ // Valid and not expired
350
+ return { hasDisable: true, isValid: true, isExpired: false, date: dateStr };
351
+ }
352
+ }
353
+
354
+ return { hasDisable: false, isValid: false, isExpired: false };
355
+ }
356
+
357
+ /**
358
+ * Count lines in a file and check for violations
359
+ */
360
+ // webpieces-disable max-lines-new-methods -- File iteration with disable checking logic
361
+ function findViolations(workspaceRoot: string, changedFiles: string[], limit: number, disableAllowed: boolean): FileViolation[] {
362
+ const violations: FileViolation[] = [];
363
+
364
+ for (const file of changedFiles) {
365
+ const fullPath = path.join(workspaceRoot, file);
366
+
367
+ if (!fs.existsSync(fullPath)) continue;
368
+
369
+ const content = fs.readFileSync(fullPath, 'utf-8');
370
+ const lineCount = content.split('\n').length;
371
+
372
+ // Skip files under the limit
373
+ if (lineCount <= limit) continue;
374
+
375
+ // When disableAllowed is false, ignore all disable comments
376
+ if (!disableAllowed) {
377
+ violations.push({ file, lines: lineCount });
378
+ continue;
379
+ }
380
+
381
+ // Check for disable comment
382
+ const disableStatus = checkDisableComment(content);
383
+
384
+ if (disableStatus.hasDisable) {
385
+ if (disableStatus.isValid && !disableStatus.isExpired) {
386
+ // Valid, non-expired disable - skip this file
387
+ continue;
388
+ }
389
+
390
+ if (disableStatus.isExpired) {
391
+ // Expired disable - report as violation with expired info
392
+ violations.push({
393
+ file,
394
+ lines: lineCount,
395
+ expiredDisable: true,
396
+ expiredDate: disableStatus.date,
397
+ });
398
+ continue;
399
+ }
400
+
401
+ // Invalid disable (missing/bad date) - fall through to report as violation
402
+ }
403
+
404
+ violations.push({
405
+ file,
406
+ lines: lineCount,
407
+ });
408
+ }
409
+
410
+ return violations;
411
+ }
412
+
413
+ /**
414
+ * Auto-detect the base branch by finding the merge-base with origin/main.
415
+ */
416
+ function detectBase(workspaceRoot: string): string | null {
417
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
418
+ try {
419
+ const mergeBase = execSync('git merge-base HEAD origin/main', {
420
+ cwd: workspaceRoot,
421
+ encoding: 'utf-8',
422
+ stdio: ['pipe', 'pipe', 'pipe'],
423
+ }).trim();
424
+
425
+ if (mergeBase) {
426
+ return mergeBase;
427
+ }
428
+ } catch (err: unknown) {
429
+ //const error = toError(err);
430
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
431
+ try {
432
+ const mergeBase = execSync('git merge-base HEAD main', {
433
+ cwd: workspaceRoot,
434
+ encoding: 'utf-8',
435
+ stdio: ['pipe', 'pipe', 'pipe'],
436
+ }).trim();
437
+
438
+ if (mergeBase) {
439
+ return mergeBase;
440
+ }
441
+ } catch (err2: unknown) {
442
+ //const error2 = toError(err2);
443
+ // Ignore
444
+ }
445
+ }
446
+ return null;
447
+ }
448
+
449
+ /**
450
+ * Get today's date in yyyy/mm/dd format for error messages
451
+ */
452
+ function getTodayDateString(): string {
453
+ const now = new Date();
454
+ const year = now.getFullYear();
455
+ const month = String(now.getMonth() + 1).padStart(2, '0');
456
+ const day = String(now.getDate()).padStart(2, '0');
457
+ return `${year}/${month}/${day}`;
458
+ }
459
+
460
+ /**
461
+ * Report violations to console
462
+ */
463
+ // webpieces-disable max-lines-new-methods -- Error output formatting with multiple message sections
464
+ function reportViolations(violations: FileViolation[], limit: number, disableAllowed: boolean): void {
465
+ console.error('');
466
+ console.error('\u274c YOU MUST FIX THIS AND NOT be more than ' + limit + ' lines of code per file');
467
+ console.error(' as it slows down IDEs AND is VERY VERY EASY to refactor.');
468
+ console.error('');
469
+ console.error('\ud83d\udcda With stateless systems + dependency injection, refactor is trivial:');
470
+ console.error(' Pick a method or a few and move to new class XXXXX, then inject XXXXX');
471
+ console.error(' into all users of those methods via the constructor.');
472
+ console.error(' Delete those methods from original class.');
473
+ console.error(' 99% of files can be less than ' + limit + ' lines of code.');
474
+ console.error('');
475
+ console.error('\u26a0\ufe0f *** READ .webpieces/instruct-ai/webpieces.filesize.md for detailed guidance on how to fix this easily *** \u26a0\ufe0f');
476
+ console.error('');
477
+
478
+ for (const v of violations) {
479
+ if (v.expiredDisable) {
480
+ console.error(` \u274c ${v.file} (${v.lines} lines, max: ${limit})`);
481
+ console.error(` \u23f0 EXPIRED DISABLE: Your disable comment dated ${v.expiredDate} has expired (>1 month old).`);
482
+ console.error(` You must either FIX the file or UPDATE the date to get another month.`);
483
+ } else {
484
+ console.error(` \u274c ${v.file} (${v.lines} lines, max: ${limit})`);
485
+ }
486
+ }
487
+ console.error('');
488
+
489
+ // Only show escape hatch instructions when disableAllowed is true
490
+ if (disableAllowed) {
491
+ console.error(' You can disable this error, but you will be forced to fix again in 1 month');
492
+ console.error(' since 99% of files can be less than ' + limit + ' lines of code.');
493
+ console.error('');
494
+ console.error(' Use escape with DATE (expires in 1 month):');
495
+ console.error(` // webpieces-disable max-lines-modified-files ${getTodayDateString()} -- [your reason]`);
496
+ console.error('');
497
+ } else {
498
+ console.error(' \u26a0\ufe0f disableAllowed is false - disable comments are NOT allowed.');
499
+ console.error(' This rule must be met and cannot be disabled since nx.json disableAllowed is set to false.');
500
+ console.error(' You MUST refactor to reduce file size.');
501
+ console.error('');
502
+ console.error(' For a major refactor, a human can add "ignoreModifiedUntilEpoch" to nx.json validate-code options.');
503
+ console.error(' This is an expiry timestamp (epoch ms) for when we start forcing everyone to meet size rules again.');
504
+ console.error(' Sometimes for speed, we allow files to expand during a refactor and over time,');
505
+ console.error(' each PR reduces files as they get touched.');
506
+ console.error(' AI agents should NOT add ignoreModifiedUntilEpoch - ask a human to do it.');
507
+ console.error('');
508
+ }
509
+ }
510
+
511
+ export default async function runValidator(
512
+ options: ValidateModifiedFilesOptions,
513
+ workspaceRoot: string
514
+ ): Promise<ExecutorResult> {
515
+ const limit = options.limit ?? 900;
516
+ const mode: FileMaxLimitMode = options.mode ?? 'MODIFIED_FILES';
517
+ const disableAllowed = options.disableAllowed ?? true;
518
+
519
+ // Skip validation entirely if mode is OFF
520
+ if (mode === 'OFF') {
521
+ console.log('\n\u23ed\ufe0f Skipping modified files validation (mode: OFF)');
522
+ console.log('');
523
+ return { success: true };
524
+ }
525
+
526
+ // If NX_HEAD is set (via nx affected --head=X), use it; otherwise compare to working tree
527
+ let base = process.env['NX_BASE'];
528
+ const head = process.env['NX_HEAD'];
529
+
530
+ if (!base) {
531
+ base = detectBase(workspaceRoot) ?? undefined;
532
+
533
+ if (!base) {
534
+ console.log('\n\u23ed\ufe0f Skipping modified files validation (could not detect base branch)');
535
+ console.log(' To run explicitly: nx affected --target=validate-modified-files --base=origin/main');
536
+ console.log('');
537
+ return { success: true };
538
+ }
539
+
540
+ console.log('\n\ud83d\udccf Validating Modified File Sizes (auto-detected base)\n');
541
+ } else {
542
+ console.log('\n\ud83d\udccf Validating Modified File Sizes\n');
543
+ }
544
+
545
+ console.log(` Base: ${base}`);
546
+ console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);
547
+ console.log(` Mode: ${mode}`);
548
+ console.log(` Max lines for modified files: ${limit}`);
549
+ console.log(` Disable allowed: ${disableAllowed}${!disableAllowed ? ' (no escape hatch)' : ''}`);
550
+ console.log('');
551
+
552
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
553
+ try {
554
+ const changedFiles = getChangedTypeScriptFiles(workspaceRoot, base, head);
555
+
556
+ if (changedFiles.length === 0) {
557
+ console.log('\u2705 No TypeScript files changed');
558
+ return { success: true };
559
+ }
560
+
561
+ console.log(`\ud83d\udcc2 Checking ${changedFiles.length} changed file(s)...`);
562
+
563
+ const violations = findViolations(workspaceRoot, changedFiles, limit, disableAllowed);
564
+
565
+ if (violations.length === 0) {
566
+ console.log('\u2705 All modified files are under ' + limit + ' lines');
567
+ return { success: true };
568
+ }
569
+
570
+ writeTmpInstructions(workspaceRoot);
571
+ reportViolations(violations, limit, disableAllowed);
572
+ return { success: false };
573
+ } catch (err: unknown) {
574
+ //const error = toError(err);
575
+ const error = err instanceof Error ? err : new Error(String(err));
576
+ console.error('\u274c Modified files validation failed:', error.message);
577
+ return { success: false };
578
+ }
579
+ }