@webpieces/dev-config 0.2.60 → 0.2.62

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.
@@ -14,7 +14,9 @@
14
14
  * Usage:
15
15
  * nx affected --target=validate-modified-methods --base=origin/main
16
16
  *
17
- * Escape hatch: Add webpieces-disable max-lines-new-and-modified comment with justification
17
+ * Escape hatch: Add webpieces-disable max-lines-new-and-modified comment with date and justification
18
+ * Format: // webpieces-disable max-lines-new-and-modified 2025/01/15 -- [reason]
19
+ * The disable expires after 1 month from the date specified.
18
20
  */
19
21
 
20
22
  import type { ExecutorContext } from '@nx/devkit';
@@ -36,6 +38,8 @@ interface MethodViolation {
36
38
  methodName: string;
37
39
  line: number;
38
40
  lines: number;
41
+ expiredDisable?: boolean;
42
+ expiredDate?: string;
39
43
  }
40
44
 
41
45
  const TMP_DIR = 'tmp/webpieces';
@@ -140,15 +144,19 @@ const result = this.buildResultObject(data);
140
144
 
141
145
  Sometimes methods genuinely need to be longer (complex algorithms, state machines, etc.).
142
146
 
143
- **Escape hatch**: Add a webpieces-disable comment with justification:
147
+ **Escape hatch**: Add a webpieces-disable comment with DATE and justification:
144
148
 
