@webpieces/dev-config 0.2.94 → 0.2.97

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/config/eslint/base.mjs +1 -1
  2. package/executors.json +6 -91
  3. package/package.json +6 -19
  4. package/{executors → src/executors}/help/executor.d.ts +4 -2
  5. package/src/executors/help/executor.js.map +1 -0
  6. package/{executors → src/executors}/validate-eslint-sync/executor.d.ts +3 -2
  7. package/src/executors/validate-eslint-sync/executor.js.map +1 -0
  8. package/{executors → src/executors}/validate-versions-locked/executor.js +5 -3
  9. package/src/executors/validate-versions-locked/executor.js.map +1 -0
  10. package/src/generators/init/generator.js.map +1 -1
  11. package/src/index.d.ts +1 -1
  12. package/src/index.js +1 -1
  13. package/src/index.js.map +1 -1
  14. package/src/plugin.d.ts +86 -0
  15. package/{plugin.js → src/plugin.js} +31 -15
  16. package/src/plugin.js.map +1 -0
  17. package/src/toError.d.ts +5 -0
  18. package/src/toError.js +37 -0
  19. package/src/toError.js.map +1 -0
  20. package/templates/eslint.webpieces.config.mjs +1 -1
  21. package/templates/webpieces.exceptions.md +15 -15
  22. package/architecture/executors/diff-utils.d.ts +0 -24
  23. package/architecture/executors/diff-utils.js +0 -119
  24. package/architecture/executors/diff-utils.js.map +0 -1
  25. package/architecture/executors/diff-utils.ts +0 -127
  26. package/architecture/executors/generate/executor.d.ts +0 -16
  27. package/architecture/executors/generate/executor.js +0 -44
  28. package/architecture/executors/generate/executor.js.map +0 -1
  29. package/architecture/executors/generate/executor.ts +0 -59
  30. package/architecture/executors/generate/schema.json +0 -14
  31. package/architecture/executors/validate-architecture-unchanged/executor.d.ts +0 -17
  32. package/architecture/executors/validate-architecture-unchanged/executor.js +0 -229
  33. package/architecture/executors/validate-architecture-unchanged/executor.js.map +0 -1
  34. package/architecture/executors/validate-architecture-unchanged/executor.ts +0 -251
  35. package/architecture/executors/validate-architecture-unchanged/schema.json +0 -14
  36. package/architecture/executors/validate-code/executor.d.ts +0 -78
  37. package/architecture/executors/validate-code/executor.js +0 -243
  38. package/architecture/executors/validate-code/executor.js.map +0 -1
  39. package/architecture/executors/validate-code/executor.ts +0 -406
  40. package/architecture/executors/validate-code/schema.json +0 -227
  41. package/architecture/executors/validate-dtos/executor.d.ts +0 -42
  42. package/architecture/executors/validate-dtos/executor.js +0 -561
  43. package/architecture/executors/validate-dtos/executor.js.map +0 -1
  44. package/architecture/executors/validate-dtos/executor.ts +0 -689
  45. package/architecture/executors/validate-dtos/schema.json +0 -33
  46. package/architecture/executors/validate-modified-files/executor.d.ts +0 -25
  47. package/architecture/executors/validate-modified-files/executor.js +0 -501
  48. package/architecture/executors/validate-modified-files/executor.js.map +0 -1
  49. package/architecture/executors/validate-modified-files/executor.ts +0 -571
  50. package/architecture/executors/validate-modified-files/schema.json +0 -25
  51. package/architecture/executors/validate-modified-methods/executor.d.ts +0 -31
  52. package/architecture/executors/validate-modified-methods/executor.js +0 -694
  53. package/architecture/executors/validate-modified-methods/executor.js.map +0 -1
  54. package/architecture/executors/validate-modified-methods/executor.ts +0 -797
  55. package/architecture/executors/validate-modified-methods/schema.json +0 -25
  56. package/architecture/executors/validate-new-methods/executor.d.ts +0 -28
  57. package/architecture/executors/validate-new-methods/executor.js +0 -513
  58. package/architecture/executors/validate-new-methods/executor.js.map +0 -1
  59. package/architecture/executors/validate-new-methods/executor.ts +0 -584
  60. package/architecture/executors/validate-new-methods/schema.json +0 -25
  61. package/architecture/executors/validate-no-any-unknown/executor.d.ts +0 -42
  62. package/architecture/executors/validate-no-any-unknown/executor.js +0 -462
  63. package/architecture/executors/validate-no-any-unknown/executor.js.map +0 -1
  64. package/architecture/executors/validate-no-any-unknown/executor.ts +0 -540
  65. package/architecture/executors/validate-no-any-unknown/schema.json +0 -24
  66. package/architecture/executors/validate-no-architecture-cycles/executor.d.ts +0 -16
  67. package/architecture/executors/validate-no-architecture-cycles/executor.js +0 -48
  68. package/architecture/executors/validate-no-architecture-cycles/executor.js.map +0 -1
  69. package/architecture/executors/validate-no-architecture-cycles/executor.ts +0 -60
  70. package/architecture/executors/validate-no-architecture-cycles/schema.json +0 -8
  71. package/architecture/executors/validate-no-destructure/executor.d.ts +0 -52
  72. package/architecture/executors/validate-no-destructure/executor.js +0 -491
  73. package/architecture/executors/validate-no-destructure/executor.js.map +0 -1
  74. package/architecture/executors/validate-no-destructure/executor.ts +0 -578
  75. package/architecture/executors/validate-no-destructure/schema.json +0 -24
  76. package/architecture/executors/validate-no-direct-api-resolver/executor.d.ts +0 -47
  77. package/architecture/executors/validate-no-direct-api-resolver/executor.js +0 -566
  78. package/architecture/executors/validate-no-direct-api-resolver/executor.js.map +0 -1
  79. package/architecture/executors/validate-no-direct-api-resolver/executor.ts +0 -666
  80. package/architecture/executors/validate-no-direct-api-resolver/schema.json +0 -29
  81. package/architecture/executors/validate-no-inline-types/executor.d.ts +0 -91
  82. package/architecture/executors/validate-no-inline-types/executor.js +0 -669
  83. package/architecture/executors/validate-no-inline-types/executor.js.map +0 -1
  84. package/architecture/executors/validate-no-inline-types/executor.ts +0 -775
  85. package/architecture/executors/validate-no-inline-types/schema.json +0 -24
  86. package/architecture/executors/validate-no-skiplevel-deps/executor.d.ts +0 -19
  87. package/architecture/executors/validate-no-skiplevel-deps/executor.js +0 -227
  88. package/architecture/executors/validate-no-skiplevel-deps/executor.js.map +0 -1
  89. package/architecture/executors/validate-no-skiplevel-deps/executor.ts +0 -267
  90. package/architecture/executors/validate-no-skiplevel-deps/schema.json +0 -8
  91. package/architecture/executors/validate-packagejson/executor.d.ts +0 -16
  92. package/architecture/executors/validate-packagejson/executor.js +0 -57
  93. package/architecture/executors/validate-packagejson/executor.js.map +0 -1
  94. package/architecture/executors/validate-packagejson/executor.ts +0 -74
  95. package/architecture/executors/validate-packagejson/schema.json +0 -8
  96. package/architecture/executors/validate-prisma-converters/executor.d.ts +0 -60
  97. package/architecture/executors/validate-prisma-converters/executor.js +0 -634
  98. package/architecture/executors/validate-prisma-converters/executor.js.map +0 -1
  99. package/architecture/executors/validate-prisma-converters/executor.ts +0 -822
  100. package/architecture/executors/validate-prisma-converters/schema.json +0 -38
  101. package/architecture/executors/validate-return-types/executor.d.ts +0 -29
  102. package/architecture/executors/validate-return-types/executor.js +0 -439
  103. package/architecture/executors/validate-return-types/executor.js.map +0 -1
  104. package/architecture/executors/validate-return-types/executor.ts +0 -524
  105. package/architecture/executors/validate-return-types/schema.json +0 -24
  106. package/architecture/executors/visualize/executor.d.ts +0 -17
  107. package/architecture/executors/visualize/executor.js +0 -49
  108. package/architecture/executors/visualize/executor.js.map +0 -1
  109. package/architecture/executors/visualize/executor.ts +0 -63
  110. package/architecture/executors/visualize/schema.json +0 -14
  111. package/architecture/index.d.ts +0 -19
  112. package/architecture/index.js +0 -23
  113. package/architecture/index.js.map +0 -1
  114. package/architecture/index.ts +0 -20
  115. package/architecture/lib/graph-comparator.d.ts +0 -39
  116. package/architecture/lib/graph-comparator.js +0 -100
  117. package/architecture/lib/graph-comparator.js.map +0 -1
  118. package/architecture/lib/graph-comparator.ts +0 -141
  119. package/architecture/lib/graph-generator.d.ts +0 -19
  120. package/architecture/lib/graph-generator.js +0 -84
  121. package/architecture/lib/graph-generator.js.map +0 -1
  122. package/architecture/lib/graph-generator.ts +0 -97
  123. package/architecture/lib/graph-loader.d.ts +0 -31
  124. package/architecture/lib/graph-loader.js +0 -98
  125. package/architecture/lib/graph-loader.js.map +0 -1
  126. package/architecture/lib/graph-loader.ts +0 -116
  127. package/architecture/lib/graph-sorter.d.ts +0 -37
  128. package/architecture/lib/graph-sorter.js +0 -110
  129. package/architecture/lib/graph-sorter.js.map +0 -1
  130. package/architecture/lib/graph-sorter.ts +0 -137
  131. package/architecture/lib/graph-visualizer.d.ts +0 -29
  132. package/architecture/lib/graph-visualizer.js +0 -217
  133. package/architecture/lib/graph-visualizer.js.map +0 -1
  134. package/architecture/lib/graph-visualizer.ts +0 -231
  135. package/architecture/lib/package-validator.d.ts +0 -38
  136. package/architecture/lib/package-validator.js +0 -126
  137. package/architecture/lib/package-validator.js.map +0 -1
  138. package/architecture/lib/package-validator.ts +0 -170
  139. package/eslint-plugin/__tests__/catch-error-pattern.test.ts +0 -359
  140. package/eslint-plugin/__tests__/max-file-lines.test.ts +0 -207
  141. package/eslint-plugin/__tests__/max-method-lines.test.ts +0 -258
  142. package/eslint-plugin/__tests__/no-unmanaged-exceptions.test.ts +0 -359
  143. package/eslint-plugin/index.d.ts +0 -23
  144. package/eslint-plugin/index.js +0 -30
  145. package/eslint-plugin/index.js.map +0 -1
  146. package/eslint-plugin/index.ts +0 -29
  147. package/eslint-plugin/rules/catch-error-pattern.d.ts +0 -11
  148. package/eslint-plugin/rules/catch-error-pattern.js +0 -196
  149. package/eslint-plugin/rules/catch-error-pattern.js.map +0 -1
  150. package/eslint-plugin/rules/catch-error-pattern.ts +0 -281
  151. package/eslint-plugin/rules/enforce-architecture.d.ts +0 -15
  152. package/eslint-plugin/rules/enforce-architecture.js +0 -476
  153. package/eslint-plugin/rules/enforce-architecture.js.map +0 -1
  154. package/eslint-plugin/rules/enforce-architecture.ts +0 -543
  155. package/eslint-plugin/rules/max-file-lines.d.ts +0 -12
  156. package/eslint-plugin/rules/max-file-lines.js +0 -257
  157. package/eslint-plugin/rules/max-file-lines.js.map +0 -1
  158. package/eslint-plugin/rules/max-file-lines.ts +0 -272
  159. package/eslint-plugin/rules/max-method-lines.d.ts +0 -12
  160. package/eslint-plugin/rules/max-method-lines.js +0 -240
  161. package/eslint-plugin/rules/max-method-lines.js.map +0 -1
  162. package/eslint-plugin/rules/max-method-lines.ts +0 -287
  163. package/eslint-plugin/rules/no-unmanaged-exceptions.d.ts +0 -22
  164. package/eslint-plugin/rules/no-unmanaged-exceptions.js +0 -160
  165. package/eslint-plugin/rules/no-unmanaged-exceptions.js.map +0 -1
  166. package/eslint-plugin/rules/no-unmanaged-exceptions.ts +0 -179
  167. package/executors/help/executor.js.map +0 -1
  168. package/executors/help/executor.ts +0 -61
  169. package/executors/validate-eslint-sync/executor.js.map +0 -1
  170. package/executors/validate-eslint-sync/executor.ts +0 -83
  171. package/executors/validate-versions-locked/executor.js.map +0 -1
  172. package/executors/validate-versions-locked/executor.ts +0 -367
  173. package/plugin/README.md +0 -243
  174. package/plugin/index.d.ts +0 -4
  175. package/plugin/index.js +0 -8
  176. package/plugin/index.js.map +0 -1
  177. package/plugin/index.ts +0 -4
  178. /package/{executors → src/executors}/help/executor.js +0 -0
  179. /package/{executors → src/executors}/help/schema.json +0 -0
  180. /package/{executors → src/executors}/validate-eslint-sync/executor.js +0 -0
  181. /package/{executors → src/executors}/validate-eslint-sync/schema.json +0 -0
  182. /package/{executors → src/executors}/validate-versions-locked/executor.d.ts +0 -0
  183. /package/{executors → src/executors}/validate-versions-locked/schema.json +0 -0
