@webpieces/eslint-plugin 0.0.0-dev

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,473 @@
1
+ "use strict";
2
+ /**
3
+ * ESLint rule to enforce architecture boundaries
4
+ *
5
+ * Validates that imports from @webpieces/* packages comply with the
6
+ * blessed dependency graph in .graphs/dependencies.json
7
+ *
8
+ * Supports transitive dependencies: if A depends on B and B depends on C,
9
+ * then A can import from C.
10
+ *
11
+ * Configuration:
12
+ * '@webpieces/enforce-architecture': 'error'
13
+ */
14
+ const tslib_1 = require("tslib");
15
+ const fs = tslib_1.__importStar(require("fs"));
16
+ const path = tslib_1.__importStar(require("path"));
17
+ const toError_1 = require("../toError");
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
28
+
29
+ **READ THIS FILE FIRST before making any changes!**
30
+
31
+ ## ⚠️ CRITICAL WARNING ⚠️
32
+
33
+ **This is a VERY IMPORTANT change that has LARGE REPERCUSSIONS later!**
34
+
35
+ Adding new dependencies creates technical debt that compounds over time:
36
+ - Creates coupling between packages that may be hard to undo
37
+ - Can create circular dependency tangles
38
+ - Makes packages harder to test in isolation
39
+ - Increases build times and bundle sizes
40
+ - May force unnecessary upgrades across the codebase
41
+
42
+ **DO NOT add dependencies without senior developer approval!**
43
+
44
+ ## Understanding the Error
45
+
46
+ You've attempted to import from a package that is not in your project's allowed dependencies.
47
+ The architecture enforces a layered dependency structure where:
48
+ - Level 0 packages are foundation packages with NO dependencies on other @webpieces packages
49
+ - Higher level packages can only depend on lower level packages
50
+ - All dependencies must be explicitly declared
51
+
52
+ ## Steps to Resolve
53
+
54
+ ### Step 1: Generate Current Dependency Graph
55
+ Run this command to see the current architecture:
56
+ \`\`\`bash
57
+ npx nx run architecture:generate
58
+ \`\`\`
59
+ This creates/updates \`architecture/dependencies.json\` showing all packages and their levels.
60
+
61
+ ### Step 2: Analyze the Proposed Change
62
+ Ask yourself:
63
+ 1. **Is this import truly necessary?** Can you refactor to avoid it?
64
+ 2. **Should the code move instead?** Maybe the code belongs in a different package.
65
+ 3. **Will this create a cycle?** Use \`npx nx graph\` to visualize dependencies.
66
+ 4. **Can you use an interface/abstraction?** Define interface in lower-level package, implement in higher-level.
67
+
68
+ ### Step 3: Get Senior Developer Approval
69
+
70
+ ## 🛑 AI AGENTS: STOP HERE AND ASK FOR HUMAN APPROVAL! 🛑
71
+
72
+ **YOU MUST NOT PROCEED TO STEP 4 WITHOUT EXPLICIT HUMAN APPROVAL!**
73
+
74
+ **REQUIRED**: Discuss this architectural change with a senior developer before proceeding.
75
+ - Explain why the dependency is needed
76
+ - Show you've considered alternatives (Step 2)
77
+ - **WAIT for explicit approval before making ANY changes to project.json or package.json**
78
+
79
+ **AI Agent Instructions:**
80
+ 1. Present your analysis from Step 2 to the human
81
+ 2. Explain which package needs which dependency and why
82
+ 3. ASK: "Do you approve adding this dependency?"
83
+ 4. **DO NOT modify project.json or package.json until you receive explicit "yes" or approval**
84
+
85
+ ### Step 4: If Approved, Add the Dependency
86
+
87
+ ## ⛔ NEVER MODIFY THESE FILES WITHOUT HUMAN APPROVAL FROM STEP 3! ⛔
88
+
89
+ Only after receiving explicit human approval in Step 3, make these changes:
90
+
91
+ 1. **Update project.json** - Add to \`build.dependsOn\`:
92
+ \`\`\`json
93
+ {
94
+ "targets": {
95
+ "build": {
96
+ "dependsOn": ["^build", "dep1:build", "NEW_PACKAGE:build"]
97
+ }
98
+ }
99
+ }
100
+ \`\`\`
101
+
102
+ 2. **Update package.json** - Add to \`dependencies\`:
103
+ \`\`\`json
104
+ {
105
+ "dependencies": {
106
+ "@webpieces/NEW_PACKAGE": "*"
107
+ }
108
+ }
109
+ \`\`\`
110
+
111
+ ### Step 5: Update Architecture Definition
112
+ Run this command to validate and update the architecture:
113
+ \`\`\`bash
114
+ npx nx run architecture:generate
115
+ \`\`\`
116
+
117
+ This will:
118
+ - Detect any cycles (which MUST be fixed before proceeding)
119
+ - Update \`architecture/dependencies.json\` with the new dependency
120
+ - Recalculate package levels
121
+
122
+ ### Step 6: Verify No Cycles
123
+ \`\`\`bash
124
+ npx nx run architecture:validate-no-architecture-cycles
125
+ \`\`\`
126
+
127
+ If cycles are detected, you MUST refactor to break the cycle. Common strategies:
128
+ - Move shared code to a lower-level package
129
+ - Use dependency inversion (interfaces in low-level, implementations in high-level)
130
+ - Restructure package boundaries
131
+
132
+ ## Alternative Solutions (Preferred over adding dependencies)
133
+
134
+ ### Option A: Move the Code
135
+ If you need functionality from another package, consider moving that code to a shared lower-level package.
136
+
137
+ ### Option B: Dependency Inversion
138
+ Define an interface in the lower-level package, implement it in the higher-level package:
139
+ \`\`\`typescript
140
+ // In foundation package (level 0)
141
+ export interface Logger { log(msg: string): void; }
142
+
143
+ // In higher-level package
144
+ export class ConsoleLogger implements Logger { ... }
145
+ \`\`\`
146
+
147
+ ### Option C: Pass Dependencies as Parameters
148
+ Instead of importing, receive the dependency as a constructor or method parameter.
149
+
150
+ ## Remember
151
+ - Every dependency you add today is technical debt for tomorrow
152
+ - The best dependency is the one you don't need
153
+ - When in doubt, refactor rather than add dependencies
154
+ `;
155
+ // Module-level flag to prevent redundant file creation
156
+ let dependenciesDocCreated = false;
157
+ /**
158
+ * Ensure a documentation file exists at the given path.
159
+ */
160
+ function ensureDocFile(docPath, content) {
161
+ try {
162
+ fs.mkdirSync(path.dirname(docPath), { recursive: true });
163
+ fs.writeFileSync(docPath, content, 'utf-8');
164
+ return true;
165
+ }
166
+ catch (err) {
167
+ void err;
168
+ console.warn(`[webpieces] Could not create doc file: ${docPath}`);
169
+ return false;
170
+ }
171
+ }
172
+ /**
173
+ * Ensure the dependencies documentation file exists.
174
+ * Called when an architecture violation is detected.
175
+ */
176
+ function ensureDependenciesDoc(workspaceRoot) {
177
+ if (dependenciesDocCreated)
178
+ return;
179
+ const docPath = path.join(workspaceRoot, 'tmp', 'webpieces', 'webpieces.dependencies.md');
180
+ if (ensureDocFile(docPath, DEPENDENCIES_DOC_CONTENT)) {
181
+ dependenciesDocCreated = true;
182
+ }
183
+ }
184
+ // Cache for blessed graph (loaded once per lint run)
185
+ let cachedGraph = null;
186
+ let cachedGraphPath = null;
187
+ // Cache for project mappings
188
+ let cachedProjectMappings = null;
189
+ /**
190
+ * Find workspace root by walking up from file location
191
+ */
192
+ function findWorkspaceRoot(startPath) {
193
+ let currentDir = path.dirname(startPath);
194
+ for (let i = 0; i < 20; i++) {
195
+ const packagePath = path.join(currentDir, 'package.json');
196
+ if (fs.existsSync(packagePath)) {
197
+ try {
198
+ const pkg = JSON.parse(fs.readFileSync(packagePath, 'utf-8'));
199
+ if (pkg.workspaces || pkg.name === 'webpieces-ts') {
200
+ return currentDir;
201
+ }
202
+ }
203
+ catch (err) {
204
+ //const error = toError(err);
205
+ void err;
206
+ }
207
+ }
208
+ const parent = path.dirname(currentDir);
209
+ if (parent === currentDir)
210
+ break;
211
+ currentDir = parent;
212
+ }
213
+ return process.cwd();
214
+ }
215
+ /**
216
+ * Load blessed graph from architecture/dependencies.json
217
+ */
218
+ function loadBlessedGraph(workspaceRoot) {
219
+ const graphPath = path.join(workspaceRoot, 'architecture', 'dependencies.json');
220
+ // Return cached if same path
221
+ if (cachedGraphPath === graphPath && cachedGraph !== null) {
222
+ return cachedGraph;
223
+ }
224
+ if (!fs.existsSync(graphPath)) {
225
+ return null;
226
+ }
227
+ try {
228
+ const content = fs.readFileSync(graphPath, 'utf-8');
229
+ cachedGraph = JSON.parse(content);
230
+ cachedGraphPath = graphPath;
231
+ return cachedGraph;
232
+ }
233
+ catch (err) {
234
+ const error = (0, toError_1.toError)(err);
235
+ console.error(`[ESLint @webpieces/enforce-architecture] Could not load graph: ${error.message}`);
236
+ return null;
237
+ }
238
+ }
239
+ /**
240
+ * Build set of all workspace package names (from package.json files)
241
+ * Used to detect workspace imports (works for any scope or unscoped)
242
+ */
243
+ function buildWorkspacePackageNames(workspaceRoot) {
244
+ const packageNames = new Set();
245
+ const mappings = buildProjectMappings(workspaceRoot);
246
+ for (const mapping of mappings) {
247
+ const pkgJsonPath = path.join(workspaceRoot, mapping.root, 'package.json');
248
+ if (fs.existsSync(pkgJsonPath)) {
249
+ try {
250
+ const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));
251
+ if (pkgJson.name) {
252
+ packageNames.add(pkgJson.name);
253
+ }
254
+ }
255
+ catch {
256
+ // Ignore parse errors
257
+ }
258
+ }
259
+ }
260
+ return packageNames;
261
+ }
262
+ /**
263
+ * Check if an import path is a workspace project
264
+ * Works for scoped (@scope/name) or unscoped (name) packages
265
+ */
266
+ function isWorkspaceImport(importPath, workspaceRoot) {
267
+ const workspacePackages = buildWorkspacePackageNames(workspaceRoot);
268
+ return workspacePackages.has(importPath);
269
+ }
270
+ /**
271
+ * Get project name from package name
272
+ * e.g., '@webpieces/client' → 'client', 'apis' → 'apis'
273
+ */
274
+ function getProjectNameFromPackageName(packageName, workspaceRoot) {
275
+ const mappings = buildProjectMappings(workspaceRoot);
276
+ // Try to find by reading package.json files
277
+ for (const mapping of mappings) {
278
+ const pkgJsonPath = path.join(workspaceRoot, mapping.root, 'package.json');
279
+ if (fs.existsSync(pkgJsonPath)) {
280
+ try {
281
+ const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));
282
+ if (pkgJson.name === packageName) {
283
+ return mapping.name; // Return project name
284
+ }
285
+ }
286
+ catch {
287
+ // Ignore parse errors
288
+ }
289
+ }
290
+ }
291
+ // Fallback: return package name as-is (might be unscoped project name)
292
+ return packageName;
293
+ }
294
+ /**
295
+ * Build project mappings from project.json files in workspace
296
+ */
297
+ function buildProjectMappings(workspaceRoot) {
298
+ if (cachedProjectMappings !== null) {
299
+ return cachedProjectMappings;
300
+ }
301
+ const mappings = [];
302
+ // Scan common locations for project.json files
303
+ const searchDirs = ['packages', 'apps', 'libs', 'libraries', 'services'];
304
+ for (const searchDir of searchDirs) {
305
+ const searchPath = path.join(workspaceRoot, searchDir);
306
+ if (!fs.existsSync(searchPath))
307
+ continue;
308
+ scanForProjects(searchPath, workspaceRoot, mappings);
309
+ }
310
+ // Sort by path length (longest first) for more specific matching
311
+ mappings.sort((a, b) => b.root.length - a.root.length);
312
+ cachedProjectMappings = mappings;
313
+ return mappings;
314
+ }
315
+ /**
316
+ * Recursively scan for project.json files
317
+ */
318
+ function scanForProjects(dir, workspaceRoot, mappings) {
319
+ try {
320
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
321
+ for (const entry of entries) {
322
+ const fullPath = path.join(dir, entry.name);
323
+ if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules') {
324
+ // Check for project.json in this directory
325
+ const projectJsonPath = path.join(fullPath, 'project.json');
326
+ if (fs.existsSync(projectJsonPath)) {
327
+ try {
328
+ const projectJson = JSON.parse(fs.readFileSync(projectJsonPath, 'utf-8'));
329
+ const projectRoot = path.relative(workspaceRoot, fullPath);
330
+ // Use project name from project.json as-is (no scope forcing)
331
+ const projectName = projectJson.name || entry.name;
332
+ mappings.push({
333
+ root: projectRoot,
334
+ name: projectName,
335
+ });
336
+ }
337
+ catch (err) {
338
+ //const error = toError(err);
339
+ void err;
340
+ }
341
+ }
342
+ // Continue scanning subdirectories
343
+ scanForProjects(fullPath, workspaceRoot, mappings);
344
+ }
345
+ }
346
+ }
347
+ catch (err) {
348
+ //const error = toError(err);
349
+ void err;
350
+ }
351
+ }
352
+ /**
353
+ * Get project name from file path
354
+ */
355
+ function getProjectFromFile(filePath, workspaceRoot) {
356
+ const relativePath = path.relative(workspaceRoot, filePath).replace(/\\/g, '/');
357
+ const mappings = buildProjectMappings(workspaceRoot);
358
+ for (const mapping of mappings) {
359
+ if (relativePath.startsWith(mapping.root + '/') || relativePath.startsWith(mapping.root)) {
360
+ return mapping.name;
361
+ }
362
+ }
363
+ return null;
364
+ }
365
+ /**
366
+ * Compute all transitive dependencies for a project
367
+ */
368
+ function computeTransitiveDependencies(project, graph) {
369
+ const result = new Set();
370
+ const visited = new Set();
371
+ function visit(currentProject) {
372
+ if (visited.has(currentProject))
373
+ return;
374
+ visited.add(currentProject);
375
+ const entry = graph[currentProject];
376
+ if (!entry || !entry.dependsOn)
377
+ return;
378
+ for (const dep of entry.dependsOn) {
379
+ result.add(dep);
380
+ visit(dep);
381
+ }
382
+ }
383
+ visit(project);
384
+ return result;
385
+ }
386
+ function buildAllowedDepsList(allowedDeps, graph) {
387
+ const sorted = Array.from(allowedDeps).sort((a, b) => {
388
+ const diff = (graph[b]?.level ?? 0) - (graph[a]?.level ?? 0);
389
+ return diff !== 0 ? diff : a.localeCompare(b);
390
+ });
391
+ if (sorted.length === 0)
392
+ return ' (none - this is a foundation project)';
393
+ return sorted.map((dep) => ` - ${dep} (level ${graph[dep]?.level ?? '?'})`).join('\n');
394
+ }
395
+ const rule = {
396
+ meta: {
397
+ type: 'problem',
398
+ docs: {
399
+ description: 'Enforce blessed architecture dependencies',
400
+ category: 'Best Practices',
401
+ recommended: true,
402
+ url: 'https://github.com/deanhiller/webpieces-ts',
403
+ },
404
+ messages: {
405
+ illegalImport: "⚠️ AI Agent: READ tmp/webpieces/webpieces.dependencies.md for resolution steps!\n\n" +
406
+ "Import '{{imported}}' violates architecture boundaries.\n\n" +
407
+ "Project '{{project}}' (level {{level}}) can only import from:\n" +
408
+ '{{allowedList}}',
409
+ noGraph: 'No architecture graph found at architecture/dependencies.json\n' +
410
+ 'Run: nx run architecture:validate --mode=update',
411
+ },
412
+ schema: [],
413
+ },
414
+ // webpieces-disable max-lines-new-methods -- ESLint rule create method with AST validation
415
+ create(context) {
416
+ const filename = context.filename || context.getFilename();
417
+ const workspaceRoot = findWorkspaceRoot(filename);
418
+ return {
419
+ // webpieces-disable no-any-unknown -- ESLint visitor callback receives untyped AST node
420
+ ImportDeclaration(node) {
421
+ const importPath = node.source.value;
422
+ // Check if this is a workspace import (works for any scope or unscoped)
423
+ if (!isWorkspaceImport(importPath, workspaceRoot)) {
424
+ return; // Not a workspace import, skip validation
425
+ }
426
+ // Determine which project this file belongs to
427
+ const sourceProject = getProjectFromFile(filename, workspaceRoot);
428
+ if (!sourceProject) {
429
+ // File not in any known project (e.g., tools/, scripts/)
430
+ return;
431
+ }
432
+ // Convert import (package name) to project name
433
+ const targetProject = getProjectNameFromPackageName(importPath, workspaceRoot);
434
+ // Self-import is always allowed
435
+ if (targetProject === sourceProject) {
436
+ return;
437
+ }
438
+ // Load blessed graph
439
+ const graph = loadBlessedGraph(workspaceRoot);
440
+ if (!graph) {
441
+ // No graph file - warn but don't fail (allows gradual adoption)
442
+ return;
443
+ }
444
+ // Get project entry
445
+ const projectEntry = graph[sourceProject];
446
+ if (!projectEntry) {
447
+ // Project not in graph (new project?) - allow
448
+ return;
449
+ }
450
+ // Compute allowed dependencies (direct + transitive)
451
+ const allowedDeps = computeTransitiveDependencies(sourceProject, graph);
452
+ // Check if import is allowed (use project name, not package name)
453
+ if (!allowedDeps.has(targetProject)) {
454
+ // Write documentation file for AI/developer to read
455
+ ensureDependenciesDoc(workspaceRoot);
456
+ const allowedList = buildAllowedDepsList(allowedDeps, graph);
457
+ context.report({
458
+ node: node.source,
459
+ messageId: 'illegalImport',
460
+ data: {
461
+ imported: importPath,
462
+ project: sourceProject,
463
+ level: String(projectEntry.level),
464
+ allowedList: allowedList,
465
+ },
466
+ });
467
+ }
468
+ },
469
+ };
470
+ },
471
+ };
472
+ module.exports = rule;
473
+ //# sourceMappingURL=enforce-architecture.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enforce-architecture.js","sourceRoot":"","sources":["../../../../../../packages/tooling/eslint-plugin/src/rules/enforce-architecture.ts"],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O;gBACX,CAAC;gBAED,oBAAoB;gBACpB,MAAM,YAAY,GAAG,KAAK,CAAC,aAAa,CAAC,CAAC;gBAC1C,IAAI,CAAC,YAAY,EAAE,CAAC;oBAChB,8CAA8C;oBAC9C,OAAO;gBACX,CAAC;gBAED,qDAAqD;gBACrD,MAAM,WAAW,GAAG,6BAA6B,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;gBAExE,kEAAkE;gBAClE,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC;oBAClC,oDAAoD;oBACpD,qBAAqB,CAAC,aAAa,CAAC,CAAC;oBAErC,MAAM,WAAW,GAAG,oBAAoB,CAAC,WAAW,EAAE,KAAK,CAAC,CAAC;oBAE7D,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';\nimport { toError } from '../toError';\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-architecture-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: unknown) {\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: unknown) {\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: unknown) {\n const error = toError(err);\n console.error(`[ESLint @webpieces/enforce-architecture] Could not load graph: ${error.message}`);\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: unknown) {\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: unknown) {\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\nfunction buildAllowedDepsList(allowedDeps: Set<string>, graph: EnhancedGraph): string {\n const sorted = Array.from(allowedDeps).sort((a, b) => {\n const diff = (graph[b]?.level ?? 0) - (graph[a]?.level ?? 0);\n return diff !== 0 ? diff : a.localeCompare(b);\n });\n if (sorted.length === 0) return ' (none - this is a foundation project)';\n return sorted.map((dep) => ` - ${dep} (level ${graph[dep]?.level ?? '?'})`).join('\\n');\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 // webpieces-disable max-lines-new-methods -- ESLint rule create method with AST validation\n create(context: Rule.RuleContext): Rule.RuleListener {\n const filename = context.filename || context.getFilename();\n const workspaceRoot = findWorkspaceRoot(filename);\n\n return {\n // webpieces-disable no-any-unknown -- ESLint visitor callback receives untyped AST node\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 allowedList = buildAllowedDepsList(allowedDeps, graph);\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"]}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * ESLint rule to enforce maximum file length
3
+ *
4
+ * Enforces a configurable maximum line count for files.
5
+ * Default: 700 lines
6
+ *
7
+ * Configuration:
8
+ * '@webpieces/max-file-lines': ['error', { max: 700 }]
9
+ */
10
+ import type { Rule } from 'eslint';
11
+ declare const rule: Rule.RuleModule;
12
+ export = rule;