145
149
  \`\`\`typescript
146
- // webpieces-disable max-lines-new-and-modified -- Complex state machine, splitting reduces clarity
150
+ // webpieces-disable max-lines-new-and-modified 2025/01/15 -- Complex state machine, splitting reduces clarity
147
151
  async complexStateMachine(): Promise<void> {
148
152
  // ... longer method with justification
149
153
  }
150
154
  \`\`\`
151
155
 
156
+ **IMPORTANT**: The date format is yyyy/mm/dd. The disable will EXPIRE after 1 month from this date.
157
+ After expiration, you must either fix the method or update the date to get another month.
158
+ This ensures that disable comments are reviewed periodically.
159
+
152
160
  ## AI Agent Action Steps
153
161
 
154
162
  1. **READ** the method to understand its logical sections
@@ -289,14 +297,64 @@ function getChangedLineNumbers(diffContent: string): Set<number> {
289
297
  return changedLines;
290
298
  }
291
299
 
300
+ /**
301
+ * Parse a date string in yyyy/mm/dd format and return a Date object.
302
+ * Returns null if the format is invalid.
303
+ */
304
+ function parseDisableDate(dateStr: string): Date | null {
305
+ // Match yyyy/mm/dd format
306
+ const match = dateStr.match(/^(\d{4})\/(\d{2})\/(\d{2})$/);
307
+ if (!match) return null;
308
+
309
+ const year = parseInt(match[1], 10);
310
+ const month = parseInt(match[2], 10) - 1; // JS months are 0-indexed
311
+ const day = parseInt(match[3], 10);
312
+
313
+ const date = new Date(year, month, day);
314
+
315
+ // Validate the date is valid (e.g., not Feb 30)
316
+ if (date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) {
317
+ return null;
318
+ }
319
+
320
+ return date;
321
+ }
322
+
323
+ /**
324
+ * Check if a date is within the last month (not expired).
325
+ */
326
+ function isDateWithinMonth(date: Date): boolean {
327
+ const now = new Date();
328
+ const oneMonthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
329
+ return date >= oneMonthAgo;
330
+ }
331
+
332
+ /**
333
+ * Get today's date in yyyy/mm/dd format for error messages
334
+ */
335
+ function getTodayDateString(): string {
336
+ const now = new Date();
337
+ const year = now.getFullYear();
338
+ const month = String(now.getMonth() + 1).padStart(2, '0');
339
+ const day = String(now.getDate()).padStart(2, '0');
340
+ return `${year}/${month}/${day}`;
341
+ }
342
+
343
+ interface DisableInfo {
344
+ type: 'full' | 'new-only' | 'none';
345
+ isExpired: boolean;
346
+ date?: string;
347
+ }
348
+
292
349
  /**
293
350
  * Check what kind of webpieces-disable comment is present for a method.
294
- * Returns: 'full' | 'new-only' | 'none'
351
+ * Returns: DisableInfo with type, expiration status, and date
295
352
  * - 'full': max-lines-new-and-modified (ultimate escape, skips both validators)
296
353
  * - 'new-only': max-lines-new-methods (escaped 30-line check, still needs 80-line check)
297
354
  * - 'none': no escape hatch
298
355
  */
299
- function getDisableType(lines: string[], lineNumber: number): 'full' | 'new-only' | 'none' {
356
+ // webpieces-disable max-lines-new-methods -- Complex validation logic with multiple escape hatch types
357
+ function getDisableInfo(lines: string[], lineNumber: number): DisableInfo {
300
358
  const startCheck = Math.max(0, lineNumber - 5);
301
359
  for (let i = lineNumber - 2; i >= startCheck; i--) {
302
360
  const line = lines[i]?.trim() ?? '';
@@ -305,24 +363,83 @@ function getDisableType(lines: string[], lineNumber: number): 'full' | 'new-only
305
363
  }
306
364
  if (line.includes('webpieces-disable')) {
307
365
  if (line.includes('max-lines-new-and-modified')) {
308
- return 'full';
366
+ // Check for date in format: max-lines-new-and-modified yyyy/mm/dd
367
+ const dateMatch = line.match(/max-lines-new-and-modified\s+(\d{4}\/\d{2}\/\d{2}|XXXX\/XX\/XX)/);
368
+
369
+ if (!dateMatch) {
370
+ // No date found - treat as expired (invalid)
371
+ return { type: 'full', isExpired: true, date: undefined };
372
+ }
373
+
374
+ const dateStr = dateMatch[1];
375
+
376
+ // Secret permanent disable
377
+ if (dateStr === 'XXXX/XX/XX') {
378
+ return { type: 'full', isExpired: false, date: dateStr };
379
+ }
380
+
381
+ const date = parseDisableDate(dateStr);
382
+ if (!date) {
383
+ // Invalid date format - treat as expired
384
+ return { type: 'full', isExpired: true, date: dateStr };
385
+ }
386
+
387
+ if (!isDateWithinMonth(date)) {
388
+ // Date is expired (older than 1 month)
389
+ return { type: 'full', isExpired: true, date: dateStr };
390
+ }
391
+
392
+ // Valid and not expired
393
+ return { type: 'full', isExpired: false, date: dateStr };
309
394
  }
310
395
  if (line.includes('max-lines-new-methods')) {
311
- return 'new-only';
396
+ // Check for date in format: max-lines-new-methods yyyy/mm/dd
397
+ const dateMatch = line.match(/max-lines-new-methods\s+(\d{4}\/\d{2}\/\d{2}|XXXX\/XX\/XX)/);
398
+
399
+ if (!dateMatch) {
400
+ // No date found - treat as expired (invalid)
401
+ return { type: 'new-only', isExpired: true, date: undefined };
402
+ }
403
+
404
+ const dateStr = dateMatch[1];
405
+
406
+ // Secret permanent disable
407
+ if (dateStr === 'XXXX/XX/XX') {
408
+ return { type: 'new-only', isExpired: false, date: dateStr };
409
+ }
410
+
411
+ const date = parseDisableDate(dateStr);
412
+ if (!date) {
413
+ // Invalid date format - treat as expired
414
+ return { type: 'new-only', isExpired: true, date: dateStr };
415
+ }
416
+
417
+ if (!isDateWithinMonth(date)) {
418
+ // Date is expired (older than 1 month)
419
+ return { type: 'new-only', isExpired: true, date: dateStr };
420
+ }
421
+
422
+ // Valid and not expired
423
+ return { type: 'new-only', isExpired: false, date: dateStr };
312
424
  }
313
425
  }
314
426
  }
315
- return 'none';
427
+ return { type: 'none', isExpired: false };
428
+ }
429
+
430
+ interface MethodInfo {
431
+ name: string;
432
+ line: number;
433
+ endLine: number;
434
+ lines: number;
435
+ disableInfo: DisableInfo;
316
436
  }
317
437
 
318
438
  /**
319
439
  * Parse a TypeScript file and find methods with their line counts
320
440
  */
321
441
  // webpieces-disable max-lines-new-methods -- AST traversal requires inline visitor function
322
- function findMethodsInFile(
323
- filePath: string,
324
- workspaceRoot: string
325
- ): Array<{ name: string; line: number; endLine: number; lines: number; disableType: 'full' | 'new-only' | 'none' }> {
442
+ function findMethodsInFile(filePath: string, workspaceRoot: string): MethodInfo[] {
326
443
  const fullPath = path.join(workspaceRoot, filePath);
327
444
  if (!fs.existsSync(fullPath)) return [];
328
445
 
@@ -330,8 +447,7 @@ function findMethodsInFile(
330
447
  const fileLines = content.split('\n');
331
448
  const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
332
449
 
333
- const methods: Array<{ name: string; line: number; endLine: number; lines: number; disableType: 'full' | 'new-only' | 'none' }> =
334
- [];
450
+ const methods: MethodInfo[] = [];
335
451
 
336
452
  // webpieces-disable max-lines-new-methods -- AST visitor pattern requires handling multiple node types
337
453
  function visit(node: ts.Node): void {
@@ -367,7 +483,7 @@ function findMethodsInFile(
367
483
  line: startLine,
368
484
  endLine: endLine,
369
485
  lines: endLine - startLine + 1,
370
- disableType: getDisableType(fileLines, startLine),
486
+ disableInfo: getDisableInfo(fileLines, startLine),
371
487
  });
372
488
  }
373
489
 
@@ -387,9 +503,9 @@ function findMethodsInFile(
387
503
  *
388
504
  * Skips:
389
505
  * - NEW methods without any escape (let validate-new-methods handle them first)
390
- * - Methods with `max-lines-new-and-modified` escape (ultimate escape hatch)
506
+ * - Methods with valid, non-expired `max-lines-new-and-modified` escape (ultimate escape hatch)
391
507
  */
392
- // webpieces-disable max-lines-new-methods -- Core validation logic with multiple file operations
508
+ // webpieces-disable max-lines-new-and-modified 2025/12/20 -- Core validation logic with multiple file operations
393
509
  function findViolations(
394
510
  workspaceRoot: string,
395
511
  changedFiles: string[],
@@ -414,26 +530,52 @@ function findViolations(
414
530
 
415
531
  for (const method of methods) {
416
532
  const isNewMethod = newMethodNames.has(method.name);
533
+ const { type: disableType, isExpired, date: disableDate } = method.disableInfo;
417
534
 
418
- // Skip methods with full escape (max-lines-new-and-modified)
419
- if (method.disableType === 'full') continue;
535
+ // Skip methods with valid, non-expired full escape (max-lines-new-and-modified)
536
+ if (disableType === 'full' && !isExpired) continue;
420
537
 
421
538
  // Skip methods under the limit
422
539
  if (method.lines <= maxLines) continue;
423
540
 
424
541
  if (isNewMethod) {
425
542
  // For NEW methods:
426
- // - If has 'new-only' escape → check (they escaped 30-line, now need 80-line check)
543
+ // - If has 'new-only' escape (non-expired) → check (they escaped 30-line, now need 80-line check)
427
544
  // - If has 'none' → skip (let validate-new-methods handle first)
428
- if (method.disableType !== 'new-only') continue;
429
-
430
- // New method with max-lines-new-methods escape - check against 80-line limit
431
- violations.push({
432
- file,
433
- methodName: method.name,
434
- line: method.line,
435
- lines: method.lines,
436
- });
545
+ // - If has expired disable → report as violation
546
+ if (disableType === 'full' && isExpired) {
547
+ // Expired full disable - report with expired info
548
+ violations.push({
549
+ file,
550
+ methodName: method.name,
551
+ line: method.line,
552
+ lines: method.lines,
553
+ expiredDisable: true,
554
+ expiredDate: disableDate,
555
+ });
556
+ continue;
557
+ }
558
+ if (disableType !== 'new-only') continue;
559
+
560
+ if (isExpired) {
561
+ // Expired new-only disable - report with expired info
562
+ violations.push({
563
+ file,
564
+ methodName: method.name,
565
+ line: method.line,
566
+ lines: method.lines,
567
+ expiredDisable: true,
568
+ expiredDate: disableDate,
569
+ });
570
+ } else {
571
+ // New method with valid max-lines-new-methods escape - check against 80-line limit
572
+ violations.push({
573
+ file,
574
+ methodName: method.name,
575
+ line: method.line,
576
+ lines: method.lines,
577
+ });
578
+ }
437
579
  } else {
438
580
  // For MODIFIED methods: check if any changed line falls within method's range
439
581
  let hasChanges = false;
@@ -445,12 +587,24 @@ function findViolations(
445
587
  }
446
588
 
447
589
  if (hasChanges) {
448
- violations.push({
449
- file,
450
- methodName: method.name,
451
- line: method.line,
452
- lines: method.lines,
453
- });
590
+ if (disableType === 'full' && isExpired) {
591
+ // Expired full disable - report with expired info
592
+ violations.push({
593
+ file,
594
+ methodName: method.name,
595
+ line: method.line,
596
+ lines: method.lines,
597
+ expiredDisable: true,
598
+ expiredDate: disableDate,
599
+ });
600
+ } else {
601
+ violations.push({
602
+ file,
603
+ methodName: method.name,
604
+ line: method.line,
605
+ lines: method.lines,
606
+ });
607
+ }
454
608
  }
455
609
  }
456
610
  }
@@ -491,6 +645,46 @@ function detectBase(workspaceRoot: string): string | null {
491
645
  return null;
492
646
  }
493
647
 
648
+ /**
649
+ * Report violations to console
650
+ */
651
+ // webpieces-disable max-lines-new-methods -- Error output formatting with multiple message sections
652
+ function reportViolations(violations: MethodViolation[], maxLines: number): void {
653
+ console.error('');
654
+ console.error('❌ Modified methods exceed ' + maxLines + ' lines!');
655
+ console.error('');
656
+ console.error('📚 When you modify a method, you must bring it under ' + maxLines + ' lines.');
657
+ console.error(' This rule encourages GRADUAL cleanup so even though you did not cause it,');
658
+ console.error(' you touched it, so you should fix now as part of your PR');
659
+ console.error(' (this is for vibe coding and AI to fix as it touches things).');
660
+ console.error(' You can refactor to stay under the limit 50% of the time. If not feasible, use the escape hatch.');
661
+ console.error('');
662
+ console.error(
663
+ '⚠️ *** READ tmp/webpieces/webpieces.methodsize.md for detailed guidance on how to fix this easily *** ⚠️'
664
+ );
665
+ console.error('');
666
+
667
+ for (const v of violations) {
668
+ if (v.expiredDisable) {
669
+ console.error(` ❌ ${v.file}:${v.line}`);
670
+ console.error(` Method: ${v.methodName} (${v.lines} lines, max: ${maxLines})`);
671
+ console.error(` ⏰ EXPIRED DISABLE: Your disable comment dated ${v.expiredDate ?? 'unknown'} has expired (>1 month old).`);
672
+ console.error(` You must either FIX the method or UPDATE the date to get another month.`);
673
+ } else {
674
+ console.error(` ❌ ${v.file}:${v.line}`);
675
+ console.error(` Method: ${v.methodName} (${v.lines} lines, max: ${maxLines})`);
676
+ }
677
+ }
678
+ console.error('');
679
+
680
+ console.error(' You can disable this error, but you will be forced to fix again in 1 month');
681
+ console.error(' since 99% of methods can be less than ' + maxLines + ' lines of code.');
682
+ console.error('');
683
+ console.error(' Use escape with DATE (expires in 1 month):');
684
+ console.error(` // webpieces-disable max-lines-new-and-modified ${getTodayDateString()} -- [your reason]`);
685
+ console.error('');
686
+ }
687
+
494
688
  export default async function runExecutor(
495
689
  options: ValidateModifiedMethodsOptions,
496
690
  context: ExecutorContext
@@ -537,30 +731,8 @@ export default async function runExecutor(
537
731
  return { success: true };
538
732
  }
539
733
 
540
- // Write instructions file
541
734
  writeTmpInstructions(workspaceRoot);
542
-
543
- // Report violations
544
- console.error('');
545
- console.error('❌ Modified methods exceed ' + maxLines + ' lines!');
546
- console.error('');
547
- console.error('📚 When you modify a method, you must bring it under ' + maxLines + ' lines.');
548
- console.error(' This rule encourages GRADUAL cleanup so even though you did not cause it,');
549
- console.error(' you touched it, so you should fix now as part of your PR');
550
- console.error(' (this is for vibe coding and AI to fix as it touches things).');
551
- console.error(' You can refactor to stay under the limit 50% of the time. If not feasible, use the escape hatch.');
552
- console.error('');
553
- console.error(
554
- '⚠️ *** READ tmp/webpieces/webpieces.methodsize.md for detailed guidance on how to fix this easily *** ⚠️'
555
- );
556
- console.error('');
557
-
558
- for (const v of violations) {
559
- console.error(` ❌ ${v.file}:${v.line}`);
560
- console.error(` Method: ${v.methodName} (${v.lines} lines, max: ${maxLines})`);
561
- }
562
- console.error('');
563
-
735
+ reportViolations(violations, maxLines);
564
736
  return { success: false };
565
737
  } catch (err: unknown) {
566
738
  const error = err instanceof Error ? err : new Error(String(err));
@@ -363,6 +363,28 @@ function detectBase(workspaceRoot) {
363
363
  }
364
364
  return null;
365
365
  }
