@webpieces/dev-config 0.2.38 → 0.2.40
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.
- package/architecture/executors/validate-architecture-unchanged/executor.js +166 -2
- package/architecture/executors/validate-architecture-unchanged/executor.js.map +1 -1
- package/architecture/executors/validate-architecture-unchanged/executor.ts +172 -2
- package/architecture/executors/validate-new-methods/executor.d.ts +22 -0
- package/architecture/executors/validate-new-methods/executor.js +351 -0
- package/architecture/executors/validate-new-methods/executor.js.map +1 -0
- package/architecture/executors/validate-new-methods/executor.ts +408 -0
- package/architecture/executors/validate-new-methods/schema.json +14 -0
- package/eslint-plugin/rules/enforce-architecture.js +12 -3
- package/eslint-plugin/rules/enforce-architecture.js.map +1 -1
- package/eslint-plugin/rules/enforce-architecture.ts +12 -3
- package/executors.json +5 -0
- package/package.json +1 -1
- package/plugin.js +43 -0
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Validate New Methods Executor
|
|
3
|
+
*
|
|
4
|
+
* Validates that newly added methods don't exceed a maximum line count.
|
|
5
|
+
* Only runs when NX_BASE environment variable is set (affected mode).
|
|
6
|
+
*
|
|
7
|
+
* This validator encourages writing methods that read like a "table of contents"
|
|
8
|
+
* where each method call describes a larger piece of work.
|
|
9
|
+
*
|
|
10
|
+
* Usage:
|
|
11
|
+
* nx affected --target=validate-new-methods --base=origin/main
|
|
12
|
+
*
|
|
13
|
+
* Escape hatch: Add eslint-disable comment with justification
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import type { ExecutorContext } from '@nx/devkit';
|
|
17
|
+
import { execSync } from 'child_process';
|
|
18
|
+
import * as fs from 'fs';
|
|
19
|
+
import * as path from 'path';
|
|
20
|
+
import * as ts from 'typescript';
|
|
21
|
+
|
|
22
|
+
export interface ValidateNewMethodsOptions {
|
|
23
|
+
max?: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface ExecutorResult {
|
|
27
|
+
success: boolean;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface MethodViolation {
|
|
31
|
+
file: string;
|
|
32
|
+
methodName: string;
|
|
33
|
+
line: number;
|
|
34
|
+
lines: number;
|
|
35
|
+
isNew: boolean;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const TMP_DIR = 'tmp/webpieces';
|
|
39
|
+
const TMP_MD_FILE = 'webpieces.methodsize.md';
|
|
40
|
+
|
|
41
|
+
const METHODSIZE_DOC_CONTENT = `# Instructions: New Method Too Long
|
|
42
|
+
|
|
43
|
+
## The "Table of Contents" Principle
|
|
44
|
+
|
|
45
|
+
Good code reads like a book's table of contents:
|
|
46
|
+
- Chapter titles (method names) tell you WHAT happens
|
|
47
|
+
- Reading chapter titles gives you the full story
|
|
48
|
+
- You can dive into chapters (implementations) for details
|
|
49
|
+
|
|
50
|
+
## Why Limit New Methods to 20-30 Lines?
|
|
51
|
+
|
|
52
|
+
Methods under 20-30 lines are:
|
|
53
|
+
- Easy to review in a single screen
|
|
54
|
+
- Simple to understand without scrolling
|
|
55
|
+
- Quick for AI to analyze and suggest improvements
|
|
56
|
+
- More testable in isolation
|
|
57
|
+
- Self-documenting through well-named extracted methods
|
|
58
|
+
|
|
59
|
+
**~50% of the time**, you can stay under 20-30 lines in new code by extracting
|
|
60
|
+
logical units into well-named methods. This makes code more readable for both
|
|
61
|
+
AI and humans.
|
|
62
|
+
|
|
63
|
+
## How to Refactor
|
|
64
|
+
|
|
65
|
+
Instead of:
|
|
66
|
+
\`\`\`typescript
|
|
67
|
+
async processOrder(order: Order): Promise<Result> {
|
|
68
|
+
// 50 lines of validation, transformation, saving, notifications...
|
|
69
|
+
}
|
|
70
|
+
\`\`\`
|
|
71
|
+
|
|
72
|
+
Write:
|
|
73
|
+
\`\`\`typescript
|
|
74
|
+
async processOrder(order: Order): Promise<Result> {
|
|
75
|
+
const validated = this.validateOrder(order);
|
|
76
|
+
const transformed = this.applyBusinessRules(validated);
|
|
77
|
+
const saved = await this.saveToDatabase(transformed);
|
|
78
|
+
await this.notifyStakeholders(saved);
|
|
79
|
+
return this.buildResult(saved);
|
|
80
|
+
}
|
|
81
|
+
\`\`\`
|
|
82
|
+
|
|
83
|
+
Now the main method is a "table of contents" - each line tells part of the story!
|
|
84
|
+
|
|
85
|
+
## Patterns for Extraction
|
|
86
|
+
|
|
87
|
+
### Pattern 1: Extract Loop Bodies
|
|
88
|
+
\`\`\`typescript
|
|
89
|
+
// BEFORE
|
|
90
|
+
for (const item of items) {
|
|
91
|
+
// 20 lines of processing
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// AFTER
|
|
95
|
+
for (const item of items) {
|
|
96
|
+
this.processItem(item);
|
|
97
|
+
}
|
|
98
|
+
\`\`\`
|
|
99
|
+
|
|
100
|
+
### Pattern 2: Extract Conditional Blocks
|
|
101
|
+
\`\`\`typescript
|
|
102
|
+
// BEFORE
|
|
103
|
+
if (isAdmin(user)) {
|
|
104
|
+
// 15 lines of admin logic
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// AFTER
|
|
108
|
+
if (isAdmin(user)) {
|
|
109
|
+
this.handleAdminUser(user);
|
|
110
|
+
}
|
|
111
|
+
\`\`\`
|
|
112
|
+
|
|
113
|
+
### Pattern 3: Extract Data Transformations
|
|
114
|
+
\`\`\`typescript
|
|
115
|
+
// BEFORE
|
|
116
|
+
const result = {
|
|
117
|
+
// 10+ lines of object construction
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
// AFTER
|
|
121
|
+
const result = this.buildResultObject(data);
|
|
122
|
+
\`\`\`
|
|
123
|
+
|
|
124
|
+
## If Refactoring Is Not Feasible
|
|
125
|
+
|
|
126
|
+
Sometimes methods genuinely need to be longer (complex algorithms, state machines, etc.).
|
|
127
|
+
|
|
128
|
+
**Escape hatch**: Add an eslint-disable comment with justification:
|
|
129
|
+
|
|
130
|
+
\`\`\`typescript
|
|
131
|
+
// eslint-disable-next-line @webpieces/max-method-lines -- Complex state machine, splitting reduces clarity
|
|
132
|
+
async complexStateMachine(): Promise<void> {
|
|
133
|
+
// ... longer method with justification
|
|
134
|
+
}
|
|
135
|
+
\`\`\`
|
|
136
|
+
|
|
137
|
+
## AI Agent Action Steps
|
|
138
|
+
|
|
139
|
+
1. **READ** the method to understand its logical sections
|
|
140
|
+
2. **IDENTIFY** logical units that can be extracted
|
|
141
|
+
3. **EXTRACT** into well-named private methods
|
|
142
|
+
4. **VERIFY** the main method now reads like a table of contents
|
|
143
|
+
5. **IF NOT FEASIBLE**: Add eslint-disable with clear justification
|
|
144
|
+
|
|
145
|
+
## Remember
|
|
146
|
+
|
|
147
|
+
- Every method you write today will be read many times tomorrow
|
|
148
|
+
- The best code explains itself through structure
|
|
149
|
+
- When in doubt, extract and name it
|
|
150
|
+
`;
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Write the instructions documentation to tmp directory
|
|
154
|
+
*/
|
|
155
|
+
function writeTmpInstructions(workspaceRoot: string): string {
|
|
156
|
+
const tmpDir = path.join(workspaceRoot, TMP_DIR);
|
|
157
|
+
const mdPath = path.join(tmpDir, TMP_MD_FILE);
|
|
158
|
+
|
|
159
|
+
fs.mkdirSync(tmpDir, { recursive: true });
|
|
160
|
+
fs.writeFileSync(mdPath, METHODSIZE_DOC_CONTENT);
|
|
161
|
+
|
|
162
|
+
return mdPath;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Get changed TypeScript files between base and head
|
|
167
|
+
*/
|
|
168
|
+
function getChangedTypeScriptFiles(workspaceRoot: string, base: string, head: string): string[] {
|
|
169
|
+
try {
|
|
170
|
+
const output = execSync(`git diff --name-only ${base}...${head} -- '*.ts' '*.tsx'`, {
|
|
171
|
+
cwd: workspaceRoot,
|
|
172
|
+
encoding: 'utf-8',
|
|
173
|
+
});
|
|
174
|
+
return output
|
|
175
|
+
.trim()
|
|
176
|
+
.split('\n')
|
|
177
|
+
.filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
|
|
178
|
+
} catch {
|
|
179
|
+
return [];
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Get the diff content for a specific file
|
|
185
|
+
*/
|
|
186
|
+
function getFileDiff(workspaceRoot: string, file: string, base: string, head: string): string {
|
|
187
|
+
try {
|
|
188
|
+
return execSync(`git diff ${base}...${head} -- "${file}"`, {
|
|
189
|
+
cwd: workspaceRoot,
|
|
190
|
+
encoding: 'utf-8',
|
|
191
|
+
});
|
|
192
|
+
} catch {
|
|
193
|
+
return '';
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Parse diff to find newly added method signatures
|
|
199
|
+
*/
|
|
200
|
+
function findNewMethodSignaturesInDiff(diffContent: string): Set<string> {
|
|
201
|
+
const newMethods = new Set<string>();
|
|
202
|
+
const lines = diffContent.split('\n');
|
|
203
|
+
|
|
204
|
+
// Patterns to match method definitions
|
|
205
|
+
const patterns = [
|
|
206
|
+
// async methodName( or methodName(
|
|
207
|
+
/^\+\s*(async\s+)?(\w+)\s*\(/,
|
|
208
|
+
// function methodName(
|
|
209
|
+
/^\+\s*(async\s+)?function\s+(\w+)\s*\(/,
|
|
210
|
+
// const/let methodName = (async)? (
|
|
211
|
+
/^\+\s*(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/,
|
|
212
|
+
// const/let methodName = (async)? function
|
|
213
|
+
/^\+\s*(?:const|let)\s+(\w+)\s*=\s*(?:async\s+)?function/,
|
|
214
|
+
];
|
|
215
|
+
|
|
216
|
+
for (const line of lines) {
|
|
217
|
+
if (line.startsWith('+') && !line.startsWith('+++')) {
|
|
218
|
+
for (const pattern of patterns) {
|
|
219
|
+
const match = line.match(pattern);
|
|
220
|
+
if (match) {
|
|
221
|
+
// Extract method name from different capture groups
|
|
222
|
+
const methodName = match[2] || match[1];
|
|
223
|
+
if (methodName && !['if', 'for', 'while', 'switch', 'catch', 'constructor'].includes(methodName)) {
|
|
224
|
+
newMethods.add(methodName);
|
|
225
|
+
}
|
|
226
|
+
break;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
return newMethods;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Parse a TypeScript file and find methods with their line counts
|
|
237
|
+
*/
|
|
238
|
+
function findMethodsInFile(
|
|
239
|
+
filePath: string,
|
|
240
|
+
workspaceRoot: string
|
|
241
|
+
): Array<{ name: string; line: number; lines: number }> {
|
|
242
|
+
const fullPath = path.join(workspaceRoot, filePath);
|
|
243
|
+
if (!fs.existsSync(fullPath)) return [];
|
|
244
|
+
|
|
245
|
+
const content = fs.readFileSync(fullPath, 'utf-8');
|
|
246
|
+
const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
|
|
247
|
+
|
|
248
|
+
const methods: Array<{ name: string; line: number; lines: number }> = [];
|
|
249
|
+
|
|
250
|
+
function visit(node: ts.Node): void {
|
|
251
|
+
let methodName: string | undefined;
|
|
252
|
+
let startLine: number | undefined;
|
|
253
|
+
let endLine: number | undefined;
|
|
254
|
+
|
|
255
|
+
if (ts.isMethodDeclaration(node) && node.name) {
|
|
256
|
+
methodName = node.name.getText(sourceFile);
|
|
257
|
+
const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
258
|
+
const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
|
|
259
|
+
startLine = start.line + 1;
|
|
260
|
+
endLine = end.line + 1;
|
|
261
|
+
} else if (ts.isFunctionDeclaration(node) && node.name) {
|
|
262
|
+
methodName = node.name.getText(sourceFile);
|
|
263
|
+
const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
264
|
+
const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
|
|
265
|
+
startLine = start.line + 1;
|
|
266
|
+
endLine = end.line + 1;
|
|
267
|
+
} else if (ts.isArrowFunction(node)) {
|
|
268
|
+
// Check if it's assigned to a variable
|
|
269
|
+
if (ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name)) {
|
|
270
|
+
methodName = node.parent.name.getText(sourceFile);
|
|
271
|
+
const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
272
|
+
const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
|
|
273
|
+
startLine = start.line + 1;
|
|
274
|
+
endLine = end.line + 1;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
if (methodName && startLine !== undefined && endLine !== undefined) {
|
|
279
|
+
methods.push({
|
|
280
|
+
name: methodName,
|
|
281
|
+
line: startLine,
|
|
282
|
+
lines: endLine - startLine + 1,
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
ts.forEachChild(node, visit);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
visit(sourceFile);
|
|
290
|
+
return methods;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Find new methods that exceed the line limit
|
|
295
|
+
*/
|
|
296
|
+
function findViolations(
|
|
297
|
+
workspaceRoot: string,
|
|
298
|
+
changedFiles: string[],
|
|
299
|
+
base: string,
|
|
300
|
+
head: string,
|
|
301
|
+
maxLines: number
|
|
302
|
+
): MethodViolation[] {
|
|
303
|
+
const violations: MethodViolation[] = [];
|
|
304
|
+
|
|
305
|
+
for (const file of changedFiles) {
|
|
306
|
+
// Get the diff to find which methods are NEW (not just modified)
|
|
307
|
+
const diff = getFileDiff(workspaceRoot, file, base, head);
|
|
308
|
+
const newMethodNames = findNewMethodSignaturesInDiff(diff);
|
|
309
|
+
|
|
310
|
+
if (newMethodNames.size === 0) continue;
|
|
311
|
+
|
|
312
|
+
// Parse the current file to get method line counts
|
|
313
|
+
const methods = findMethodsInFile(file, workspaceRoot);
|
|
314
|
+
|
|
315
|
+
for (const method of methods) {
|
|
316
|
+
// Only check NEW methods
|
|
317
|
+
if (newMethodNames.has(method.name) && method.lines > maxLines) {
|
|
318
|
+
violations.push({
|
|
319
|
+
file,
|
|
320
|
+
methodName: method.name,
|
|
321
|
+
line: method.line,
|
|
322
|
+
lines: method.lines,
|
|
323
|
+
isNew: true,
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
return violations;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
export default async function runExecutor(
|
|
333
|
+
options: ValidateNewMethodsOptions,
|
|
334
|
+
context: ExecutorContext
|
|
335
|
+
): Promise<ExecutorResult> {
|
|
336
|
+
const workspaceRoot = context.root;
|
|
337
|
+
const maxLines = options.max ?? 30;
|
|
338
|
+
|
|
339
|
+
// Check if running in affected mode
|
|
340
|
+
const base = process.env['NX_BASE'];
|
|
341
|
+
const head = process.env['NX_HEAD'] || 'HEAD';
|
|
342
|
+
|
|
343
|
+
if (!base) {
|
|
344
|
+
console.log('\n⏭️ Skipping new method validation (not in affected mode)');
|
|
345
|
+
console.log(' To run: nx affected --target=validate-new-methods --base=origin/main');
|
|
346
|
+
console.log('');
|
|
347
|
+
return { success: true };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
console.log('\n📏 Validating New Method Sizes\n');
|
|
351
|
+
console.log(` Base: ${base}`);
|
|
352
|
+
console.log(` Head: ${head}`);
|
|
353
|
+
console.log(` Max lines for new methods: ${maxLines}`);
|
|
354
|
+
console.log('');
|
|
355
|
+
|
|
356
|
+
try {
|
|
357
|
+
// Get changed TypeScript files
|
|
358
|
+
const changedFiles = getChangedTypeScriptFiles(workspaceRoot, base, head);
|
|
359
|
+
|
|
360
|
+
if (changedFiles.length === 0) {
|
|
361
|
+
console.log('✅ No TypeScript files changed');
|
|
362
|
+
return { success: true };
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);
|
|
366
|
+
|
|
367
|
+
// Find violations
|
|
368
|
+
const violations = findViolations(workspaceRoot, changedFiles, base, head, maxLines);
|
|
369
|
+
|
|
370
|
+
if (violations.length === 0) {
|
|
371
|
+
console.log('✅ All new methods are under ' + maxLines + ' lines');
|
|
372
|
+
return { success: true };
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// Write instructions file
|
|
376
|
+
const mdPath = writeTmpInstructions(workspaceRoot);
|
|
377
|
+
|
|
378
|
+
// Report violations
|
|
379
|
+
console.error('');
|
|
380
|
+
console.error('❌ New methods exceed ' + maxLines + ' lines!');
|
|
381
|
+
console.error('');
|
|
382
|
+
console.error('📚 Methods should read like a "table of contents" - each method call');
|
|
383
|
+
console.error(' describes a larger piece of work. ~50% of the time, you can refactor');
|
|
384
|
+
console.error(' to stay under ' + maxLines + ' lines. If not feasible, use the escape hatch.');
|
|
385
|
+
console.error('');
|
|
386
|
+
|
|
387
|
+
for (const v of violations) {
|
|
388
|
+
console.error(` ❌ ${v.file}:${v.line}`);
|
|
389
|
+
console.error(` Method: ${v.methodName} (${v.lines} lines, max: ${maxLines})`);
|
|
390
|
+
console.error(` READ ${mdPath} to fix this error properly`);
|
|
391
|
+
console.error('');
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
console.error('💡 To fix:');
|
|
395
|
+
console.error(' 1. Refactor the method to read like a table of contents (preferred)');
|
|
396
|
+
console.error(' 2. OR add eslint-disable comment with justification:');
|
|
397
|
+
console.error(' // eslint-disable-next-line @webpieces/max-method-lines -- [reason]');
|
|
398
|
+
console.error('');
|
|
399
|
+
console.error(`⚠️ *** READ ${mdPath} for detailed guidance *** ⚠️`);
|
|
400
|
+
console.error('');
|
|
401
|
+
|
|
402
|
+
return { success: false };
|
|
403
|
+
} catch (err: unknown) {
|
|
404
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
405
|
+
console.error('❌ New method validation failed:', error.message);
|
|
406
|
+
return { success: false };
|
|
407
|
+
}
|
|
408
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "http://json-schema.org/schema",
|
|
3
|
+
"title": "Validate New Methods Executor",
|
|
4
|
+
"description": "Validates that newly added methods don't exceed a maximum line count. Only runs in affected mode (when NX_BASE is set).",
|
|
5
|
+
"type": "object",
|
|
6
|
+
"properties": {
|
|
7
|
+
"max": {
|
|
8
|
+
"type": "number",
|
|
9
|
+
"description": "Maximum number of lines allowed for new methods",
|
|
10
|
+
"default": 30
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"required": []
|
|
14
|
+
}
|
|
@@ -14,7 +14,16 @@
|
|
|
14
14
|
const tslib_1 = require("tslib");
|
|
15
15
|
const fs = tslib_1.__importStar(require("fs"));
|
|
16
16
|
const path = tslib_1.__importStar(require("path"));
|
|
17
|
-
const DEPENDENCIES_DOC_CONTENT = `#
|
|
17
|
+
const DEPENDENCIES_DOC_CONTENT = `# Instructions: Architecture Dependency Violation
|
|
18
|
+
|
|
19
|
+
IN GENERAL, it is better to avoid these changes and find a different way by moving classes
|
|
20
|
+
around to existing packages you already depend on. It is not always avoidable though.
|
|
21
|
+
A clean dependency graph keeps you out of huge trouble later.
|
|
22
|
+
|
|
23
|
+
If you are a human, simply run these commands:
|
|
24
|
+
* nx run architecture:visualize - to see the new dependencies and validate that change is desired
|
|
25
|
+
* nx run architecture:generate - updates the dep graph
|
|
26
|
+
* git diff architecture/dependencies.json - to see the deps changes you made
|
|
18
27
|
|
|
19
28
|
**READ THIS FILE FIRST before making any changes!**
|
|
20
29
|
|
|
@@ -101,7 +110,7 @@ Only after receiving explicit human approval in Step 3, make these changes:
|
|
|
101
110
|
### Step 5: Update Architecture Definition
|
|
102
111
|
Run this command to validate and update the architecture:
|
|
103
112
|
\`\`\`bash
|
|
104
|
-
npx nx run architecture:
|
|
113
|
+
npx nx run architecture:generate
|
|
105
114
|
\`\`\`
|
|
106
115
|
|
|
107
116
|
This will:
|
|
@@ -111,7 +120,7 @@ This will:
|
|
|
111
120
|
|
|
112
121
|
### Step 6: Verify No Cycles
|
|
113
122
|
\`\`\`bash
|
|
114
|
-
npx nx run architecture:validate
|
|
123
|
+
npx nx run architecture:validate-no-cycles
|
|
115
124
|
\`\`\`
|
|
116
125
|
|
|
117
126
|
If cycles are detected, you MUST refactor to break the cycle. Common strategies:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enforce-architecture.js","sourceRoot":"","sources":["../../../../../../packages/tooling/dev-config/eslint-plugin/rules/enforce-architecture.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;GAWG;;AAGH,+CAAyB;AACzB,mDAA6B;AAE7B,MAAM,wBAAwB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+HhC,CAAC;AAEF,uDAAuD;AACvD,IAAI,sBAAsB,GAAG,KAAK,CAAC;AAEnC;;GAEG;AACH,SAAS,aAAa,CAAC,OAAe,EAAE,OAAe;IACnD,IAAI,CAAC;QACD,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACzD,EAAE,CAAC,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QAC5C,OAAO,IAAI,CAAC;IAChB,CAAC;IAAC,OAAO,GAAQ,EAAE,CAAC;QAChB,KAAK,GAAG,CAAC;QACT,OAAO,CAAC,IAAI,CAAC,0CAA0C,OAAO,EAAE,CAAC,CAAC;QAClE,OAAO,KAAK,CAAC;IACjB,CAAC;AACL,CAAC;AAED;;;GAGG;AACH,SAAS,qBAAqB,CAAC,aAAqB;IAChD,IAAI,sBAAsB;QAAE,OAAO;IACnC,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,KAAK,EAAE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wBACjB,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,OAAO,GAAG,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;4BAChD,yCAAyC;wBAC3C,CAAC,CAAC,yCAAyC,CAAC;oBAEpD,OAAO,CAAC,MAAM,CAAC;wBACX,IAAI,EAAE,IAAI,CAAC,MAAM;wBACjB,SAAS,EAAE,eAAe;wBAC1B,IAAI,EAAE;4BACF,QAAQ,EAAE,UAAU;4BACpB,OAAO,EAAE,aAAa;4BACtB,KAAK,EAAE,MAAM,CAAC,YAAY,CAAC,KAAK,CAAC;4BACjC,WAAW,EAAE,WAAW;yBAC3B;qBACJ,CAAC,CAAC;gBACP,CAAC;YACL,CAAC;SACJ,CAAC;IACN,CAAC;CACJ,CAAC;AAEF,iBAAS,IAAI,CAAC","sourcesContent":["/**\n * ESLint rule to enforce architecture boundaries\n *\n * Validates that imports from @webpieces/* packages comply with the\n * blessed dependency graph in .graphs/dependencies.json\n *\n * Supports transitive dependencies: if A depends on B and B depends on C,\n * then A can import from C.\n *\n * Configuration:\n * '@webpieces/enforce-architecture': 'error'\n */\n\nimport type { Rule } from 'eslint';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nconst DEPENDENCIES_DOC_CONTENT = `# AI Agent Instructions: Architecture Dependency Violation\n\n**READ THIS FILE FIRST before making any changes!**\n\n## ⚠️ CRITICAL WARNING ⚠️\n\n**This is a VERY IMPORTANT change that has LARGE REPERCUSSIONS later!**\n\nAdding new dependencies creates technical debt that compounds over time:\n- Creates coupling between packages that may be hard to undo\n- Can create circular dependency tangles\n- Makes packages harder to test in isolation\n- Increases build times and bundle sizes\n- May force unnecessary upgrades across the codebase\n\n**DO NOT add dependencies without senior developer approval!**\n\n## Understanding the Error\n\nYou've attempted to import from a package that is not in your project's allowed dependencies.\nThe architecture enforces a layered dependency structure where:\n- Level 0 packages are foundation packages with NO dependencies on other @webpieces packages\n- Higher level packages can only depend on lower level packages\n- All dependencies must be explicitly declared\n\n## Steps to Resolve\n\n### Step 1: Generate Current Dependency Graph\nRun this command to see the current architecture:\n\\`\\`\\`bash\nnpx nx run architecture:generate\n\\`\\`\\`\nThis creates/updates \\`architecture/dependencies.json\\` showing all packages and their levels.\n\n### Step 2: Analyze the Proposed Change\nAsk yourself:\n1. **Is this import truly necessary?** Can you refactor to avoid it?\n2. **Should the code move instead?** Maybe the code belongs in a different package.\n3. **Will this create a cycle?** Use \\`npx nx graph\\` to visualize dependencies.\n4. **Can you use an interface/abstraction?** Define interface in lower-level package, implement in higher-level.\n\n### Step 3: Get Senior Developer Approval\n\n## 🛑 AI AGENTS: STOP HERE AND ASK FOR HUMAN APPROVAL! 🛑\n\n**YOU MUST NOT PROCEED TO STEP 4 WITHOUT EXPLICIT HUMAN APPROVAL!**\n\n**REQUIRED**: Discuss this architectural change with a senior developer before proceeding.\n- Explain why the dependency is needed\n- Show you've considered alternatives (Step 2)\n- **WAIT for explicit approval before making ANY changes to project.json or package.json**\n\n**AI Agent Instructions:**\n1. Present your analysis from Step 2 to the human\n2. Explain which package needs which dependency and why\n3. ASK: \"Do you approve adding this dependency?\"\n4. **DO NOT modify project.json or package.json until you receive explicit \"yes\" or approval**\n\n### Step 4: If Approved, Add the Dependency\n\n## ⛔ NEVER MODIFY THESE FILES WITHOUT HUMAN APPROVAL FROM STEP 3! ⛔\n\nOnly after receiving explicit human approval in Step 3, make these changes:\n\n1. **Update project.json** - Add to \\`build.dependsOn\\`:\n \\`\\`\\`json\n {\n \"targets\": {\n \"build\": {\n \"dependsOn\": [\"^build\", \"dep1:build\", \"NEW_PACKAGE:build\"]\n }\n }\n }\n \\`\\`\\`\n\n2. **Update package.json** - Add to \\`dependencies\\`:\n \\`\\`\\`json\n {\n \"dependencies\": {\n \"@webpieces/NEW_PACKAGE\": \"*\"\n }\n }\n \\`\\`\\`\n\n### Step 5: Update Architecture Definition\nRun this command to validate and update the architecture:\n\\`\\`\\`bash\nnpx nx run architecture:validate --mode=update\n\\`\\`\\`\n\nThis will:\n- Detect any cycles (which MUST be fixed before proceeding)\n- Update \\`architecture/dependencies.json\\` with the new dependency\n- Recalculate package levels\n\n### Step 6: Verify No Cycles\n\\`\\`\\`bash\nnpx nx run architecture:validate\n\\`\\`\\`\n\nIf cycles are detected, you MUST refactor to break the cycle. Common strategies:\n- Move shared code to a lower-level package\n- Use dependency inversion (interfaces in low-level, implementations in high-level)\n- Restructure package boundaries\n\n## Alternative Solutions (Preferred over adding dependencies)\n\n### Option A: Move the Code\nIf you need functionality from another package, consider moving that code to a shared lower-level package.\n\n### Option B: Dependency Inversion\nDefine an interface in the lower-level package, implement it in the higher-level package:\n\\`\\`\\`typescript\n// In foundation package (level 0)\nexport interface Logger { log(msg: string): void; }\n\n// In higher-level package\nexport class ConsoleLogger implements Logger { ... }\n\\`\\`\\`\n\n### Option C: Pass Dependencies as Parameters\nInstead of importing, receive the dependency as a constructor or method parameter.\n\n## Remember\n- Every dependency you add today is technical debt for tomorrow\n- The best dependency is the one you don't need\n- When in doubt, refactor rather than add dependencies\n`;\n\n// Module-level flag to prevent redundant file creation\nlet dependenciesDocCreated = false;\n\n/**\n * Ensure a documentation file exists at the given path.\n */\nfunction ensureDocFile(docPath: string, content: string): boolean {\n try {\n fs.mkdirSync(path.dirname(docPath), { recursive: true });\n fs.writeFileSync(docPath, content, 'utf-8');\n return true;\n } catch (err: any) {\n void err;\n console.warn(`[webpieces] Could not create doc file: ${docPath}`);\n return false;\n }\n}\n\n/**\n * Ensure the dependencies documentation file exists.\n * Called when an architecture violation is detected.\n */\nfunction ensureDependenciesDoc(workspaceRoot: string): void {\n if (dependenciesDocCreated) return;\n const docPath = path.join(workspaceRoot, 'tmp', 'webpieces', 'webpieces.dependencies.md');\n if (ensureDocFile(docPath, DEPENDENCIES_DOC_CONTENT)) {\n dependenciesDocCreated = true;\n }\n}\n\n/**\n * Graph entry format from .graphs/dependencies.json\n */\ninterface GraphEntry {\n level: number;\n dependsOn: string[];\n}\n\ntype EnhancedGraph = Record<string, GraphEntry>;\n\n/**\n * Project mapping entry\n */\ninterface ProjectMapping {\n root: string;\n name: string;\n}\n\n// Cache for blessed graph (loaded once per lint run)\nlet cachedGraph: EnhancedGraph | null = null;\nlet cachedGraphPath: string | null = null;\n\n// Cache for project mappings\nlet cachedProjectMappings: ProjectMapping[] | null = null;\n\n/**\n * Find workspace root by walking up from file location\n */\nfunction findWorkspaceRoot(startPath: string): string {\n let currentDir = path.dirname(startPath);\n\n for (let i = 0; i < 20; i++) {\n const packagePath = path.join(currentDir, 'package.json');\n if (fs.existsSync(packagePath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(packagePath, 'utf-8'));\n if (pkg.workspaces || pkg.name === 'webpieces-ts') {\n return currentDir;\n }\n } catch (err: any) {\n //const error = toError(err);\n void err;\n }\n }\n\n const parent = path.dirname(currentDir);\n if (parent === currentDir) break;\n currentDir = parent;\n }\n\n return process.cwd();\n}\n\n/**\n * Load blessed graph from architecture/dependencies.json\n */\nfunction loadBlessedGraph(workspaceRoot: string): EnhancedGraph | null {\n const graphPath = path.join(workspaceRoot, 'architecture', 'dependencies.json');\n\n // Return cached if same path\n if (cachedGraphPath === graphPath && cachedGraph !== null) {\n return cachedGraph;\n }\n\n if (!fs.existsSync(graphPath)) {\n return null;\n }\n\n try {\n const content = fs.readFileSync(graphPath, 'utf-8');\n cachedGraph = JSON.parse(content) as EnhancedGraph;\n cachedGraphPath = graphPath;\n return cachedGraph;\n } catch (err: any) {\n //const error = toError(err);\n // err is used below\n console.error(`[ESLint @webpieces/enforce-architecture] Could not load graph: ${err}`);\n return null;\n }\n}\n\n/**\n * Build set of all workspace package names (from package.json files)\n * Used to detect workspace imports (works for any scope or unscoped)\n */\nfunction buildWorkspacePackageNames(workspaceRoot: string): Set<string> {\n const packageNames = new Set<string>();\n const mappings = buildProjectMappings(workspaceRoot);\n\n for (const mapping of mappings) {\n const pkgJsonPath = path.join(workspaceRoot, mapping.root, 'package.json');\n if (fs.existsSync(pkgJsonPath)) {\n try {\n const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));\n if (pkgJson.name) {\n packageNames.add(pkgJson.name);\n }\n } catch {\n // Ignore parse errors\n }\n }\n }\n\n return packageNames;\n}\n\n/**\n * Check if an import path is a workspace project\n * Works for scoped (@scope/name) or unscoped (name) packages\n */\nfunction isWorkspaceImport(importPath: string, workspaceRoot: string): boolean {\n const workspacePackages = buildWorkspacePackageNames(workspaceRoot);\n return workspacePackages.has(importPath);\n}\n\n/**\n * Get project name from package name\n * e.g., '@webpieces/client' → 'client', 'apis' → 'apis'\n */\nfunction getProjectNameFromPackageName(packageName: string, workspaceRoot: string): string {\n const mappings = buildProjectMappings(workspaceRoot);\n\n // Try to find by reading package.json files\n for (const mapping of mappings) {\n const pkgJsonPath = path.join(workspaceRoot, mapping.root, 'package.json');\n if (fs.existsSync(pkgJsonPath)) {\n try {\n const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));\n if (pkgJson.name === packageName) {\n return mapping.name; // Return project name\n }\n } catch {\n // Ignore parse errors\n }\n }\n }\n\n // Fallback: return package name as-is (might be unscoped project name)\n return packageName;\n}\n\n/**\n * Build project mappings from project.json files in workspace\n */\nfunction buildProjectMappings(workspaceRoot: string): ProjectMapping[] {\n if (cachedProjectMappings !== null) {\n return cachedProjectMappings;\n }\n\n const mappings: ProjectMapping[] = [];\n\n // Scan common locations for project.json files\n const searchDirs = ['packages', 'apps', 'libs', 'libraries', 'services'];\n\n for (const searchDir of searchDirs) {\n const searchPath = path.join(workspaceRoot, searchDir);\n if (!fs.existsSync(searchPath)) continue;\n\n scanForProjects(searchPath, workspaceRoot, mappings);\n }\n\n // Sort by path length (longest first) for more specific matching\n mappings.sort((a, b) => b.root.length - a.root.length);\n\n cachedProjectMappings = mappings;\n return mappings;\n}\n\n/**\n * Recursively scan for project.json files\n */\nfunction scanForProjects(\n dir: string,\n workspaceRoot: string,\n mappings: ProjectMapping[]\n): void {\n try {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n\n if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules') {\n // Check for project.json in this directory\n const projectJsonPath = path.join(fullPath, 'project.json');\n if (fs.existsSync(projectJsonPath)) {\n try {\n const projectJson = JSON.parse(fs.readFileSync(projectJsonPath, 'utf-8'));\n const projectRoot = path.relative(workspaceRoot, fullPath);\n\n // Use project name from project.json as-is (no scope forcing)\n const projectName = projectJson.name || entry.name;\n\n mappings.push({\n root: projectRoot,\n name: projectName,\n });\n } catch (err: any) {\n //const error = toError(err);\n void err;\n }\n }\n\n // Continue scanning subdirectories\n scanForProjects(fullPath, workspaceRoot, mappings);\n }\n }\n } catch (err: any) {\n //const error = toError(err);\n void err;\n }\n}\n\n/**\n * Get project name from file path\n */\nfunction getProjectFromFile(filePath: string, workspaceRoot: string): string | null {\n const relativePath = path.relative(workspaceRoot, filePath).replace(/\\\\/g, '/');\n const mappings = buildProjectMappings(workspaceRoot);\n\n for (const mapping of mappings) {\n if (relativePath.startsWith(mapping.root + '/') || relativePath.startsWith(mapping.root)) {\n return mapping.name;\n }\n }\n\n return null;\n}\n\n/**\n * Compute all transitive dependencies for a project\n */\nfunction computeTransitiveDependencies(project: string, graph: EnhancedGraph): Set<string> {\n const result = new Set<string>();\n const visited = new Set<string>();\n\n function visit(currentProject: string): void {\n if (visited.has(currentProject)) return;\n visited.add(currentProject);\n\n const entry = graph[currentProject];\n if (!entry || !entry.dependsOn) return;\n\n for (const dep of entry.dependsOn) {\n result.add(dep);\n visit(dep);\n }\n }\n\n visit(project);\n return result;\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: 'problem',\n docs: {\n description: 'Enforce blessed architecture dependencies',\n category: 'Best Practices',\n recommended: true,\n url: 'https://github.com/deanhiller/webpieces-ts',\n },\n messages: {\n illegalImport:\n \"⚠️ AI Agent: READ tmp/webpieces/webpieces.dependencies.md for resolution steps!\\n\\n\" +\n \"Import '{{imported}}' violates architecture boundaries.\\n\\n\" +\n \"Project '{{project}}' (level {{level}}) can only import from:\\n\" +\n '{{allowedList}}',\n noGraph:\n 'No architecture graph found at architecture/dependencies.json\\n' +\n 'Run: nx run architecture:validate --mode=update',\n },\n schema: [],\n },\n\n create(context: Rule.RuleContext): Rule.RuleListener {\n const filename = context.filename || context.getFilename();\n const workspaceRoot = findWorkspaceRoot(filename);\n\n return {\n ImportDeclaration(node: any): void {\n const importPath = node.source.value as string;\n\n // Check if this is a workspace import (works for any scope or unscoped)\n if (!isWorkspaceImport(importPath, workspaceRoot)) {\n return; // Not a workspace import, skip validation\n }\n\n // Determine which project this file belongs to\n const sourceProject = getProjectFromFile(filename, workspaceRoot);\n if (!sourceProject) {\n // File not in any known project (e.g., tools/, scripts/)\n return;\n }\n\n // Convert import (package name) to project name\n const targetProject = getProjectNameFromPackageName(importPath, workspaceRoot);\n\n // Self-import is always allowed\n if (targetProject === sourceProject) {\n return;\n }\n\n // Load blessed graph\n const graph = loadBlessedGraph(workspaceRoot);\n if (!graph) {\n // No graph file - warn but don't fail (allows gradual adoption)\n return;\n }\n\n // Get project entry\n const projectEntry = graph[sourceProject];\n if (!projectEntry) {\n // Project not in graph (new project?) - allow\n return;\n }\n\n // Compute allowed dependencies (direct + transitive)\n const allowedDeps = computeTransitiveDependencies(sourceProject, graph);\n\n // Check if import is allowed (use project name, not package name)\n if (!allowedDeps.has(targetProject)) {\n // Write documentation file for AI/developer to read\n ensureDependenciesDoc(workspaceRoot);\n\n const directDeps = projectEntry.dependsOn || [];\n const allowedList =\n directDeps.length > 0\n ? directDeps.map((dep) => ` - ${dep}`).join('\\n') +\n '\\n (and their transitive dependencies)'\n : ' (none - this is a foundation project)';\n\n context.report({\n node: node.source,\n messageId: 'illegalImport',\n data: {\n imported: importPath,\n project: sourceProject,\n level: String(projectEntry.level),\n allowedList: allowedList,\n },\n });\n }\n },\n };\n },\n};\n\nexport = rule;\n"]}
|
|
1
|
+
{"version":3,"file":"enforce-architecture.js","sourceRoot":"","sources":["../../../../../../packages/tooling/dev-config/eslint-plugin/rules/enforce-architecture.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;GAWG;;AAGH,+CAAyB;AACzB,mDAA6B;AAE7B,MAAM,wBAAwB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwIhC,CAAC;AAEF,uDAAuD;AACvD,IAAI,sBAAsB,GAAG,KAAK,CAAC;AAEnC;;GAEG;AACH,SAAS,aAAa,CAAC,OAAe,EAAE,OAAe;IACnD,IAAI,CAAC;QACD,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACzD,EAAE,CAAC,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QAC5C,OAAO,IAAI,CAAC;IAChB,CAAC;IAAC,OAAO,GAAQ,EAAE,CAAC;QAChB,KAAK,GAAG,CAAC;QACT,OAAO,CAAC,IAAI,CAAC,0CAA0C,OAAO,EAAE,CAAC,CAAC;QAClE,OAAO,KAAK,CAAC;IACjB,CAAC;AACL,CAAC;AAED;;;GAGG;AACH,SAAS,qBAAqB,CAAC,aAAqB;IAChD,IAAI,sBAAsB;QAAE,OAAO;IACnC,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,KAAK,EAAE,WAAW,EAAE,2BAA2B,CAAC,CAAC;IAC1F,IAAI,aAAa,CAAC,OAAO,EAAE,wBAAwB,CAAC,EAAE,CAAC;QACnD,sBAAsB,GAAG,IAAI,CAAC;IAClC,CAAC;AACL,CAAC;AAoBD,qDAAqD;AACrD,IAAI,WAAW,GAAyB,IAA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,MAAM,CAAC;wBACX,IAAI,EAAE,IAAI,CAAC,MAAM;wBACjB,SAAS,EAAE,eAAe;wBAC1B,IAAI,EAAE;4BACF,QAAQ,EAAE,UAAU;4BACpB,OAAO,EAAE,aAAa;4BACtB,KAAK,EAAE,MAAM,CAAC,YAAY,CAAC,KAAK,CAAC;4BACjC,WAAW,EAAE,WAAW;yBAC3B;qBACJ,CAAC,CAAC;gBACP,CAAC;YACL,CAAC;SACJ,CAAC;IACN,CAAC;CACJ,CAAC;AAEF,iBAAS,IAAI,CAAC","sourcesContent":["/**\n * ESLint rule to enforce architecture boundaries\n *\n * Validates that imports from @webpieces/* packages comply with the\n * blessed dependency graph in .graphs/dependencies.json\n *\n * Supports transitive dependencies: if A depends on B and B depends on C,\n * then A can import from C.\n *\n * Configuration:\n * '@webpieces/enforce-architecture': 'error'\n */\n\nimport type { Rule } from 'eslint';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nconst DEPENDENCIES_DOC_CONTENT = `# Instructions: Architecture Dependency Violation\n\nIN GENERAL, it is better to avoid these changes and find a different way by moving classes\naround to existing packages you already depend on. It is not always avoidable though.\nA clean dependency graph keeps you out of huge trouble later.\n\nIf you are a human, simply run these commands:\n* nx run architecture:visualize - to see the new dependencies and validate that change is desired\n* nx run architecture:generate - updates the dep graph\n* git diff architecture/dependencies.json - to see the deps changes you made\n\n**READ THIS FILE FIRST before making any changes!**\n\n## ⚠️ CRITICAL WARNING ⚠️\n\n**This is a VERY IMPORTANT change that has LARGE REPERCUSSIONS later!**\n\nAdding new dependencies creates technical debt that compounds over time:\n- Creates coupling between packages that may be hard to undo\n- Can create circular dependency tangles\n- Makes packages harder to test in isolation\n- Increases build times and bundle sizes\n- May force unnecessary upgrades across the codebase\n\n**DO NOT add dependencies without senior developer approval!**\n\n## Understanding the Error\n\nYou've attempted to import from a package that is not in your project's allowed dependencies.\nThe architecture enforces a layered dependency structure where:\n- Level 0 packages are foundation packages with NO dependencies on other @webpieces packages\n- Higher level packages can only depend on lower level packages\n- All dependencies must be explicitly declared\n\n## Steps to Resolve\n\n### Step 1: Generate Current Dependency Graph\nRun this command to see the current architecture:\n\\`\\`\\`bash\nnpx nx run architecture:generate\n\\`\\`\\`\nThis creates/updates \\`architecture/dependencies.json\\` showing all packages and their levels.\n\n### Step 2: Analyze the Proposed Change\nAsk yourself:\n1. **Is this import truly necessary?** Can you refactor to avoid it?\n2. **Should the code move instead?** Maybe the code belongs in a different package.\n3. **Will this create a cycle?** Use \\`npx nx graph\\` to visualize dependencies.\n4. **Can you use an interface/abstraction?** Define interface in lower-level package, implement in higher-level.\n\n### Step 3: Get Senior Developer Approval\n\n## 🛑 AI AGENTS: STOP HERE AND ASK FOR HUMAN APPROVAL! 🛑\n\n**YOU MUST NOT PROCEED TO STEP 4 WITHOUT EXPLICIT HUMAN APPROVAL!**\n\n**REQUIRED**: Discuss this architectural change with a senior developer before proceeding.\n- Explain why the dependency is needed\n- Show you've considered alternatives (Step 2)\n- **WAIT for explicit approval before making ANY changes to project.json or package.json**\n\n**AI Agent Instructions:**\n1. Present your analysis from Step 2 to the human\n2. Explain which package needs which dependency and why\n3. ASK: \"Do you approve adding this dependency?\"\n4. **DO NOT modify project.json or package.json until you receive explicit \"yes\" or approval**\n\n### Step 4: If Approved, Add the Dependency\n\n## ⛔ NEVER MODIFY THESE FILES WITHOUT HUMAN APPROVAL FROM STEP 3! ⛔\n\nOnly after receiving explicit human approval in Step 3, make these changes:\n\n1. **Update project.json** - Add to \\`build.dependsOn\\`:\n \\`\\`\\`json\n {\n \"targets\": {\n \"build\": {\n \"dependsOn\": [\"^build\", \"dep1:build\", \"NEW_PACKAGE:build\"]\n }\n }\n }\n \\`\\`\\`\n\n2. **Update package.json** - Add to \\`dependencies\\`:\n \\`\\`\\`json\n {\n \"dependencies\": {\n \"@webpieces/NEW_PACKAGE\": \"*\"\n }\n }\n \\`\\`\\`\n\n### Step 5: Update Architecture Definition\nRun this command to validate and update the architecture:\n\\`\\`\\`bash\nnpx nx run architecture:generate\n\\`\\`\\`\n\nThis will:\n- Detect any cycles (which MUST be fixed before proceeding)\n- Update \\`architecture/dependencies.json\\` with the new dependency\n- Recalculate package levels\n\n### Step 6: Verify No Cycles\n\\`\\`\\`bash\nnpx nx run architecture:validate-no-cycles\n\\`\\`\\`\n\nIf cycles are detected, you MUST refactor to break the cycle. Common strategies:\n- Move shared code to a lower-level package\n- Use dependency inversion (interfaces in low-level, implementations in high-level)\n- Restructure package boundaries\n\n## Alternative Solutions (Preferred over adding dependencies)\n\n### Option A: Move the Code\nIf you need functionality from another package, consider moving that code to a shared lower-level package.\n\n### Option B: Dependency Inversion\nDefine an interface in the lower-level package, implement it in the higher-level package:\n\\`\\`\\`typescript\n// In foundation package (level 0)\nexport interface Logger { log(msg: string): void; }\n\n// In higher-level package\nexport class ConsoleLogger implements Logger { ... }\n\\`\\`\\`\n\n### Option C: Pass Dependencies as Parameters\nInstead of importing, receive the dependency as a constructor or method parameter.\n\n## Remember\n- Every dependency you add today is technical debt for tomorrow\n- The best dependency is the one you don't need\n- When in doubt, refactor rather than add dependencies\n`;\n\n// Module-level flag to prevent redundant file creation\nlet dependenciesDocCreated = false;\n\n/**\n * Ensure a documentation file exists at the given path.\n */\nfunction ensureDocFile(docPath: string, content: string): boolean {\n try {\n fs.mkdirSync(path.dirname(docPath), { recursive: true });\n fs.writeFileSync(docPath, content, 'utf-8');\n return true;\n } catch (err: any) {\n void err;\n console.warn(`[webpieces] Could not create doc file: ${docPath}`);\n return false;\n }\n}\n\n/**\n * Ensure the dependencies documentation file exists.\n * Called when an architecture violation is detected.\n */\nfunction ensureDependenciesDoc(workspaceRoot: string): void {\n if (dependenciesDocCreated) return;\n const docPath = path.join(workspaceRoot, 'tmp', 'webpieces', 'webpieces.dependencies.md');\n if (ensureDocFile(docPath, DEPENDENCIES_DOC_CONTENT)) {\n dependenciesDocCreated = true;\n }\n}\n\n/**\n * Graph entry format from .graphs/dependencies.json\n */\ninterface GraphEntry {\n level: number;\n dependsOn: string[];\n}\n\ntype EnhancedGraph = Record<string, GraphEntry>;\n\n/**\n * Project mapping entry\n */\ninterface ProjectMapping {\n root: string;\n name: string;\n}\n\n// Cache for blessed graph (loaded once per lint run)\nlet cachedGraph: EnhancedGraph | null = null;\nlet cachedGraphPath: string | null = null;\n\n// Cache for project mappings\nlet cachedProjectMappings: ProjectMapping[] | null = null;\n\n/**\n * Find workspace root by walking up from file location\n */\nfunction findWorkspaceRoot(startPath: string): string {\n let currentDir = path.dirname(startPath);\n\n for (let i = 0; i < 20; i++) {\n const packagePath = path.join(currentDir, 'package.json');\n if (fs.existsSync(packagePath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(packagePath, 'utf-8'));\n if (pkg.workspaces || pkg.name === 'webpieces-ts') {\n return currentDir;\n }\n } catch (err: any) {\n //const error = toError(err);\n void err;\n }\n }\n\n const parent = path.dirname(currentDir);\n if (parent === currentDir) break;\n currentDir = parent;\n }\n\n return process.cwd();\n}\n\n/**\n * Load blessed graph from architecture/dependencies.json\n */\nfunction loadBlessedGraph(workspaceRoot: string): EnhancedGraph | null {\n const graphPath = path.join(workspaceRoot, 'architecture', 'dependencies.json');\n\n // Return cached if same path\n if (cachedGraphPath === graphPath && cachedGraph !== null) {\n return cachedGraph;\n }\n\n if (!fs.existsSync(graphPath)) {\n return null;\n }\n\n try {\n const content = fs.readFileSync(graphPath, 'utf-8');\n cachedGraph = JSON.parse(content) as EnhancedGraph;\n cachedGraphPath = graphPath;\n return cachedGraph;\n } catch (err: any) {\n //const error = toError(err);\n // err is used below\n console.error(`[ESLint @webpieces/enforce-architecture] Could not load graph: ${err}`);\n return null;\n }\n}\n\n/**\n * Build set of all workspace package names (from package.json files)\n * Used to detect workspace imports (works for any scope or unscoped)\n */\nfunction buildWorkspacePackageNames(workspaceRoot: string): Set<string> {\n const packageNames = new Set<string>();\n const mappings = buildProjectMappings(workspaceRoot);\n\n for (const mapping of mappings) {\n const pkgJsonPath = path.join(workspaceRoot, mapping.root, 'package.json');\n if (fs.existsSync(pkgJsonPath)) {\n try {\n const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));\n if (pkgJson.name) {\n packageNames.add(pkgJson.name);\n }\n } catch {\n // Ignore parse errors\n }\n }\n }\n\n return packageNames;\n}\n\n/**\n * Check if an import path is a workspace project\n * Works for scoped (@scope/name) or unscoped (name) packages\n */\nfunction isWorkspaceImport(importPath: string, workspaceRoot: string): boolean {\n const workspacePackages = buildWorkspacePackageNames(workspaceRoot);\n return workspacePackages.has(importPath);\n}\n\n/**\n * Get project name from package name\n * e.g., '@webpieces/client' → 'client', 'apis' → 'apis'\n */\nfunction getProjectNameFromPackageName(packageName: string, workspaceRoot: string): string {\n const mappings = buildProjectMappings(workspaceRoot);\n\n // Try to find by reading package.json files\n for (const mapping of mappings) {\n const pkgJsonPath = path.join(workspaceRoot, mapping.root, 'package.json');\n if (fs.existsSync(pkgJsonPath)) {\n try {\n const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));\n if (pkgJson.name === packageName) {\n return mapping.name; // Return project name\n }\n } catch {\n // Ignore parse errors\n }\n }\n }\n\n // Fallback: return package name as-is (might be unscoped project name)\n return packageName;\n}\n\n/**\n * Build project mappings from project.json files in workspace\n */\nfunction buildProjectMappings(workspaceRoot: string): ProjectMapping[] {\n if (cachedProjectMappings !== null) {\n return cachedProjectMappings;\n }\n\n const mappings: ProjectMapping[] = [];\n\n // Scan common locations for project.json files\n const searchDirs = ['packages', 'apps', 'libs', 'libraries', 'services'];\n\n for (const searchDir of searchDirs) {\n const searchPath = path.join(workspaceRoot, searchDir);\n if (!fs.existsSync(searchPath)) continue;\n\n scanForProjects(searchPath, workspaceRoot, mappings);\n }\n\n // Sort by path length (longest first) for more specific matching\n mappings.sort((a, b) => b.root.length - a.root.length);\n\n cachedProjectMappings = mappings;\n return mappings;\n}\n\n/**\n * Recursively scan for project.json files\n */\nfunction scanForProjects(\n dir: string,\n workspaceRoot: string,\n mappings: ProjectMapping[]\n): void {\n try {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n\n if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules') {\n // Check for project.json in this directory\n const projectJsonPath = path.join(fullPath, 'project.json');\n if (fs.existsSync(projectJsonPath)) {\n try {\n const projectJson = JSON.parse(fs.readFileSync(projectJsonPath, 'utf-8'));\n const projectRoot = path.relative(workspaceRoot, fullPath);\n\n // Use project name from project.json as-is (no scope forcing)\n const projectName = projectJson.name || entry.name;\n\n mappings.push({\n root: projectRoot,\n name: projectName,\n });\n } catch (err: any) {\n //const error = toError(err);\n void err;\n }\n }\n\n // Continue scanning subdirectories\n scanForProjects(fullPath, workspaceRoot, mappings);\n }\n }\n } catch (err: any) {\n //const error = toError(err);\n void err;\n }\n}\n\n/**\n * Get project name from file path\n */\nfunction getProjectFromFile(filePath: string, workspaceRoot: string): string | null {\n const relativePath = path.relative(workspaceRoot, filePath).replace(/\\\\/g, '/');\n const mappings = buildProjectMappings(workspaceRoot);\n\n for (const mapping of mappings) {\n if (relativePath.startsWith(mapping.root + '/') || relativePath.startsWith(mapping.root)) {\n return mapping.name;\n }\n }\n\n return null;\n}\n\n/**\n * Compute all transitive dependencies for a project\n */\nfunction computeTransitiveDependencies(project: string, graph: EnhancedGraph): Set<string> {\n const result = new Set<string>();\n const visited = new Set<string>();\n\n function visit(currentProject: string): void {\n if (visited.has(currentProject)) return;\n visited.add(currentProject);\n\n const entry = graph[currentProject];\n if (!entry || !entry.dependsOn) return;\n\n for (const dep of entry.dependsOn) {\n result.add(dep);\n visit(dep);\n }\n }\n\n visit(project);\n return result;\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: 'problem',\n docs: {\n description: 'Enforce blessed architecture dependencies',\n category: 'Best Practices',\n recommended: true,\n url: 'https://github.com/deanhiller/webpieces-ts',\n },\n messages: {\n illegalImport:\n \"⚠️ AI Agent: READ tmp/webpieces/webpieces.dependencies.md for resolution steps!\\n\\n\" +\n \"Import '{{imported}}' violates architecture boundaries.\\n\\n\" +\n \"Project '{{project}}' (level {{level}}) can only import from:\\n\" +\n '{{allowedList}}',\n noGraph:\n 'No architecture graph found at architecture/dependencies.json\\n' +\n 'Run: nx run architecture:validate --mode=update',\n },\n schema: [],\n },\n\n create(context: Rule.RuleContext): Rule.RuleListener {\n const filename = context.filename || context.getFilename();\n const workspaceRoot = findWorkspaceRoot(filename);\n\n return {\n ImportDeclaration(node: any): void {\n const importPath = node.source.value as string;\n\n // Check if this is a workspace import (works for any scope or unscoped)\n if (!isWorkspaceImport(importPath, workspaceRoot)) {\n return; // Not a workspace import, skip validation\n }\n\n // Determine which project this file belongs to\n const sourceProject = getProjectFromFile(filename, workspaceRoot);\n if (!sourceProject) {\n // File not in any known project (e.g., tools/, scripts/)\n return;\n }\n\n // Convert import (package name) to project name\n const targetProject = getProjectNameFromPackageName(importPath, workspaceRoot);\n\n // Self-import is always allowed\n if (targetProject === sourceProject) {\n return;\n }\n\n // Load blessed graph\n const graph = loadBlessedGraph(workspaceRoot);\n if (!graph) {\n // No graph file - warn but don't fail (allows gradual adoption)\n return;\n }\n\n // Get project entry\n const projectEntry = graph[sourceProject];\n if (!projectEntry) {\n // Project not in graph (new project?) - allow\n return;\n }\n\n // Compute allowed dependencies (direct + transitive)\n const allowedDeps = computeTransitiveDependencies(sourceProject, graph);\n\n // Check if import is allowed (use project name, not package name)\n if (!allowedDeps.has(targetProject)) {\n // Write documentation file for AI/developer to read\n ensureDependenciesDoc(workspaceRoot);\n\n const directDeps = projectEntry.dependsOn || [];\n const allowedList =\n directDeps.length > 0\n ? directDeps.map((dep) => ` - ${dep}`).join('\\n') +\n '\\n (and their transitive dependencies)'\n : ' (none - this is a foundation project)';\n\n context.report({\n node: node.source,\n messageId: 'illegalImport',\n data: {\n imported: importPath,\n project: sourceProject,\n level: String(projectEntry.level),\n allowedList: allowedList,\n },\n });\n }\n },\n };\n },\n};\n\nexport = rule;\n"]}
|
|
@@ -15,7 +15,16 @@ import type { Rule } from 'eslint';
|
|
|
15
15
|
import * as fs from 'fs';
|
|
16
16
|
import * as path from 'path';
|
|
17
17
|
|
|
18
|
-
const DEPENDENCIES_DOC_CONTENT = `#
|
|
18
|
+
const DEPENDENCIES_DOC_CONTENT = `# Instructions: Architecture Dependency Violation
|
|
19
|
+
|
|
20
|
+
IN GENERAL, it is better to avoid these changes and find a different way by moving classes
|
|
21
|
+
around to existing packages you already depend on. It is not always avoidable though.
|
|
22
|
+
A clean dependency graph keeps you out of huge trouble later.
|
|
23
|
+
|
|
24
|
+
If you are a human, simply run these commands:
|
|
25
|
+
* nx run architecture:visualize - to see the new dependencies and validate that change is desired
|
|
26
|
+
* nx run architecture:generate - updates the dep graph
|
|
27
|
+
* git diff architecture/dependencies.json - to see the deps changes you made
|
|
19
28
|
|
|
20
29
|
**READ THIS FILE FIRST before making any changes!**
|
|
21
30
|
|
|
@@ -102,7 +111,7 @@ Only after receiving explicit human approval in Step 3, make these changes:
|
|
|
102
111
|
### Step 5: Update Architecture Definition
|
|
103
112
|
Run this command to validate and update the architecture:
|
|
104
113
|
\`\`\`bash
|
|
105
|
-
npx nx run architecture:
|
|
114
|
+
npx nx run architecture:generate
|
|
106
115
|
\`\`\`
|
|
107
116
|
|
|
108
117
|
This will:
|
|
@@ -112,7 +121,7 @@ This will:
|
|
|
112
121
|
|
|
113
122
|
### Step 6: Verify No Cycles
|
|
114
123
|
\`\`\`bash
|
|
115
|
-
npx nx run architecture:validate
|
|
124
|
+
npx nx run architecture:validate-no-cycles
|
|
116
125
|
\`\`\`
|
|
117
126
|
|
|
118
127
|
If cycles are detected, you MUST refactor to break the cycle. Common strategies:
|
package/executors.json
CHANGED
|
@@ -30,6 +30,11 @@
|
|
|
30
30
|
"schema": "./architecture/executors/validate-packagejson/schema.json",
|
|
31
31
|
"description": "Validate package.json dependencies match project.json build dependencies"
|
|
32
32
|
},
|
|
33
|
+
"validate-new-methods": {
|
|
34
|
+
"implementation": "./architecture/executors/validate-new-methods/executor",
|
|
35
|
+
"schema": "./architecture/executors/validate-new-methods/schema.json",
|
|
36
|
+
"description": "Validate new methods don't exceed max line count (only runs in affected mode)"
|
|
37
|
+
},
|
|
33
38
|
"help": {
|
|
34
39
|
"implementation": "./executors/help/executor",
|
|
35
40
|
"schema": "./executors/help/schema.json",
|