@@ -1,60 +0,0 @@
1
- /**
2
- * Validate No Architecture Cycles Executor
3
- *
4
- * Validates that the architecture dependency graph has no circular dependencies.
5
- * This is a fast check that only validates acyclicity at the project level.
6
- *
7
- * Usage:
8
- * nx run architecture:validate-no-architecture-cycles
9
- */
10
-
11
- import type { ExecutorContext } from '@nx/devkit';
12
- import { generateGraph } from '../../lib/graph-generator';
13
- import { sortGraphTopologically } from '../../lib/graph-sorter';
14
-
15
- export interface ValidateNoCyclesOptions {
16
- // No options needed
17
- }
18
-
19
- export interface ExecutorResult {
20
- success: boolean;
21
- }
22
-
23
- export default async function runExecutor(
24
- _options: ValidateNoCyclesOptions,
25
- _context: ExecutorContext
26
- ): Promise<ExecutorResult> {
27
- console.log('\n🔄 Validating No Circular Dependencies\n');
28
-
29
- try {
30
- // Step 1: Generate current graph from project.json files
31
- console.log('📊 Generating dependency graph from project.json files...');
32
- const rawGraph = await generateGraph();
33
-
34
- // Step 2: Topological sort (validates acyclic)
35
- console.log('🔄 Checking for cycles (topological sort)...');
36
- try {
37
- sortGraphTopologically(rawGraph);
38
- console.log('✅ No circular dependencies detected!');
39
-
40
- // Print summary
41
- const projectCount = Object.keys(rawGraph).length;
42
- console.log(`\n📈 Summary: ${projectCount} projects, all acyclic`);
43
-
44
- return { success: true };
45
- } catch (err: unknown) {
46
- const error = err instanceof Error ? err : new Error(String(err));
47
- console.error('❌ Circular dependency detected!');
48
- console.error(error.message);
49
- console.error('\nTo fix:');
50
- console.error(' 1. Review the cycle above');
51
- console.error(' 2. Break the cycle by refactoring dependencies');
52
- console.error(' 3. Run this check again');
53
- return { success: false };
54
- }
55
- } catch (err: unknown) {
56
- const error = err instanceof Error ? err : new Error(String(err));
57
- console.error('❌ Cycle validation failed:', error.message);
58
- return { success: false };
59
- }
60
- }
@@ -1,8 +0,0 @@
1
- {
2
- "$schema": "http://json-schema.org/schema",
3
- "title": "Validate No Cycles Executor",
4
- "description": "Validates that the architecture graph has no circular dependencies",
5
- "type": "object",
6
- "properties": {},
7
- "required": []
8
- }
@@ -1,52 +0,0 @@
1
- /**
2
- * Validate No Destructure Executor
3
- *
4
- * Validates that destructuring patterns are not used in TypeScript code.
5
- * Uses LINE-BASED detection (not method-based) for git diff filtering.
6
- *
7
- * ============================================================================
8
- * VIOLATIONS (BAD) - These patterns are flagged:
9
- * ============================================================================
10
- *
11
- * - const { x, y } = obj — object destructuring in variable declarations
12
- * - const [a, b] = fn() — array destructuring (except Promise.all)
13
- * - for (const { email } of items) — object destructuring in for-of loops
14
- * - for (const [a, b] of items) — array destructuring in for-of (except Object.entries)
15
- * - const { page = 0 } = opts — destructuring with defaults
16
- * - const { done: streamDone } = obj — destructuring with renaming
17
- * - function foo({ x, y }: Type) — function parameter destructuring
18
- *
19
- * ============================================================================
20
- * ALLOWED (skip — NOT violations)
21
- * ============================================================================
22
- *
23
- * - const [a, b] = await Promise.all([...]) — Promise.all array destructuring
24
- * - for (const [key, value] of Object.entries(obj)) — Object.entries in for-of
25
- * - const { extracted, ...rest } = obj — rest operator separation
26
- * - Lines with // webpieces-disable no-destructure -- [reason] (only when disableAllowed: true)
27
- *
28
- * ============================================================================
29
- * MODES (LINE-BASED)
30
- * ============================================================================
31
- * - OFF: Skip validation entirely
32
- * - MODIFIED_CODE: Flag destructuring on changed lines (lines in diff hunks)
33
- * - MODIFIED_FILES: Flag ALL destructuring in files that were modified
34
- *
35
- * ============================================================================
36
- * ESCAPE HATCH
37
- * ============================================================================
38
- * Add comment above the violation:
39
- * // webpieces-disable no-destructure -- [your justification]
40
- * const { x, y } = obj;
41
- */
42
- import type { ExecutorContext } from '@nx/devkit';
43
- export type NoDestructureMode = 'OFF' | 'MODIFIED_CODE' | 'MODIFIED_FILES';
44
- export interface ValidateNoDestructureOptions {
45
- mode?: NoDestructureMode;
46
- disableAllowed?: boolean;
47
- ignoreModifiedUntilEpoch?: number;
48
- }
49
- export interface ExecutorResult {
50
- success: boolean;
51
- }
52
- export default function runExecutor(options: ValidateNoDestructureOptions, context: ExecutorContext): Promise<ExecutorResult>;
@@ -1,491 +0,0 @@
1
- "use strict";
2
- /**
3
- * Validate No Destructure Executor
4
- *
5
- * Validates that destructuring patterns are not used in TypeScript code.
6
- * Uses LINE-BASED detection (not method-based) for git diff filtering.
7
- *
8
- * ============================================================================
9
- * VIOLATIONS (BAD) - These patterns are flagged:
10
- * ============================================================================
11
- *
12
- * - const { x, y } = obj — object destructuring in variable declarations
13
- * - const [a, b] = fn() — array destructuring (except Promise.all)
14
- * - for (const { email } of items) — object destructuring in for-of loops
15
- * - for (const [a, b] of items) — array destructuring in for-of (except Object.entries)
16
- * - const { page = 0 } = opts — destructuring with defaults
17
- * - const { done: streamDone } = obj — destructuring with renaming
18
- * - function foo({ x, y }: Type) — function parameter destructuring
19
- *
20
- * ============================================================================
21
- * ALLOWED (skip — NOT violations)
22
- * ============================================================================
23
- *
24
- * - const [a, b] = await Promise.all([...]) — Promise.all array destructuring
25
- * - for (const [key, value] of Object.entries(obj)) — Object.entries in for-of
26
- * - const { extracted, ...rest } = obj — rest operator separation
27
- * - Lines with // webpieces-disable no-destructure -- [reason] (only when disableAllowed: true)
28
- *
29
- * ============================================================================
30
- * MODES (LINE-BASED)
31
- * ============================================================================
32
- * - OFF: Skip validation entirely
33
- * - MODIFIED_CODE: Flag destructuring on changed lines (lines in diff hunks)
34
- * - MODIFIED_FILES: Flag ALL destructuring in files that were modified
35
- *
36
- * ============================================================================
37
- * ESCAPE HATCH
38
- * ============================================================================
39
- * Add comment above the violation:
40
- * // webpieces-disable no-destructure -- [your justification]
41
- * const { x, y } = obj;
42
- */
43
- Object.defineProperty(exports, "__esModule", { value: true });
44
- exports.default = runExecutor;
45
- const tslib_1 = require("tslib");
46
- const child_process_1 = require("child_process");
47
- const fs = tslib_1.__importStar(require("fs"));
48
- const path = tslib_1.__importStar(require("path"));
49
- const ts = tslib_1.__importStar(require("typescript"));
50
- /**
51
- * Get changed TypeScript files between base and head (or working tree if head not specified).
52
- */
53
- // webpieces-disable max-lines-new-methods -- Git command handling with untracked files requires multiple code paths
54
- function getChangedTypeScriptFiles(workspaceRoot, base, head) {
55
- try {
56
- const diffTarget = head ? `${base} ${head}` : base;
57
- const output = (0, child_process_1.execSync)(`git diff --name-only ${diffTarget} -- '*.ts' '*.tsx'`, {
58
- cwd: workspaceRoot,
59
- encoding: 'utf-8',
60
- });
61
- const changedFiles = output
62
- .trim()
63
- .split('\n')
64
- .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
65
- if (!head) {
66
- try {
67
- const untrackedOutput = (0, child_process_1.execSync)(`git ls-files --others --exclude-standard '*.ts' '*.tsx'`, {
68
- cwd: workspaceRoot,
69
- encoding: 'utf-8',
70
- });
71
- const untrackedFiles = untrackedOutput
72
- .trim()
73
- .split('\n')
74
- .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
75
- const allFiles = new Set([...changedFiles, ...untrackedFiles]);
76
- return Array.from(allFiles);
77
- }
78
- catch {
79
- return changedFiles;
80
- }
81
- }
82
- return changedFiles;
83
- }
84
- catch {
85
- return [];
86
- }
87
- }
88
- /**
89
- * Get the diff content for a specific file.
90
- */
91
- function getFileDiff(workspaceRoot, file, base, head) {
92
- try {
93
- const diffTarget = head ? `${base} ${head}` : base;
94
- const diff = (0, child_process_1.execSync)(`git diff ${diffTarget} -- "${file}"`, {
95
- cwd: workspaceRoot,
96
- encoding: 'utf-8',
97
- });
98
- if (!diff && !head) {
99
- const fullPath = path.join(workspaceRoot, file);
100
- if (fs.existsSync(fullPath)) {
101
- const isUntracked = (0, child_process_1.execSync)(`git ls-files --others --exclude-standard "${file}"`, {
102
- cwd: workspaceRoot,
103
- encoding: 'utf-8',
104
- }).trim();
105
- if (isUntracked) {
106
- const content = fs.readFileSync(fullPath, 'utf-8');
107
- const lines = content.split('\n');
108
- return lines.map((line) => `+${line}`).join('\n');
109
- }
110
- }
111
- }
112
- return diff;
113
- }
114
- catch {
115
- return '';
116
- }
117
- }
118
- /**
119
- * Parse diff to extract changed line numbers (additions only - lines starting with +).
120
- */
121
- function getChangedLineNumbers(diffContent) {
122
- const changedLines = new Set();
123
- const lines = diffContent.split('\n');
124
- let currentLine = 0;
125
- for (const line of lines) {
126
- const hunkMatch = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
127
- if (hunkMatch) {
128
- currentLine = parseInt(hunkMatch[1], 10);
129
- continue;
130
- }
131
- if (line.startsWith('+') && !line.startsWith('+++')) {
132
- changedLines.add(currentLine);
133
- currentLine++;
134
- }
135
- else if (line.startsWith('-') && !line.startsWith('---')) {
136
- // Deletions don't increment line number
137
- }
138
- else {
139
- currentLine++;
140
- }
141
- }
142
- return changedLines;
143
- }
144
- /**
145
- * Check if a line contains a webpieces-disable comment for no-destructure.
146
- */
147
- function hasDisableComment(lines, lineNumber) {
148
- const startCheck = Math.max(0, lineNumber - 5);
149
- for (let i = lineNumber - 2; i >= startCheck; i--) {
150
- const line = lines[i]?.trim() ?? '';
151
- if (line.startsWith('function ') || line.startsWith('class ') || line.endsWith('}')) {
152
- break;
153
- }
154
- if (line.includes('webpieces-disable') && line.includes('no-destructure')) {
155
- return true;
156
- }
157
- }
158
- return false;
159
- }
160
- /**
161
- * Check if an ArrayBindingPattern's initializer is `await Promise.all(...)`.
162
- */
163
- function isPromiseAllDestructure(node) {
164
- const parent = node.parent;
165
- if (!ts.isVariableDeclaration(parent))
166
- return false;
167
- const initializer = parent.initializer;
168
- if (!initializer)
169
- return false;
170
- // Handle: const [a, b] = await Promise.all([...])
171
- if (ts.isAwaitExpression(initializer)) {
172
- const awaitedExpr = initializer.expression;
173
- if (ts.isCallExpression(awaitedExpr)) {
174
- const callExpr = awaitedExpr.expression;
175
- // Promise.all(...)
176
- if (ts.isPropertyAccessExpression(callExpr) && callExpr.name.text === 'all') {
177
- const obj = callExpr.expression;
178
- if (ts.isIdentifier(obj) && obj.text === 'Promise') {
179
- return true;
180
- }
181
- }
182
- }
183
- }
184
- return false;
185
- }
186
- /**
187
- * Check if an ArrayBindingPattern in a for-of loop iterates over Object.entries(...).
188
- */
189
- function isObjectEntriesForOf(node) {
190
- // Walk up: ArrayBindingPattern -> VariableDeclaration -> VariableDeclarationList -> ForOfStatement
191
- const varDecl = node.parent;
192
- if (!ts.isVariableDeclaration(varDecl))
193
- return false;
194
- const varDeclList = varDecl.parent;
195
- if (!ts.isVariableDeclarationList(varDeclList))
196
- return false;
197
- const forOfStmt = varDeclList.parent;
198
- if (!ts.isForOfStatement(forOfStmt))
199
- return false;
200
- // Check iterable expression ends with .entries()
201
- const iterable = forOfStmt.expression;
202
- if (ts.isCallExpression(iterable)) {
203
- const callExpr = iterable.expression;
204
- if (ts.isPropertyAccessExpression(callExpr) && callExpr.name.text === 'entries') {
205
- return true;
206
- }
207
- }
208
- return false;
209
- }
210
- /**
211
- * Check if an ObjectBindingPattern contains a rest element (...rest).
212
- */
213
- function hasRestElement(node) {
214
- for (const element of node.elements) {
215
- if (element.dotDotDotToken) {
216
- return true;
217
- }
218
- }
219
- return false;
220
- }
221
- /**
222
- * Find all destructuring patterns in a file using AST.
223
- */
224
- // webpieces-disable max-lines-new-methods -- AST traversal with multiple destructuring pattern checks and exception detection
225
- function findDestructuringInFile(filePath, workspaceRoot, disableAllowed) {
226
- const fullPath = path.join(workspaceRoot, filePath);
227
- if (!fs.existsSync(fullPath))
228
- return [];
229
- const content = fs.readFileSync(fullPath, 'utf-8');
230
- const fileLines = content.split('\n');
231
- const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
232
- const violations = [];
233
- // webpieces-disable max-lines-new-methods -- AST visitor needs to handle object/array binding patterns in declarations, for-of, and parameters
234
- function visit(node) {
235
- try {
236
- // Check ObjectBindingPattern
237
- if (ts.isObjectBindingPattern(node)) {
238
- // Exception: rest operator separation
239
- if (hasRestElement(node)) {
240
- ts.forEachChild(node, visit);
241
- return;
242
- }
243
- const context = getDestructureContext(node);
244
- recordViolation(node, context, fileLines, sourceFile, violations, disableAllowed);
245
- }
246
- // Check ArrayBindingPattern
247
- if (ts.isArrayBindingPattern(node)) {
248
- // Exception: Promise.all destructure
249
- if (isPromiseAllDestructure(node)) {
250
- ts.forEachChild(node, visit);
251
- return;
252
- }
253
- // Exception: Object.entries in for-of
254
- if (isObjectEntriesForOf(node)) {
255
- ts.forEachChild(node, visit);
256
- return;
257
- }
258
- const context = getDestructureContext(node);
259
- recordViolation(node, context, fileLines, sourceFile, violations, disableAllowed);
260
- }
261
- }
262
- catch {
263
- // Skip nodes that cause errors during analysis
264
- }
265
- ts.forEachChild(node, visit);
266
- }
267
- visit(sourceFile);
268
- return violations;
269
- }
270
- function recordViolation(node, context, fileLines, sourceFile, violations, disableAllowed) {
271
- const startPos = node.getStart(sourceFile);
272
- if (startPos >= 0) {
273
- const pos = sourceFile.getLineAndCharacterOfPosition(startPos);
274
- const line = pos.line + 1;
275
- const column = pos.character + 1;
276
- const disabled = hasDisableComment(fileLines, line);
277
- if (!disableAllowed && disabled) {
278
- // When disableAllowed is false, ignore disable comments — still a violation
279
- violations.push({ line, column, context, hasDisableComment: false });
280
- }
281
- else {
282
- violations.push({ line, column, context, hasDisableComment: disabled });
283
- }
284
- }
285
- }
286
- /**
287
- * Get a description of where the destructuring pattern appears.
288
- */
289
- function getDestructureContext(node) {
290
- const parent = node.parent;
291
- if (ts.isParameter(parent)) {
292
- return 'function parameter destructuring';
293
- }
294
- if (ts.isVariableDeclaration(parent)) {
295
- const grandparent = parent.parent;
296
- if (grandparent && ts.isVariableDeclarationList(grandparent)) {
297
- const forOfParent = grandparent.parent;
298
- if (forOfParent && ts.isForOfStatement(forOfParent)) {
299
- return ts.isObjectBindingPattern(node)
300
- ? 'object destructuring in for-of loop'
301
- : 'array destructuring in for-of loop';
302
- }
303
- }
304
- return ts.isObjectBindingPattern(node)
305
- ? 'object destructuring in variable declaration'
306
- : 'array destructuring in variable declaration';
307
- }
308
- return ts.isObjectBindingPattern(node)
309
- ? 'object destructuring'
310
- : 'array destructuring';
311
- }
312
- /**
313
- * MODIFIED_CODE mode: Flag violations on changed lines in diff hunks.
314
- */
315
- // webpieces-disable max-lines-new-methods -- File iteration with diff parsing and line filtering
316
- function findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed) {
317
- const violations = [];
318
- for (const file of changedFiles) {
319
- const diff = getFileDiff(workspaceRoot, file, base, head);
320
- const changedLines = getChangedLineNumbers(diff);
321
- if (changedLines.size === 0)
322
- continue;
323
- const allViolations = findDestructuringInFile(file, workspaceRoot, disableAllowed);
324
- for (const v of allViolations) {
325
- if (disableAllowed && v.hasDisableComment)
326
- continue;
327
- // LINE-BASED: Only include if the violation is on a changed line
328
- if (!changedLines.has(v.line))
329
- continue;
330
- violations.push({
331
- file,
332
- line: v.line,
333
- column: v.column,
334
- context: v.context,
335
- });
336
- }
337
- }
338
- return violations;
339
- }
340
- /**
341
- * MODIFIED_FILES mode: Flag ALL violations in files that were modified.
342
- */
343
- function findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed) {
344
- const violations = [];
345
- for (const file of changedFiles) {
346
- const allViolations = findDestructuringInFile(file, workspaceRoot, disableAllowed);
347
- for (const v of allViolations) {
348
- if (disableAllowed && v.hasDisableComment)
349
- continue;
350
- violations.push({
351
- file,
352
- line: v.line,
353
- column: v.column,
354
- context: v.context,
355
- });
356
- }
357
- }
358
- return violations;
359
- }
360
- /**
361
- * Auto-detect the base branch by finding the merge-base with origin/main.
362
- */
363
- function detectBase(workspaceRoot) {
364
- try {
365
- const mergeBase = (0, child_process_1.execSync)('git merge-base HEAD origin/main', {
366
- cwd: workspaceRoot,
367
- encoding: 'utf-8',
368
- stdio: ['pipe', 'pipe', 'pipe'],
369
- }).trim();
370
- if (mergeBase) {
371
- return mergeBase;
372
- }
373
- }
374
- catch {
375
- try {
376
- const mergeBase = (0, child_process_1.execSync)('git merge-base HEAD main', {
377
- cwd: workspaceRoot,
378
- encoding: 'utf-8',
379
- stdio: ['pipe', 'pipe', 'pipe'],
380
- }).trim();
381
- if (mergeBase) {
382
- return mergeBase;
383
- }
384
- }
385
- catch {
386
- // Ignore
387
- }
388
- }
389
- return null;
390
- }
391
- /**
392
- * Report violations to console.
393
- */
394
- // webpieces-disable max-lines-new-methods -- Console output with examples and escape hatch information
395
- function reportViolations(violations, mode, disableAllowed) {
396
- console.error('');
397
- console.error('\u274c Destructuring patterns found! Use explicit property access instead.');
398
- console.error('');
399
- console.error('\ud83d\udcda Avoiding destructuring improves code traceability:');
400
- console.error('');
401
- console.error(' BAD: const { name, age } = user;');
402
- console.error(' GOOD: const name = user.name;');
403
- console.error(' const age = user.age;');
404
- console.error('');
405
- console.error(' BAD: function process({ x, y }: Point) { }');
406
- console.error(' GOOD: function process(point: Point) { point.x; point.y; }');
407
- console.error('');
408
- for (const v of violations) {
409
- console.error(` \u274c ${v.file}:${v.line}:${v.column}`);
410
- console.error(` ${v.context}`);
411
- }
412
- console.error('');
413
- console.error(' Allowed exceptions:');
414
- console.error(' - const [a, b] = await Promise.all([...])');
415
- console.error(' - for (const [key, value] of Object.entries(obj))');
416
- console.error(' - const { extracted, ...rest } = obj (rest operator separation)');
417
- console.error('');
418
- if (disableAllowed) {
419
- console.error(' Escape hatch (use sparingly):');
420
- console.error(' // webpieces-disable no-destructure -- [your reason]');
421
- }
422
- else {
423
- console.error(' Escape hatch: DISABLED (disableAllowed: false)');
424
- console.error(' Disable comments are ignored. Fix the destructuring directly.');
425
- }
426
- console.error('');
427
- console.error(` Current mode: ${mode}`);
428
- console.error('');
429
- }
430
- /**
431
- * Resolve mode considering ignoreModifiedUntilEpoch override.
432
- * When active, downgrades to OFF. When expired, logs a warning.
433
- */
434
- function resolveNoDestructureMode(normalMode, epoch) {
435
- if (epoch === undefined || normalMode === 'OFF') {
436
- return normalMode;
437
- }
438
- const nowSeconds = Date.now() / 1000;
439
- if (nowSeconds < epoch) {
440
- const expiresDate = new Date(epoch * 1000).toISOString().split('T')[0];
441
- console.log(`\n\u23ed\ufe0f Skipping no-destructure validation (ignoreModifiedUntilEpoch active, expires: ${expiresDate})`);
442
- console.log('');
443
- return 'OFF';
444
- }
445
- return normalMode;
446
- }
447
- async function runExecutor(options, context) {
448
- const workspaceRoot = context.root;
449
- const mode = resolveNoDestructureMode(options.mode ?? 'OFF', options.ignoreModifiedUntilEpoch);
450
- const disableAllowed = options.disableAllowed ?? true;
451
- if (mode === 'OFF') {
452
- console.log('\n\u23ed\ufe0f Skipping no-destructure validation (mode: OFF)');
453
- console.log('');
454
- return { success: true };
455
- }
456
- console.log('\n\ud83d\udccf Validating No Destructuring\n');
457
- console.log(` Mode: ${mode}`);
458
- let base = process.env['NX_BASE'];
459
- const head = process.env['NX_HEAD'];
460
- if (!base) {
461
- base = detectBase(workspaceRoot) ?? undefined;
462
- if (!base) {
463
- console.log('\n\u23ed\ufe0f Skipping no-destructure validation (could not detect base branch)');
464
- console.log('');
465
- return { success: true };
466
- }
467
- }
468
- console.log(` Base: ${base}`);
469
- console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);
470
- console.log('');
471
- const changedFiles = getChangedTypeScriptFiles(workspaceRoot, base, head);
472
- if (changedFiles.length === 0) {
473
- console.log('\u2705 No TypeScript files changed');
474
- return { success: true };
475
- }
476
- console.log(`\ud83d\udcc2 Checking ${changedFiles.length} changed file(s)...`);
477
- let violations = [];
478
- if (mode === 'MODIFIED_CODE') {
479
- violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);
480
- }
481
- else if (mode === 'MODIFIED_FILES') {
482
- violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);
483
- }
484
- if (violations.length === 0) {
485
- console.log('\u2705 No destructuring patterns found');
486
- return { success: true };
487
- }
488
- reportViolations(violations, mode, disableAllowed);
489
- return { success: false };
490
- }
491
- //# sourceMappingURL=executor.js.map