366
+ /**
367
+ * Report violations to the user with helpful instructions
368
+ */
369
+ function reportViolations(violations, maxLines) {
370
+ console.error('');
371
+ console.error('❌ New methods exceed ' + maxLines + ' lines!');
372
+ console.error('');
373
+ console.error('📚 Methods should read like a "table of contents" - each method call');
374
+ console.error(' describes a larger piece of work. You can refactor');
375
+ console.error(' to stay under ' + maxLines + ' lines 50% of the time.');
376
+ console.error('');
377
+ console.error('⚠️ *** READ tmp/webpieces/webpieces.methodsize.md for detailed guidance on how to fix this easily *** ⚠️');
378
+ console.error('');
379
+ for (const v of violations) {
380
+ console.error(` ❌ ${v.file}:${v.line}`);
381
+ console.error(` Method: ${v.methodName} (${v.lines} lines, max: ${maxLines})`);
382
+ }
383
+ console.error('');
384
+ console.error(' If you REALLY REALLY need more than ' + maxLines + ' lines, this happens 50% of the time,');
385
+ console.error(' so use escape: // webpieces-disable max-lines-new-methods -- [your reason]');
386
+ console.error('');
387
+ }
366
388
  async function runExecutor(options, context) {
367
389
  const workspaceRoot = context.root;
368
390
  const maxLines = options.max ?? 30;
@@ -402,23 +424,9 @@ async function runExecutor(options, context) {
402
424
  console.log('✅ All new methods are under ' + maxLines + ' lines');
403
425
  return { success: true };
404
426
  }
405
- // Write instructions file
427
+ // Write instructions file and report violations
406
428
  writeTmpInstructions(workspaceRoot);
407
- // Report violations
408
- console.error('');
409
- console.error('❌ New methods exceed ' + maxLines + ' lines!');
410
- console.error('');
411
- console.error('📚 Methods should read like a "table of contents" - each method call');
412
- console.error(' describes a larger piece of work. You can refactor');
413
- console.error(' to stay under ' + maxLines + ' lines 50% of the time. If not feasible, use the escape hatch.');
414
- console.error('');
415
- console.error('⚠️ *** READ tmp/webpieces/webpieces.methodsize.md for detailed guidance on how to fix this easily *** ⚠️');
416
- console.error('');
417
- for (const v of violations) {
418
- console.error(` ❌ ${v.file}:${v.line}`);
419
- console.error(` Method: ${v.methodName} (${v.lines} lines, max: ${maxLines})`);
420
- }
421
- console.error('');
429
+ reportViolations(violations, maxLines);
422
430
  return { success: false };
423
431
  }
424
432
  catch (err) {
@@ -1 +1 @@
1
- {"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/dev-config/architecture/executors/validate-new-methods/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;GAgBG;;AAyYH,8BA8EC;;AApdD,iDAAyC;AACzC,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AAkBjC,MAAM,OAAO,GAAG,eAAe,CAAC;AAChC,MAAM,WAAW,GAAG,yBAAyB,CAAC;AAE9C,MAAM,sBAAsB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoH9B,CAAC;AAEF;;GAEG;AACH,SAAS,oBAAoB,CAAC,aAAqB;IAC/C,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;IACjD,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;IAE9C,EAAE,CAAC,SAAS,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAC1C,EAAE,CAAC,aAAa,CAAC,MAAM,EAAE,sBAAsB,CAAC,CAAC;IAEjD,OAAO,MAAM,CAAC;AAClB,CAAC;AAED;;;;GAIG;AACH,SAAS,yBAAyB,CAAC,aAAqB,EAAE,IAAY;IAClE,IAAI,CAAC;QACD,gEAAgE;QAChE,MAAM,MAAM,GA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count.\n * Runs in affected mode when:\n * 1. NX_BASE environment variable is set (via nx affected), OR\n * 2. Auto-detects base by finding merge-base with origin/main\n *\n * This validator encourages writing methods that read like a \"table of contents\"\n * where each method call describes a larger piece of work.\n *\n * Usage:\n * nx affected --target=validate-new-methods --base=origin/main\n * OR: runs automatically via build's architecture:validate-complete dependency\n *\n * Escape hatch: Add webpieces-disable max-lines-new-methods comment with justification\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\n\nexport interface ValidateNewMethodsOptions {\n max?: number;\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\ninterface MethodViolation {\n file: string;\n methodName: string;\n line: number;\n lines: number;\n isNew: boolean;\n}\n\nconst TMP_DIR = 'tmp/webpieces';\nconst TMP_MD_FILE = 'webpieces.methodsize.md';\n\nconst METHODSIZE_DOC_CONTENT = `# Instructions: New Method Too Long\n\n## Requirement\n\n**~50% of the time**, you can stay under the \\`newMethodsMaxLines\\` limit from nx.json\nby extracting logical units into well-named methods.\n\n**~99% of the time**, you can stay under the \\`modifiedAndNewMethodsMaxLines\\` limit from nx.json.\nNearly all software can be written with methods under this size.\n\n## The \"Table of Contents\" Principle\n\nGood code reads like a book's table of contents:\n- Chapter titles (method names) tell you WHAT happens\n- Reading chapter titles gives you the full story\n- You can dive into chapters (implementations) for details\n\n## Why Limit New Methods?\n\nMethods under the limit are:\n- Easy to review in a single screen\n- Simple to understand without scrolling\n- Quick for AI to analyze and suggest improvements\n- More testable in isolation\n- Self-documenting through well-named extracted methods\n\nExtracting logical units into well-named methods makes code more readable for both\nAI and humans.\n\n## How to Refactor\n\nInstead of:\n\\`\\`\\`typescript\nasync processOrder(order: Order): Promise<Result> {\n // 50 lines of validation, transformation, saving, notifications...\n}\n\\`\\`\\`\n\nWrite:\n\\`\\`\\`typescript\nasync processOrder(order: Order): Promise<Result> {\n const validated = this.validateOrder(order);\n const transformed = this.applyBusinessRules(validated);\n const saved = await this.saveToDatabase(transformed);\n await this.notifyStakeholders(saved);\n return this.buildResult(saved);\n}\n\\`\\`\\`\n\nNow the main method is a \"table of contents\" - each line tells part of the story!\n\n## Patterns for Extraction\n\n### Pattern 1: Extract Loop Bodies\n\\`\\`\\`typescript\n// BEFORE\nfor (const item of items) {\n // 20 lines of processing\n}\n\n// AFTER\nfor (const item of items) {\n this.processItem(item);\n}\n\\`\\`\\`\n\n### Pattern 2: Extract Conditional Blocks\n\\`\\`\\`typescript\n// BEFORE\nif (isAdmin(user)) {\n // 15 lines of admin logic\n}\n\n// AFTER\nif (isAdmin(user)) {\n this.handleAdminUser(user);\n}\n\\`\\`\\`\n\n### Pattern 3: Extract Data Transformations\n\\`\\`\\`typescript\n// BEFORE\nconst result = {\n // 10+ lines of object construction\n};\n\n// AFTER\nconst result = this.buildResultObject(data);\n\\`\\`\\`\n\n## If Refactoring Is Not Feasible\n\nSometimes methods genuinely need to be longer (complex algorithms, state machines, etc.).\n\n**Escape hatch**: Add a webpieces-disable comment with justification:\n\n\\`\\`\\`typescript\n// webpieces-disable max-lines-new-methods -- Complex state machine, splitting reduces clarity\nasync complexStateMachine(): Promise<void> {\n // ... longer method with justification\n}\n\\`\\`\\`\n\n## AI Agent Action Steps\n\n1. **READ** the method to understand its logical sections\n2. **IDENTIFY** logical units that can be extracted\n3. **EXTRACT** into well-named private methods\n4. **VERIFY** the main method now reads like a table of contents\n5. **IF NOT FEASIBLE**: Add webpieces-disable max-lines-new-methods comment with clear justification\n\n## Remember\n\n- Every method you write today will be read many times tomorrow\n- The best code explains itself through structure\n- When in doubt, extract and name it\n`;\n\n/**\n * Write the instructions documentation to tmp directory\n */\nfunction writeTmpInstructions(workspaceRoot: string): string {\n const tmpDir = path.join(workspaceRoot, TMP_DIR);\n const mdPath = path.join(tmpDir, TMP_MD_FILE);\n\n fs.mkdirSync(tmpDir, { recursive: true });\n fs.writeFileSync(mdPath, METHODSIZE_DOC_CONTENT);\n\n return mdPath;\n}\n\n/**\n * Get changed TypeScript files between base and working tree.\n * Uses `git diff base` (no three-dots) to match what `nx affected` does -\n * this includes both committed and uncommitted changes in one diff.\n */\nfunction getChangedTypeScriptFiles(workspaceRoot: string, base: string): string[] {\n try {\n // Use two-dot diff (base to working tree) - same as nx affected\n const output = execSync(`git diff --name-only ${base} -- '*.ts' '*.tsx'`, {\n cwd: workspaceRoot,\n encoding: 'utf-8',\n });\n return output\n .trim()\n .split('\\n')\n .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));\n } catch {\n return [];\n }\n}\n\n/**\n * Get the diff content for a specific file between base and working tree.\n * Uses `git diff base` (no three-dots) to match what `nx affected` does -\n * this includes both committed and uncommitted changes in one diff.\n */\nfunction getFileDiff(workspaceRoot: string, file: string, base: string): string {\n try {\n // Use two-dot diff (base to working tree) - same as nx affected\n return execSync(`git diff ${base} -- \"${file}\"`, {\n cwd: workspaceRoot,\n encoding: 'utf-8',\n });\n } catch {\n return '';\n }\n}\n\n/**\n * Parse diff to find newly added method signatures\n */\nfunction findNewMethodSignaturesInDiff(diffContent: string): Set<string> {\n const newMethods = new Set<string>();\n const lines = diffContent.split('\\n');\n\n // Patterns to match method definitions\n const patterns = [\n // [export] [async] function methodName( - most explicit, check first\n /^\\+\\s*(?:export\\s+)?(?:async\\s+)?function\\s+(\\w+)\\s*\\(/,\n // [export] const/let methodName = [async] (\n /^\\+\\s*(?:export\\s+)?(?:const|let)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\(/,\n // [export] const/let methodName = [async] function\n /^\\+\\s*(?:export\\s+)?(?:const|let)\\s+(\\w+)\\s*=\\s*(?:async\\s+)?function/,\n // class method: [async] methodName( - but NOT constructor, if, for, while, etc.\n /^\\+\\s*(?:async\\s+)?(\\w+)\\s*\\(/,\n ];\n\n for (const line of lines) {\n if (line.startsWith('+') && !line.startsWith('+++')) {\n for (const pattern of patterns) {\n const match = line.match(pattern);\n if (match) {\n // Extract method name - now always in capture group 1\n const methodName = match[1];\n if (methodName && !['if', 'for', 'while', 'switch', 'catch', 'constructor'].includes(methodName)) {\n newMethods.add(methodName);\n }\n break;\n }\n }\n }\n }\n\n return newMethods;\n}\n\n/**\n * Check if a line contains a webpieces-disable comment that exempts from new method validation.\n * Both max-lines-new-methods AND max-lines-new-and-modified are accepted here.\n * - max-lines-new-methods: Exempts from 30-line check, still checked by 80-line validator\n * - max-lines-new-and-modified: Exempts from both validators (ultimate escape hatch)\n */\nfunction hasDisableComment(lines: string[], lineNumber: number): boolean {\n // Check the line before the method (lineNumber is 1-indexed, array is 0-indexed)\n // We need to check a few lines before in case there's JSDoc or decorators\n const startCheck = Math.max(0, lineNumber - 5);\n for (let i = lineNumber - 2; i >= startCheck; i--) {\n const line = lines[i]?.trim() ?? '';\n // Stop if we hit another function/class/etc\n if (line.startsWith('function ') || line.startsWith('class ') || line.endsWith('}')) {\n break;\n }\n if (line.includes('webpieces-disable')) {\n // Either escape hatch exempts from the 30-line new method check\n if (line.includes('max-lines-new-methods') || line.includes('max-lines-new-and-modified')) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Parse a TypeScript file and find methods with their line counts\n */\nfunction findMethodsInFile(\n filePath: string,\n workspaceRoot: string\n): Array<{ name: string; line: number; lines: number; hasDisableComment: boolean }> {\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const fileLines = content.split('\\n');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n\n const methods: Array<{ name: string; line: number; lines: number; hasDisableComment: boolean }> = [];\n\n function visit(node: ts.Node): void {\n let methodName: string | undefined;\n let startLine: number | undefined;\n let endLine: number | undefined;\n\n if (ts.isMethodDeclaration(node) && node.name) {\n methodName = node.name.getText(sourceFile);\n const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());\n startLine = start.line + 1;\n endLine = end.line + 1;\n } else if (ts.isFunctionDeclaration(node) && node.name) {\n methodName = node.name.getText(sourceFile);\n const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());\n startLine = start.line + 1;\n endLine = end.line + 1;\n } else if (ts.isArrowFunction(node)) {\n // Check if it's assigned to a variable\n if (ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name)) {\n methodName = node.parent.name.getText(sourceFile);\n const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());\n startLine = start.line + 1;\n endLine = end.line + 1;\n }\n }\n\n if (methodName && startLine !== undefined && endLine !== undefined) {\n methods.push({\n name: methodName,\n line: startLine,\n lines: endLine - startLine + 1,\n hasDisableComment: hasDisableComment(fileLines, startLine),\n });\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return methods;\n}\n\n/**\n * Find new methods that exceed the line limit\n */\nfunction findViolations(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n maxLines: number\n): MethodViolation[] {\n const violations: MethodViolation[] = [];\n\n for (const file of changedFiles) {\n // Get the diff to find which methods are NEW (not just modified)\n const diff = getFileDiff(workspaceRoot, file, base);\n const newMethodNames = findNewMethodSignaturesInDiff(diff);\n\n if (newMethodNames.size === 0) continue;\n\n // Parse the current file to get method line counts\n const methods = findMethodsInFile(file, workspaceRoot);\n\n for (const method of methods) {\n // Only check NEW methods that don't have webpieces-disable comment\n if (newMethodNames.has(method.name) && method.lines > maxLines && !method.hasDisableComment) {\n violations.push({\n file,\n methodName: method.name,\n line: method.line,\n lines: method.lines,\n isNew: true,\n });\n }\n }\n }\n\n return violations;\n}\n\n/**\n * Auto-detect the base branch by finding the merge-base with origin/main.\n * This allows the executor to run even when NX_BASE isn't set (e.g., via dependsOn).\n */\nfunction detectBase(workspaceRoot: string): string | null {\n try {\n // First, try to get merge-base with origin/main\n const mergeBase = execSync('git merge-base HEAD origin/main', {\n cwd: workspaceRoot,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n\n if (mergeBase) {\n return mergeBase;\n }\n } catch {\n // origin/main might not exist, try main\n try {\n const mergeBase = execSync('git merge-base HEAD main', {\n cwd: workspaceRoot,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n\n if (mergeBase) {\n return mergeBase;\n }\n } catch {\n // Ignore - will return null\n }\n }\n return null;\n}\n\nexport default async function runExecutor(\n options: ValidateNewMethodsOptions,\n context: ExecutorContext\n): Promise<ExecutorResult> {\n const workspaceRoot = context.root;\n const maxLines = options.max ?? 30;\n\n // Check if running in affected mode via NX_BASE, or auto-detect\n // We use NX_BASE as the base, and compare to WORKING TREE (not NX_HEAD)\n // This matches what `nx affected` does - it compares base to working tree\n let base = process.env['NX_BASE'];\n\n if (!base) {\n // Try to auto-detect base from git merge-base\n base = detectBase(workspaceRoot) ?? undefined;\n\n if (!base) {\n console.log('\\n⏭️ Skipping new method validation (could not detect base branch)');\n console.log(' To run explicitly: nx affected --target=validate-new-methods --base=origin/main');\n console.log('');\n return { success: true };\n }\n\n console.log('\\n📏 Validating New Method Sizes (auto-detected base)\\n');\n } else {\n console.log('\\n📏 Validating New Method Sizes\\n');\n }\n\n console.log(` Base: ${base}`);\n console.log(` Comparing to: working tree (includes uncommitted changes)`);\n console.log(` Max lines for new methods: ${maxLines}`);\n console.log('');\n\n try {\n // Get changed TypeScript files (base to working tree, like nx affected)\n const changedFiles = getChangedTypeScriptFiles(workspaceRoot, base);\n\n if (changedFiles.length === 0) {\n console.log('✅ No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);\n\n // Find violations\n const violations = findViolations(workspaceRoot, changedFiles, base, maxLines);\n\n if (violations.length === 0) {\n console.log('✅ All new methods are under ' + maxLines + ' lines');\n return { success: true };\n }\n\n // Write instructions file\n writeTmpInstructions(workspaceRoot);\n\n // Report violations\n console.error('');\n console.error('❌ New methods exceed ' + maxLines + ' lines!');\n console.error('');\n console.error('📚 Methods should read like a \"table of contents\" - each method call');\n console.error(' describes a larger piece of work. You can refactor');\n console.error(' to stay under ' + maxLines + ' lines 50% of the time. If not feasible, use the escape hatch.');\n console.error('');\n console.error('⚠️ *** READ tmp/webpieces/webpieces.methodsize.md for detailed guidance on how to fix this easily *** ⚠️');\n console.error('');\n\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}`);\n console.error(` Method: ${v.methodName} (${v.lines} lines, max: ${maxLines})`);\n }\n console.error('');\n\n return { success: false };\n } catch (err: unknown) {\n const error = err instanceof Error ? err : new Error(String(err));\n console.error('❌ New method validation failed:', error.message);\n return { success: false };\n }\n}\n"]}
1
+ {"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/dev-config/architecture/executors/validate-new-methods/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;GAgBG;;AAiaH,8BA8DC;;AA5dD,iDAAyC;AACzC,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AAkBjC,MAAM,OAAO,GAAG,eAAe,CAAC;AAChC,MAAM,WAAW,GAAG,yBAAyB,CAAC;AAE9C,MAAM,sBAAsB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoH9B,CAAC;AAEF;;GAEG;AACH,SAAS,oBAAoB,CAAC,aAAqB;IAC/C,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;IACjD,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;IAE9C,EAAE,CAAC,SAAS,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,C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Aa,CAAC,CAAC;QACpC,gBAAgB,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;QAEvC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;QAClE,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAChE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;AACL,CAAC","sourcesContent":["/**\n * Validate New Methods Executor\n *\n * Validates that newly added methods don't exceed a maximum line count.\n * Runs in affected mode when:\n * 1. NX_BASE environment variable is set (via nx affected), OR\n * 2. Auto-detects base by finding merge-base with origin/main\n *\n * This validator encourages writing methods that read like a \"table of contents\"\n * where each method call describes a larger piece of work.\n *\n * Usage:\n * nx affected --target=validate-new-methods --base=origin/main\n * OR: runs automatically via build's architecture:validate-complete dependency\n *\n * Escape hatch: Add webpieces-disable max-lines-new-methods comment with justification\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\n\nexport interface ValidateNewMethodsOptions {\n max?: number;\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\ninterface MethodViolation {\n file: string;\n methodName: string;\n line: number;\n lines: number;\n isNew: boolean;\n}\n\nconst TMP_DIR = 'tmp/webpieces';\nconst TMP_MD_FILE = 'webpieces.methodsize.md';\n\nconst METHODSIZE_DOC_CONTENT = `# Instructions: New Method Too Long\n\n## Requirement\n\n**~50% of the time**, you can stay under the \\`newMethodsMaxLines\\` limit from nx.json\nby extracting logical units into well-named methods.\n\n**~99% of the time**, you can stay under the \\`modifiedAndNewMethodsMaxLines\\` limit from nx.json.\nNearly all software can be written with methods under this size.\n\n## The \"Table of Contents\" Principle\n\nGood code reads like a book's table of contents:\n- Chapter titles (method names) tell you WHAT happens\n- Reading chapter titles gives you the full story\n- You can dive into chapters (implementations) for details\n\n## Why Limit New Methods?\n\nMethods under the limit are:\n- Easy to review in a single screen\n- Simple to understand without scrolling\n- Quick for AI to analyze and suggest improvements\n- More testable in isolation\n- Self-documenting through well-named extracted methods\n\nExtracting logical units into well-named methods makes code more readable for both\nAI and humans.\n\n## How to Refactor\n\nInstead of:\n\\`\\`\\`typescript\nasync processOrder(order: Order): Promise<Result> {\n // 50 lines of validation, transformation, saving, notifications...\n}\n\\`\\`\\`\n\nWrite:\n\\`\\`\\`typescript\nasync processOrder(order: Order): Promise<Result> {\n const validated = this.validateOrder(order);\n const transformed = this.applyBusinessRules(validated);\n const saved = await this.saveToDatabase(transformed);\n await this.notifyStakeholders(saved);\n return this.buildResult(saved);\n}\n\\`\\`\\`\n\nNow the main method is a \"table of contents\" - each line tells part of the story!\n\n## Patterns for Extraction\n\n### Pattern 1: Extract Loop Bodies\n\\`\\`\\`typescript\n// BEFORE\nfor (const item of items) {\n // 20 lines of processing\n}\n\n// AFTER\nfor (const item of items) {\n this.processItem(item);\n}\n\\`\\`\\`\n\n### Pattern 2: Extract Conditional Blocks\n\\`\\`\\`typescript\n// BEFORE\nif (isAdmin(user)) {\n // 15 lines of admin logic\n}\n\n// AFTER\nif (isAdmin(user)) {\n this.handleAdminUser(user);\n}\n\\`\\`\\`\n\n### Pattern 3: Extract Data Transformations\n\\`\\`\\`typescript\n// BEFORE\nconst result = {\n // 10+ lines of object construction\n};\n\n// AFTER\nconst result = this.buildResultObject(data);\n\\`\\`\\`\n\n## If Refactoring Is Not Feasible\n\nSometimes methods genuinely need to be longer (complex algorithms, state machines, etc.).\n\n**Escape hatch**: Add a webpieces-disable comment with justification:\n\n\\`\\`\\`typescript\n// webpieces-disable max-lines-new-methods -- Complex state machine, splitting reduces clarity\nasync complexStateMachine(): Promise<void> {\n // ... longer method with justification\n}\n\\`\\`\\`\n\n## AI Agent Action Steps\n\n1. **READ** the method to understand its logical sections\n2. **IDENTIFY** logical units that can be extracted\n3. **EXTRACT** into well-named private methods\n4. **VERIFY** the main method now reads like a table of contents\n5. **IF NOT FEASIBLE**: Add webpieces-disable max-lines-new-methods comment with clear justification\n\n## Remember\n\n- Every method you write today will be read many times tomorrow\n- The best code explains itself through structure\n- When in doubt, extract and name it\n`;\n\n/**\n * Write the instructions documentation to tmp directory\n */\nfunction writeTmpInstructions(workspaceRoot: string): string {\n const tmpDir = path.join(workspaceRoot, TMP_DIR);\n const mdPath = path.join(tmpDir, TMP_MD_FILE);\n\n fs.mkdirSync(tmpDir, { recursive: true });\n fs.writeFileSync(mdPath, METHODSIZE_DOC_CONTENT);\n\n return mdPath;\n}\n\n/**\n * Get changed TypeScript files between base and working tree.\n * Uses `git diff base` (no three-dots) to match what `nx affected` does -\n * this includes both committed and uncommitted changes in one diff.\n */\nfunction getChangedTypeScriptFiles(workspaceRoot: string, base: string): string[] {\n try {\n // Use two-dot diff (base to working tree) - same as nx affected\n const output = execSync(`git diff --name-only ${base} -- '*.ts' '*.tsx'`, {\n cwd: workspaceRoot,\n encoding: 'utf-8',\n });\n return output\n .trim()\n .split('\\n')\n .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));\n } catch {\n return [];\n }\n}\n\n/**\n * Get the diff content for a specific file between base and working tree.\n * Uses `git diff base` (no three-dots) to match what `nx affected` does -\n * this includes both committed and uncommitted changes in one diff.\n */\nfunction getFileDiff(workspaceRoot: string, file: string, base: string): string {\n try {\n // Use two-dot diff (base to working tree) - same as nx affected\n return execSync(`git diff ${base} -- \"${file}\"`, {\n cwd: workspaceRoot,\n encoding: 'utf-8',\n });\n } catch {\n return '';\n }\n}\n\n/**\n * Parse diff to find newly added method signatures\n */\nfunction findNewMethodSignaturesInDiff(diffContent: string): Set<string> {\n const newMethods = new Set<string>();\n const lines = diffContent.split('\\n');\n\n // Patterns to match method definitions\n const patterns = [\n // [export] [async] function methodName( - most explicit, check first\n /^\\+\\s*(?:export\\s+)?(?:async\\s+)?function\\s+(\\w+)\\s*\\(/,\n // [export] const/let methodName = [async] (\n /^\\+\\s*(?:export\\s+)?(?:const|let)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\(/,\n // [export] const/let methodName = [async] function\n /^\\+\\s*(?:export\\s+)?(?:const|let)\\s+(\\w+)\\s*=\\s*(?:async\\s+)?function/,\n // class method: [async] methodName( - but NOT constructor, if, for, while, etc.\n /^\\+\\s*(?:async\\s+)?(\\w+)\\s*\\(/,\n ];\n\n for (const line of lines) {\n if (line.startsWith('+') && !line.startsWith('+++')) {\n for (const pattern of patterns) {\n const match = line.match(pattern);\n if (match) {\n // Extract method name - now always in capture group 1\n const methodName = match[1];\n if (methodName && !['if', 'for', 'while', 'switch', 'catch', 'constructor'].includes(methodName)) {\n newMethods.add(methodName);\n }\n break;\n }\n }\n }\n }\n\n return newMethods;\n}\n\n/**\n * Check if a line contains a webpieces-disable comment that exempts from new method validation.\n * Both max-lines-new-methods AND max-lines-new-and-modified are accepted here.\n * - max-lines-new-methods: Exempts from 30-line check, still checked by 80-line validator\n * - max-lines-new-and-modified: Exempts from both validators (ultimate escape hatch)\n */\nfunction hasDisableComment(lines: string[], lineNumber: number): boolean {\n // Check the line before the method (lineNumber is 1-indexed, array is 0-indexed)\n // We need to check a few lines before in case there's JSDoc or decorators\n const startCheck = Math.max(0, lineNumber - 5);\n for (let i = lineNumber - 2; i >= startCheck; i--) {\n const line = lines[i]?.trim() ?? '';\n // Stop if we hit another function/class/etc\n if (line.startsWith('function ') || line.startsWith('class ') || line.endsWith('}')) {\n break;\n }\n if (line.includes('webpieces-disable')) {\n // Either escape hatch exempts from the 30-line new method check\n if (line.includes('max-lines-new-methods') || line.includes('max-lines-new-and-modified')) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Parse a TypeScript file and find methods with their line counts\n */\nfunction findMethodsInFile(\n filePath: string,\n workspaceRoot: string\n): Array<{ name: string; line: number; lines: number; hasDisableComment: boolean }> {\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const fileLines = content.split('\\n');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n\n const methods: Array<{ name: string; line: number; lines: number; hasDisableComment: boolean }> = [];\n\n function visit(node: ts.Node): void {\n let methodName: string | undefined;\n let startLine: number | undefined;\n let endLine: number | undefined;\n\n if (ts.isMethodDeclaration(node) && node.name) {\n methodName = node.name.getText(sourceFile);\n const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());\n startLine = start.line + 1;\n endLine = end.line + 1;\n } else if (ts.isFunctionDeclaration(node) && node.name) {\n methodName = node.name.getText(sourceFile);\n const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());\n startLine = start.line + 1;\n endLine = end.line + 1;\n } else if (ts.isArrowFunction(node)) {\n // Check if it's assigned to a variable\n if (ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name)) {\n methodName = node.parent.name.getText(sourceFile);\n const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());\n startLine = start.line + 1;\n endLine = end.line + 1;\n }\n }\n\n if (methodName && startLine !== undefined && endLine !== undefined) {\n methods.push({\n name: methodName,\n line: startLine,\n lines: endLine - startLine + 1,\n hasDisableComment: hasDisableComment(fileLines, startLine),\n });\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return methods;\n}\n\n/**\n * Find new methods that exceed the line limit\n */\nfunction findViolations(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n maxLines: number\n): MethodViolation[] {\n const violations: MethodViolation[] = [];\n\n for (const file of changedFiles) {\n // Get the diff to find which methods are NEW (not just modified)\n const diff = getFileDiff(workspaceRoot, file, base);\n const newMethodNames = findNewMethodSignaturesInDiff(diff);\n\n if (newMethodNames.size === 0) continue;\n\n // Parse the current file to get method line counts\n const methods = findMethodsInFile(file, workspaceRoot);\n\n for (const method of methods) {\n // Only check NEW methods that don't have webpieces-disable comment\n if (newMethodNames.has(method.name) && method.lines > maxLines && !method.hasDisableComment) {\n violations.push({\n file,\n methodName: method.name,\n line: method.line,\n lines: method.lines,\n isNew: true,\n });\n }\n }\n }\n\n return violations;\n}\n\n/**\n * Auto-detect the base branch by finding the merge-base with origin/main.\n * This allows the executor to run even when NX_BASE isn't set (e.g., via dependsOn).\n */\nfunction detectBase(workspaceRoot: string): string | null {\n try {\n // First, try to get merge-base with origin/main\n const mergeBase = execSync('git merge-base HEAD origin/main', {\n cwd: workspaceRoot,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n\n if (mergeBase) {\n return mergeBase;\n }\n } catch {\n // origin/main might not exist, try main\n try {\n const mergeBase = execSync('git merge-base HEAD main', {\n cwd: workspaceRoot,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n\n if (mergeBase) {\n return mergeBase;\n }\n } catch {\n // Ignore - will return null\n }\n }\n return null;\n}\n\n/**\n * Report violations to the user with helpful instructions\n */\nfunction reportViolations(violations: MethodViolation[], maxLines: number): void {\n console.error('');\n console.error('❌ New methods exceed ' + maxLines + ' lines!');\n console.error('');\n console.error('📚 Methods should read like a \"table of contents\" - each method call');\n console.error(' describes a larger piece of work. You can refactor');\n console.error(' to stay under ' + maxLines + ' lines 50% of the time.');\n console.error('');\n console.error('⚠️ *** READ tmp/webpieces/webpieces.methodsize.md for detailed guidance on how to fix this easily *** ⚠️');\n console.error('');\n\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}`);\n console.error(` Method: ${v.methodName} (${v.lines} lines, max: ${maxLines})`);\n }\n console.error('');\n console.error(' If you REALLY REALLY need more than ' + maxLines + ' lines, this happens 50% of the time,');\n console.error(' so use escape: // webpieces-disable max-lines-new-methods -- [your reason]');\n console.error('');\n}\n\nexport default async function runExecutor(\n options: ValidateNewMethodsOptions,\n context: ExecutorContext\n): Promise<ExecutorResult> {\n const workspaceRoot = context.root;\n const maxLines = options.max ?? 30;\n\n // Check if running in affected mode via NX_BASE, or auto-detect\n // We use NX_BASE as the base, and compare to WORKING TREE (not NX_HEAD)\n // This matches what `nx affected` does - it compares base to working tree\n let base = process.env['NX_BASE'];\n\n if (!base) {\n // Try to auto-detect base from git merge-base\n base = detectBase(workspaceRoot) ?? undefined;\n\n if (!base) {\n console.log('\\n⏭️ Skipping new method validation (could not detect base branch)');\n console.log(' To run explicitly: nx affected --target=validate-new-methods --base=origin/main');\n console.log('');\n return { success: true };\n }\n\n console.log('\\n📏 Validating New Method Sizes (auto-detected base)\\n');\n } else {\n console.log('\\n📏 Validating New Method Sizes\\n');\n }\n\n console.log(` Base: ${base}`);\n console.log(` Comparing to: working tree (includes uncommitted changes)`);\n console.log(` Max lines for new methods: ${maxLines}`);\n console.log('');\n\n try {\n // Get changed TypeScript files (base to working tree, like nx affected)\n const changedFiles = getChangedTypeScriptFiles(workspaceRoot, base);\n\n if (changedFiles.length === 0) {\n console.log('✅ No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);\n\n // Find violations\n const violations = findViolations(workspaceRoot, changedFiles, base, maxLines);\n\n if (violations.length === 0) {\n console.log('✅ All new methods are under ' + maxLines + ' lines');\n return { success: true };\n }\n\n // Write instructions file and report violations\n writeTmpInstructions(workspaceRoot);\n reportViolations(violations, maxLines);\n\n return { success: false };\n } catch (err: unknown) {\n const error = err instanceof Error ? err : new Error(String(err));\n console.error('❌ New method validation failed:', error.message);\n return { success: false };\n }\n}\n"]}
@@ -407,6 +407,30 @@ function detectBase(workspaceRoot: string): string | null {
407
407
  return null;
408
408
  }
409
409
 
410
+ /**
411
+ * Report violations to the user with helpful instructions
412
+ */
413
+ function reportViolations(violations: MethodViolation[], maxLines: number): void {
414
+ console.error('');
415
+ console.error('❌ New methods exceed ' + maxLines + ' lines!');
416
+ console.error('');
417
+ console.error('📚 Methods should read like a "table of contents" - each method call');
418
+ console.error(' describes a larger piece of work. You can refactor');
419
+ console.error(' to stay under ' + maxLines + ' lines 50% of the time.');
420
+ console.error('');
421
+ console.error('⚠️ *** READ tmp/webpieces/webpieces.methodsize.md for detailed guidance on how to fix this easily *** ⚠️');
422
+ console.error('');
423
+
424
+ for (const v of violations) {
425
+ console.error(` ❌ ${v.file}:${v.line}`);
426
+ console.error(` Method: ${v.methodName} (${v.lines} lines, max: ${maxLines})`);
427
+ }
428
+ console.error('');
429
+ console.error(' If you REALLY REALLY need more than ' + maxLines + ' lines, this happens 50% of the time,');
430
+ console.error(' so use escape: // webpieces-disable max-lines-new-methods -- [your reason]');
431
+ console.error('');
432
+ }
433
+
410
434
  export default async function runExecutor(
411
435
  options: ValidateNewMethodsOptions,
412
436
  context: ExecutorContext
@@ -459,25 +483,9 @@ export default async function runExecutor(
459
483
  return { success: true };
460
484
  }
461
485
 
462
- // Write instructions file
486
+ // Write instructions file and report violations
463
487
  writeTmpInstructions(workspaceRoot);
464
-
465
- // Report violations
466
- console.error('');
467
- console.error('❌ New methods exceed ' + maxLines + ' lines!');
468
- console.error('');
469
- console.error('📚 Methods should read like a "table of contents" - each method call');
470
- console.error(' describes a larger piece of work. You can refactor');
471
- console.error(' to stay under ' + maxLines + ' lines 50% of the time. If not feasible, use the escape hatch.');
472
- console.error('');
473
- console.error('⚠️ *** READ tmp/webpieces/webpieces.methodsize.md for detailed guidance on how to fix this easily *** ⚠️');
474
- console.error('');
475
-
476
- for (const v of violations) {
477
- console.error(` ❌ ${v.file}:${v.line}`);
478
- console.error(` Method: ${v.methodName} (${v.lines} lines, max: ${maxLines})`);
479
- }
480
- console.error('');
488
+ reportViolations(violations, maxLines);
481
489
 
482
490
  return { success: false };
483
491
  } catch (err: unknown) {