@webpieces/nx-webpieces-rules 0.3.258 → 0.3.259
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/package.json +6 -6
- package/src/di-graph-targets.js +2 -2
- package/src/di-graph-targets.js.map +1 -1
- package/src/executors/di-graph-generate/executor.d.ts +2 -1
- package/src/executors/di-graph-generate/executor.js +20 -6
- package/src/executors/di-graph-generate/executor.js.map +1 -1
- package/src/executors/generate/executor.js +5 -0
- package/src/executors/generate/executor.js.map +1 -1
- package/src/executors/validate-di-graph-unchanged/executor.d.ts +2 -2
- package/src/executors/validate-di-graph-unchanged/executor.js +5 -5
- package/src/executors/validate-di-graph-unchanged/executor.js.map +1 -1
- package/src/executors/visualize/executor.js +0 -1
- package/src/executors/visualize/executor.js.map +1 -1
- package/src/lib/di-graph/design-visualizer.d.ts +5 -1
- package/src/lib/di-graph/design-visualizer.js +13 -1
- package/src/lib/di-graph/design-visualizer.js.map +1 -1
- package/src/lib/graph-visualizer.d.ts +9 -2
- package/src/lib/graph-visualizer.js +49 -11
- package/src/lib/graph-visualizer.js.map +1 -1
- package/src/plugin.js +2 -1
- package/src/plugin.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/nx-webpieces-rules",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.259",
|
|
4
4
|
"description": "Nx-specific webpieces validation rules and graph tooling. Bundles all @webpieces rule packages with Nx graph validators and an inference plugin.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -21,11 +21,11 @@
|
|
|
21
21
|
"README.md"
|
|
22
22
|
],
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@webpieces/ai-hook-rules": "0.3.
|
|
25
|
-
"@webpieces/code-rules": "0.3.
|
|
26
|
-
"@webpieces/eslint-rules": "0.3.
|
|
27
|
-
"@webpieces/pr-gate": "0.3.
|
|
28
|
-
"@webpieces/rules-config": "0.3.
|
|
24
|
+
"@webpieces/ai-hook-rules": "0.3.259",
|
|
25
|
+
"@webpieces/code-rules": "0.3.259",
|
|
26
|
+
"@webpieces/eslint-rules": "0.3.259",
|
|
27
|
+
"@webpieces/pr-gate": "0.3.259",
|
|
28
|
+
"@webpieces/rules-config": "0.3.259",
|
|
29
29
|
"madge": "8.0.0"
|
|
30
30
|
},
|
|
31
31
|
"peerDependencies": {
|
package/src/di-graph-targets.js
CHANGED
|
@@ -16,10 +16,10 @@ function createDiGraphGenerateTarget() {
|
|
|
16
16
|
return {
|
|
17
17
|
executor: '@webpieces/nx-webpieces-rules:di-graph-generate',
|
|
18
18
|
cache: false,
|
|
19
|
-
outputs: ['{projectRoot}/design.json', '{projectRoot}/design.md'],
|
|
19
|
+
outputs: ['{projectRoot}/design.json', '{projectRoot}/design.md', '{projectRoot}/design.html'],
|
|
20
20
|
metadata: {
|
|
21
21
|
technologies: ['nx'],
|
|
22
|
-
description: 'Generate the Inversify DI dependency DAG into design.json + design.md',
|
|
22
|
+
description: 'Generate the Inversify DI dependency DAG into design.json + design.md + clickable design.html',
|
|
23
23
|
},
|
|
24
24
|
};
|
|
25
25
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"di-graph-targets.js","sourceRoot":"","sources":["../../../../../packages/tooling/nx-webpieces-rules/src/di-graph-targets.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AASH,
|
|
1
|
+
{"version":3,"file":"di-graph-targets.js","sourceRoot":"","sources":["../../../../../packages/tooling/nx-webpieces-rules/src/di-graph-targets.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AASH,kEAWC;AAMD,oFAUC;AAhCD;;;;GAIG;AACH,SAAgB,2BAA2B;IACvC,OAAO;QACH,QAAQ,EAAE,iDAAiD;QAC3D,KAAK,EAAE,KAAK;QACZ,OAAO,EAAE,CAAC,2BAA2B,EAAE,yBAAyB,EAAE,2BAA2B,CAAC;QAC9F,QAAQ,EAAE;YACN,YAAY,EAAE,CAAC,IAAI,CAAC;YACpB,WAAW,EACP,+FAA+F;SACtG;KACJ,CAAC;AACN,CAAC;AAED;;;GAGG;AACH,SAAgB,oCAAoC;IAChD,OAAO;QACH,QAAQ,EAAE,2DAA2D;QACrE,KAAK,EAAE,KAAK,EAAE,uBAAuB;QACrC,SAAS,EAAE,CAAC,mBAAmB,CAAC;QAChC,QAAQ,EAAE;YACN,YAAY,EAAE,CAAC,IAAI,CAAC;YACpB,WAAW,EAAE,6EAA6E;SAC7F;KACJ,CAAC;AACN,CAAC","sourcesContent":["/**\n * Per-project DI design graph targets (design.json + design.md), attached to every\n * project.json project by the inference plugin. Split out of plugin.ts the same way\n * as runtime-targets.ts.\n */\n\nimport type { TargetConfiguration } from '@nx/devkit';\n\n/**\n * Create per-project DI graph generation target. cache:false because the point\n * is to regenerate design.json/design.md on EVERY build so the committed DI\n * design DAG can never silently drift from the code.\n */\nexport function createDiGraphGenerateTarget(): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:di-graph-generate',\n cache: false,\n outputs: ['{projectRoot}/design.json', '{projectRoot}/design.md', '{projectRoot}/design.html'],\n metadata: {\n technologies: ['nx'],\n description:\n 'Generate the Inversify DI dependency DAG into design.json + design.md + clickable design.html',\n },\n };\n}\n\n/**\n * Create per-project DI graph staleness gate — regenerates first (dependsOn),\n * then fails if the regenerated files differ from the committed copies.\n */\nexport function createValidateDiGraphUnchangedTarget(): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-di-graph-unchanged',\n cache: false, // Depends on git state\n dependsOn: ['di-graph-generate'],\n metadata: {\n technologies: ['nx'],\n description: 'Validate the committed design.json/design.md match the regenerated DI graph',\n },\n };\n}\n"]}
|
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Per-project: statically analyzes the project's Inversify dependency DAG
|
|
5
5
|
* (constructor injection from controllers — or library top-of-DAG classes —
|
|
6
|
-
* down to leaves) and writes
|
|
6
|
+
* down to leaves) and writes three checked-in files at the project root:
|
|
7
7
|
*
|
|
8
8
|
* design.json — machine-readable graph (deterministic, sorted)
|
|
9
9
|
* design.md — Mermaid diagram rendered by GitHub/IDEs in PRs
|
|
10
|
+
* design.html — clickable viz.js page (linked from architecture/dependencies.html)
|
|
10
11
|
*
|
|
11
12
|
* Runs on every build (cache:false; the build gates on
|
|
12
13
|
* validate-di-graph-unchanged which dependsOn this target). Unrecognized DI
|
|
@@ -4,10 +4,11 @@
|
|
|
4
4
|
*
|
|
5
5
|
* Per-project: statically analyzes the project's Inversify dependency DAG
|
|
6
6
|
* (constructor injection from controllers — or library top-of-DAG classes —
|
|
7
|
-
* down to leaves) and writes
|
|
7
|
+
* down to leaves) and writes three checked-in files at the project root:
|
|
8
8
|
*
|
|
9
9
|
* design.json — machine-readable graph (deterministic, sorted)
|
|
10
10
|
* design.md — Mermaid diagram rendered by GitHub/IDEs in PRs
|
|
11
|
+
* design.html — clickable viz.js page (linked from architecture/dependencies.html)
|
|
11
12
|
*
|
|
12
13
|
* Runs on every build (cache:false; the build gates on
|
|
13
14
|
* validate-di-graph-unchanged which dependsOn this target). Unrecognized DI
|
|
@@ -27,6 +28,7 @@ const analyzer_strategy_1 = require("../../lib/di-graph/analyzer-strategy");
|
|
|
27
28
|
const program_1 = require("../../lib/di-graph/program");
|
|
28
29
|
const serializer_1 = require("../../lib/di-graph/serializer");
|
|
29
30
|
const mermaid_1 = require("../../lib/di-graph/mermaid");
|
|
31
|
+
const design_visualizer_1 = require("../../lib/di-graph/design-visualizer");
|
|
30
32
|
const model_1 = require("../../lib/di-graph/model");
|
|
31
33
|
const toError_1 = require("../../toError");
|
|
32
34
|
const RULE_NAME = 'di-graph';
|
|
@@ -83,9 +85,21 @@ function detectFrameworkMarkers(dir) {
|
|
|
83
85
|
});
|
|
84
86
|
return new analyzer_strategy_1.FrameworkMarkers(angular, controller);
|
|
85
87
|
}
|
|
86
|
-
|
|
88
|
+
/**
|
|
89
|
+
* Repo-relative back link from a project's committed design.html up to
|
|
90
|
+
* architecture/dependencies.html, so a reader who clicked a box in the
|
|
91
|
+
* architecture graph can click back out. E.g. 'packages/http/http-api' →
|
|
92
|
+
* '../../../architecture/dependencies.html'.
|
|
93
|
+
*/
|
|
94
|
+
function architectureBackHref(projectRoot) {
|
|
95
|
+
return path.posix.relative(projectRoot.replace(/\\/g, '/'), 'architecture/dependencies.html');
|
|
96
|
+
}
|
|
97
|
+
function writeDesignFiles(projectRootAbs, projectRoot, graph) {
|
|
98
|
+
// toDesignJson sorts the graph in place, so design.md/design.html below all
|
|
99
|
+
// see the same deterministic ordering (no git churn on re-run).
|
|
87
100
|
fs.writeFileSync(path.join(projectRootAbs, 'design.json'), (0, serializer_1.toDesignJson)(graph));
|
|
88
101
|
fs.writeFileSync(path.join(projectRootAbs, 'design.md'), (0, mermaid_1.toDesignMarkdown)(graph));
|
|
102
|
+
fs.writeFileSync(path.join(projectRootAbs, 'design.html'), (0, design_visualizer_1.generateDesignHTML)(graph, architectureBackHref(projectRoot)));
|
|
89
103
|
}
|
|
90
104
|
/** The analyzer chosen for a project plus the role tag that drove the choice. */
|
|
91
105
|
class AnalyzerChoice {
|
|
@@ -132,13 +146,13 @@ async function runExecutor(_options, context) {
|
|
|
132
146
|
try {
|
|
133
147
|
if (!sourceHasDiMarkers(srcDir)) {
|
|
134
148
|
console.log(' No DI markers found — writing empty design graph');
|
|
135
|
-
writeDesignFiles(projectRootAbs, new model_1.DiGraph(projectName));
|
|
149
|
+
writeDesignFiles(projectRootAbs, projectRoot, new model_1.DiGraph(projectName));
|
|
136
150
|
return { success: true };
|
|
137
151
|
}
|
|
138
152
|
const program = (0, program_1.createProjectProgram)(projectRootAbs);
|
|
139
153
|
if (!program) {
|
|
140
154
|
console.log(' No usable tsconfig/source — writing empty design graph');
|
|
141
|
-
writeDesignFiles(projectRootAbs, new model_1.DiGraph(projectName));
|
|
155
|
+
writeDesignFiles(projectRootAbs, projectRoot, new model_1.DiGraph(projectName));
|
|
142
156
|
return { success: true };
|
|
143
157
|
}
|
|
144
158
|
const choice = chooseAnalyzer(projectConfig?.tags ?? [], srcDir);
|
|
@@ -149,10 +163,10 @@ async function runExecutor(_options, context) {
|
|
|
149
163
|
reportDesignedLibMissingRoot(projectName);
|
|
150
164
|
return { success: false };
|
|
151
165
|
}
|
|
152
|
-
writeDesignFiles(projectRootAbs, graph);
|
|
166
|
+
writeDesignFiles(projectRootAbs, projectRoot, graph);
|
|
153
167
|
const nodeCount = graph.designs.reduce((sum, d) => sum + d.nodes.length, 0);
|
|
154
168
|
const edgeCount = graph.designs.reduce((sum, d) => sum + d.edges.length, 0);
|
|
155
|
-
console.log(`✅ Wrote ${projectRoot}/design.json + design.md ` +
|
|
169
|
+
console.log(`✅ Wrote ${projectRoot}/design.json + design.md + design.html ` +
|
|
156
170
|
`(${graph.designs.length} design(s), ${nodeCount} node(s), ${edgeCount} edge(s))`);
|
|
157
171
|
const unresolved = [...new Set(graph.designs.flatMap((d) => d.unresolved))];
|
|
158
172
|
if (unresolved.length > 0) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/di-graph-generate/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;AAuHH,8BA+DC;;AAnLD,0DAA0D;AAC1D,+CAAyB;AACzB,mDAA6B;AAC7B,4EAM8C;AAC9C,wDAAkE;AAClE,8DAA6D;AAC7D,wDAA8D;AAC9D,oDAA6D;AAC7D,2CAAwC;AAUxC,MAAM,SAAS,GAAG,UAAU,CAAC;AAE7B,gFAAgF;AAChF,uEAAuE;AACvE,gFAAgF;AAChF,sDAAsD;AACtD,MAAM,UAAU,GAAG;IACf,cAAc;IACd,qBAAqB;IACrB,mBAAmB;IACnB,mBAAmB;IACnB,aAAa;IACb,qBAAqB;IACrB,UAAU;IACV,aAAa;IACb,sBAAsB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AM,EAAE,CAAC,CAAC,CAAC;QAC9F,MAAM,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,GAAW,EAAE,CAAW,EAAE,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QAC9F,OAAO,CAAC,GAAG,CACP,WAAW,WAAW,2BAA2B;YAC7C,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,eAAe,SAAS,aAAa,SAAS,WAAW,CACxF,CAAC;QACF,MAAM,UAAU,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAW,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QACtF,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACxB,OAAO,CAAC,IAAI,CAAC,OAAO,UAAU,CAAC,MAAM,iCAAiC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACnG,CAAC;QACD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,iBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,OAAO,CAAC,KAAK,CAAC,oCAAoC,WAAW,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QACnF,OAAO,CAAC,KAAK,CAAC,oCAAoC,SAAS,yCAAyC,CAAC,CAAC;QACtG,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;AACL,CAAC","sourcesContent":["/**\n * DI Graph Generate Executor\n *\n * Per-project: statically analyzes the project's Inversify dependency DAG\n * (constructor injection from controllers — or library top-of-DAG classes —\n * down to leaves) and writes two checked-in files at the project root:\n *\n * design.json — machine-readable graph (deterministic, sorted)\n * design.md — Mermaid diagram rendered by GitHub/IDEs in PRs\n *\n * Runs on every build (cache:false; the build gates on\n * validate-di-graph-unchanged which dependsOn this target). Unrecognized DI\n * patterns become \"unresolved\" nodes rather than failing the build.\n *\n * Config (webpieces.config.json, rule key `di-graph`): mode RUN_EVERY_TIME | OFF.\n *\n * Usage: nx run <project>:di-graph-generate\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { loadAndValidate } from '@webpieces/rules-config';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n DiAnalyzer,\n explicitFrameworkTag,\n explicitRoleTag,\n FrameworkMarkers,\n selectAnalyzer,\n} from '../../lib/di-graph/analyzer-strategy';\nimport { createProjectProgram } from '../../lib/di-graph/program';\nimport { toDesignJson } from '../../lib/di-graph/serializer';\nimport { toDesignMarkdown } from '../../lib/di-graph/mermaid';\nimport { DiDesign, DiGraph } from '../../lib/di-graph/model';\nimport { toError } from '../../toError';\n\nexport interface DiGraphGenerateOptions {\n // No options here — config comes from webpieces.config.json at runtime.\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\nconst RULE_NAME = 'di-graph';\n\n// Cheap substring pre-scan: a project whose source never mentions any DI marker\n// gets an empty graph without paying for a ts.Program. Angular markers\n// (@Component/bootstrapApplication) are included so an Angular app that uses no\n// Inversify decorator isn't short-circuited to empty.\nconst DI_MARKERS = [\n '@Controller(',\n '@ApiImplementation(',\n '@provideSingleton',\n '@provideTransient',\n '@injectable',\n 'new ContainerModule',\n '@inject(',\n '@Component(',\n 'bootstrapApplication',\n];\n\nconst ANGULAR_MARKERS = ['@Component(', 'bootstrapApplication'];\nconst CONTROLLER_MARKER = '@Controller(';\n\n/** Recursively read every project .ts file, folding each into `visit`. */\nfunction forEachSourceFile(dir: string, visit: (content: string) => void): void {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name === 'node_modules' || entry.name === 'dist') continue;\n forEachSourceFile(full, visit);\n } else if (entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts')) {\n visit(fs.readFileSync(full, 'utf-8'));\n }\n }\n}\n\nfunction sourceHasDiMarkers(dir: string): boolean {\n let found = false;\n forEachSourceFile(dir, (content: string) => {\n if (!found && DI_MARKERS.some((marker: string) => content.includes(marker))) found = true;\n });\n return found;\n}\n\n/** Pre-scan a project's source for the framework markers used when no tag is set. */\nfunction detectFrameworkMarkers(dir: string): FrameworkMarkers {\n let angular = false;\n let controller = false;\n forEachSourceFile(dir, (content: string) => {\n if (!angular && ANGULAR_MARKERS.some((marker: string) => content.includes(marker))) angular = true;\n if (!controller && content.includes(CONTROLLER_MARKER)) controller = true;\n });\n return new FrameworkMarkers(angular, controller);\n}\n\nfunction writeDesignFiles(projectRootAbs: string, graph: DiGraph): void {\n fs.writeFileSync(path.join(projectRootAbs, 'design.json'), toDesignJson(graph));\n fs.writeFileSync(path.join(projectRootAbs, 'design.md'), toDesignMarkdown(graph));\n}\n\n/** The analyzer chosen for a project plus the role tag that drove the choice. */\nclass AnalyzerChoice {\n constructor(\n public readonly analyzer: DiAnalyzer,\n public readonly role: string | null,\n ) {}\n}\n\n/**\n * Select the analyzer by role (server→@Controller, designed-lib→@ApiImplementation,\n * client→angular design, lib→skip). The explicit `role:` nx tag is the source of\n * truth; when absent we fall back to the legacy `framework:` selection + marker\n * pre-scan so designs stay identical until a project is retagged.\n */\nfunction chooseAnalyzer(tags: string[], srcDir: string): AnalyzerChoice {\n const role = explicitRoleTag(tags);\n const framework = explicitFrameworkTag(tags);\n const analyzer = selectAnalyzer(role, framework, detectFrameworkMarkers(srcDir));\n console.log(\n ` Analyzer: ${analyzer.constructor.name} ` +\n `(role tag: ${role ?? 'none'}, framework tag: ${framework ?? 'none'})`,\n );\n return new AnalyzerChoice(analyzer, role);\n}\n\nfunction reportDesignedLibMissingRoot(projectName: string): void {\n console.error(\n `❌ ${projectName} is tagged role:designed-lib but has no @ApiImplementation class.\\n` +\n ` Annotate the library's top implementation class with @ApiImplementation ` +\n `(from @webpieces/http-routing), or retag the project role:lib if it has no design.`,\n );\n}\n\nexport default async function runExecutor(\n _options: DiGraphGenerateOptions,\n context: ExecutorContext,\n): Promise<ExecutorResult> {\n const shared = loadAndValidate(context.root).resolved;\n const rule = shared.rules.get(RULE_NAME);\n if (rule && rule.isOff) {\n console.log(`\\n⏭️ Skipping ${RULE_NAME} generation (mode: OFF)\\n`);\n return { success: true };\n }\n\n const projectName = context.projectName ?? 'project';\n const projectConfig = context.projectsConfigurations?.projects[projectName];\n const projectRoot = projectConfig?.root ?? '.';\n const projectRootAbs = path.join(context.root, projectRoot);\n const srcDir = path.join(projectRootAbs, 'src');\n\n console.log(`\\n🧬 Generating DI design graph for ${projectName}\\n`);\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- chokepoint: a generator crash must produce an actionable failure, not a stack trace mid-build\n try {\n if (!sourceHasDiMarkers(srcDir)) {\n console.log(' No DI markers found — writing empty design graph');\n writeDesignFiles(projectRootAbs, new DiGraph(projectName));\n return { success: true };\n }\n\n const program = createProjectProgram(projectRootAbs);\n if (!program) {\n console.log(' No usable tsconfig/source — writing empty design graph');\n writeDesignFiles(projectRootAbs, new DiGraph(projectName));\n return { success: true };\n }\n\n const choice = chooseAnalyzer(projectConfig?.tags ?? [], srcDir);\n const graph = choice.analyzer.analyzeProject(program, context.root, projectRoot, projectName);\n\n // A designed-lib MUST expose at least one @ApiImplementation root, else its\n // design would be empty and the tag is meaningless — fail loudly.\n if (choice.role === 'designed-lib' && graph.designs.length === 0) {\n reportDesignedLibMissingRoot(projectName);\n return { success: false };\n }\n\n writeDesignFiles(projectRootAbs, graph);\n\n const nodeCount = graph.designs.reduce((sum: number, d: DiDesign) => sum + d.nodes.length, 0);\n const edgeCount = graph.designs.reduce((sum: number, d: DiDesign) => sum + d.edges.length, 0);\n console.log(\n `✅ Wrote ${projectRoot}/design.json + design.md ` +\n `(${graph.designs.length} design(s), ${nodeCount} node(s), ${edgeCount} edge(s))`,\n );\n const unresolved = [...new Set(graph.designs.flatMap((d: DiDesign) => d.unresolved))];\n if (unresolved.length > 0) {\n console.warn(`⚠️ ${unresolved.length} unresolved token(s)/type(s): ${unresolved.join(', ')}`);\n }\n return { success: true };\n } catch (err: unknown) {\n const error = toError(err);\n console.error(`❌ DI graph generation failed for ${projectName}: ${error.message}`);\n console.error(` To unblock builds, set rules[\"${RULE_NAME}\"].mode=\"OFF\" in webpieces.config.json.`);\n return { success: false };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/di-graph-generate/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;GAkBG;;AAwIH,8BA+DC;;AApMD,0DAA0D;AAC1D,+CAAyB;AACzB,mDAA6B;AAC7B,4EAM8C;AAC9C,wDAAkE;AAClE,8DAA6D;AAC7D,wDAA8D;AAC9D,4EAA0E;AAC1E,oDAA6D;AAC7D,2CAAwC;AAUxC,MAAM,SAAS,GAAG,UAAU,CAAC;AAE7B,gFAAgF;AAChF,uEAAuE;AACvE,gFAAgF;AAChF,sDAAsD;AACtD,MAAM,UAAU,GAAG;IACf,cAAc;IACd,qBAAqB;IACrB,mBAAmB;IACnB,mBAAmB;IACnB,aAAa;IACb,qBAAqB;IACrB,UAAU;IACV,aAAa;IACb,sBAAsB;CACzB,CAAC;AAEF,MAAM,eAAe,GAAG,CAAC,aAAa,EAAE,sBAAsB,CAAC,CAAC;AAChE,MAAM,iBAAiB,GAAG,cAAc,CAAC;AAEzC,0EAA0E;AAC1E,SAAS,iBAAiB,CAAC,GAAW,EAAE,KAAgC;IACpE,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,OAAO;IAChC,KAAK,MAAM,KAAK,IAAI,EAAE,CAAC,WAAW,CAAC,GAAG,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;QAC/D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W,EAAE,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QAC9F,MAAM,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,GAAW,EAAE,CAAW,EAAE,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QAC9F,OAAO,CAAC,GAAG,CACP,WAAW,WAAW,yCAAyC;YAC3D,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,eAAe,SAAS,aAAa,SAAS,WAAW,CACxF,CAAC;QACF,MAAM,UAAU,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAW,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QACtF,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACxB,OAAO,CAAC,IAAI,CAAC,OAAO,UAAU,CAAC,MAAM,iCAAiC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACnG,CAAC;QACD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,iBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,OAAO,CAAC,KAAK,CAAC,oCAAoC,WAAW,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QACnF,OAAO,CAAC,KAAK,CAAC,oCAAoC,SAAS,yCAAyC,CAAC,CAAC;QACtG,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;AACL,CAAC","sourcesContent":["/**\n * DI Graph Generate Executor\n *\n * Per-project: statically analyzes the project's Inversify dependency DAG\n * (constructor injection from controllers — or library top-of-DAG classes —\n * down to leaves) and writes three checked-in files at the project root:\n *\n * design.json — machine-readable graph (deterministic, sorted)\n * design.md — Mermaid diagram rendered by GitHub/IDEs in PRs\n * design.html — clickable viz.js page (linked from architecture/dependencies.html)\n *\n * Runs on every build (cache:false; the build gates on\n * validate-di-graph-unchanged which dependsOn this target). Unrecognized DI\n * patterns become \"unresolved\" nodes rather than failing the build.\n *\n * Config (webpieces.config.json, rule key `di-graph`): mode RUN_EVERY_TIME | OFF.\n *\n * Usage: nx run <project>:di-graph-generate\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { loadAndValidate } from '@webpieces/rules-config';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n DiAnalyzer,\n explicitFrameworkTag,\n explicitRoleTag,\n FrameworkMarkers,\n selectAnalyzer,\n} from '../../lib/di-graph/analyzer-strategy';\nimport { createProjectProgram } from '../../lib/di-graph/program';\nimport { toDesignJson } from '../../lib/di-graph/serializer';\nimport { toDesignMarkdown } from '../../lib/di-graph/mermaid';\nimport { generateDesignHTML } from '../../lib/di-graph/design-visualizer';\nimport { DiDesign, DiGraph } from '../../lib/di-graph/model';\nimport { toError } from '../../toError';\n\nexport interface DiGraphGenerateOptions {\n // No options here — config comes from webpieces.config.json at runtime.\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\nconst RULE_NAME = 'di-graph';\n\n// Cheap substring pre-scan: a project whose source never mentions any DI marker\n// gets an empty graph without paying for a ts.Program. Angular markers\n// (@Component/bootstrapApplication) are included so an Angular app that uses no\n// Inversify decorator isn't short-circuited to empty.\nconst DI_MARKERS = [\n '@Controller(',\n '@ApiImplementation(',\n '@provideSingleton',\n '@provideTransient',\n '@injectable',\n 'new ContainerModule',\n '@inject(',\n '@Component(',\n 'bootstrapApplication',\n];\n\nconst ANGULAR_MARKERS = ['@Component(', 'bootstrapApplication'];\nconst CONTROLLER_MARKER = '@Controller(';\n\n/** Recursively read every project .ts file, folding each into `visit`. */\nfunction forEachSourceFile(dir: string, visit: (content: string) => void): void {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name === 'node_modules' || entry.name === 'dist') continue;\n forEachSourceFile(full, visit);\n } else if (entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts')) {\n visit(fs.readFileSync(full, 'utf-8'));\n }\n }\n}\n\nfunction sourceHasDiMarkers(dir: string): boolean {\n let found = false;\n forEachSourceFile(dir, (content: string) => {\n if (!found && DI_MARKERS.some((marker: string) => content.includes(marker))) found = true;\n });\n return found;\n}\n\n/** Pre-scan a project's source for the framework markers used when no tag is set. */\nfunction detectFrameworkMarkers(dir: string): FrameworkMarkers {\n let angular = false;\n let controller = false;\n forEachSourceFile(dir, (content: string) => {\n if (!angular && ANGULAR_MARKERS.some((marker: string) => content.includes(marker))) angular = true;\n if (!controller && content.includes(CONTROLLER_MARKER)) controller = true;\n });\n return new FrameworkMarkers(angular, controller);\n}\n\n/**\n * Repo-relative back link from a project's committed design.html up to\n * architecture/dependencies.html, so a reader who clicked a box in the\n * architecture graph can click back out. E.g. 'packages/http/http-api' →\n * '../../../architecture/dependencies.html'.\n */\nfunction architectureBackHref(projectRoot: string): string {\n return path.posix.relative(projectRoot.replace(/\\\\/g, '/'), 'architecture/dependencies.html');\n}\n\nfunction writeDesignFiles(projectRootAbs: string, projectRoot: string, graph: DiGraph): void {\n // toDesignJson sorts the graph in place, so design.md/design.html below all\n // see the same deterministic ordering (no git churn on re-run).\n fs.writeFileSync(path.join(projectRootAbs, 'design.json'), toDesignJson(graph));\n fs.writeFileSync(path.join(projectRootAbs, 'design.md'), toDesignMarkdown(graph));\n fs.writeFileSync(\n path.join(projectRootAbs, 'design.html'),\n generateDesignHTML(graph, architectureBackHref(projectRoot)),\n );\n}\n\n/** The analyzer chosen for a project plus the role tag that drove the choice. */\nclass AnalyzerChoice {\n constructor(\n public readonly analyzer: DiAnalyzer,\n public readonly role: string | null,\n ) {}\n}\n\n/**\n * Select the analyzer by role (server→@Controller, designed-lib→@ApiImplementation,\n * client→angular design, lib→skip). The explicit `role:` nx tag is the source of\n * truth; when absent we fall back to the legacy `framework:` selection + marker\n * pre-scan so designs stay identical until a project is retagged.\n */\nfunction chooseAnalyzer(tags: string[], srcDir: string): AnalyzerChoice {\n const role = explicitRoleTag(tags);\n const framework = explicitFrameworkTag(tags);\n const analyzer = selectAnalyzer(role, framework, detectFrameworkMarkers(srcDir));\n console.log(\n ` Analyzer: ${analyzer.constructor.name} ` +\n `(role tag: ${role ?? 'none'}, framework tag: ${framework ?? 'none'})`,\n );\n return new AnalyzerChoice(analyzer, role);\n}\n\nfunction reportDesignedLibMissingRoot(projectName: string): void {\n console.error(\n `❌ ${projectName} is tagged role:designed-lib but has no @ApiImplementation class.\\n` +\n ` Annotate the library's top implementation class with @ApiImplementation ` +\n `(from @webpieces/http-routing), or retag the project role:lib if it has no design.`,\n );\n}\n\nexport default async function runExecutor(\n _options: DiGraphGenerateOptions,\n context: ExecutorContext,\n): Promise<ExecutorResult> {\n const shared = loadAndValidate(context.root).resolved;\n const rule = shared.rules.get(RULE_NAME);\n if (rule && rule.isOff) {\n console.log(`\\n⏭️ Skipping ${RULE_NAME} generation (mode: OFF)\\n`);\n return { success: true };\n }\n\n const projectName = context.projectName ?? 'project';\n const projectConfig = context.projectsConfigurations?.projects[projectName];\n const projectRoot = projectConfig?.root ?? '.';\n const projectRootAbs = path.join(context.root, projectRoot);\n const srcDir = path.join(projectRootAbs, 'src');\n\n console.log(`\\n🧬 Generating DI design graph for ${projectName}\\n`);\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- chokepoint: a generator crash must produce an actionable failure, not a stack trace mid-build\n try {\n if (!sourceHasDiMarkers(srcDir)) {\n console.log(' No DI markers found — writing empty design graph');\n writeDesignFiles(projectRootAbs, projectRoot, new DiGraph(projectName));\n return { success: true };\n }\n\n const program = createProjectProgram(projectRootAbs);\n if (!program) {\n console.log(' No usable tsconfig/source — writing empty design graph');\n writeDesignFiles(projectRootAbs, projectRoot, new DiGraph(projectName));\n return { success: true };\n }\n\n const choice = chooseAnalyzer(projectConfig?.tags ?? [], srcDir);\n const graph = choice.analyzer.analyzeProject(program, context.root, projectRoot, projectName);\n\n // A designed-lib MUST expose at least one @ApiImplementation root, else its\n // design would be empty and the tag is meaningless — fail loudly.\n if (choice.role === 'designed-lib' && graph.designs.length === 0) {\n reportDesignedLibMissingRoot(projectName);\n return { success: false };\n }\n\n writeDesignFiles(projectRootAbs, projectRoot, graph);\n\n const nodeCount = graph.designs.reduce((sum: number, d: DiDesign) => sum + d.nodes.length, 0);\n const edgeCount = graph.designs.reduce((sum: number, d: DiDesign) => sum + d.edges.length, 0);\n console.log(\n `✅ Wrote ${projectRoot}/design.json + design.md + design.html ` +\n `(${graph.designs.length} design(s), ${nodeCount} node(s), ${edgeCount} edge(s))`,\n );\n const unresolved = [...new Set(graph.designs.flatMap((d: DiDesign) => d.unresolved))];\n if (unresolved.length > 0) {\n console.warn(`⚠️ ${unresolved.length} unresolved token(s)/type(s): ${unresolved.join(', ')}`);\n }\n return { success: true };\n } catch (err: unknown) {\n const error = toError(err);\n console.error(`❌ DI graph generation failed for ${projectName}: ${error.message}`);\n console.error(` To unblock builds, set rules[\"${RULE_NAME}\"].mode=\"OFF\" in webpieces.config.json.`);\n return { success: false };\n }\n}\n"]}
|
|
@@ -14,6 +14,7 @@ const graph_generator_1 = require("../../lib/graph-generator");
|
|
|
14
14
|
const graph_sorter_1 = require("../../lib/graph-sorter");
|
|
15
15
|
const graph_loader_1 = require("../../lib/graph-loader");
|
|
16
16
|
const graph_metadata_1 = require("../../lib/graph-metadata");
|
|
17
|
+
const graph_visualizer_1 = require("../../lib/graph-visualizer");
|
|
17
18
|
const runtime_markers_1 = require("../../lib/runtime-markers");
|
|
18
19
|
const runtime_graph_1 = require("../../lib/runtime-graph");
|
|
19
20
|
const runtime_config_1 = require("../../lib/runtime-config");
|
|
@@ -58,6 +59,10 @@ async function runExecutor(options, context) {
|
|
|
58
59
|
console.log('💾 Saving graph to architecture/dependencies.json...');
|
|
59
60
|
(0, graph_loader_1.saveGraph)(enhancedGraph, workspaceRoot, graphPath);
|
|
60
61
|
console.log('✅ Graph saved successfully');
|
|
62
|
+
// Step 4b: Write the committed, clickable HTML view next to the JSON so
|
|
63
|
+
// dependencies.html regenerates in lock-step with dependencies.json.
|
|
64
|
+
const vizPaths = (0, graph_visualizer_1.writeVisualization)(enhancedGraph, workspaceRoot);
|
|
65
|
+
console.log(`✅ Wrote ${vizPaths.htmlPath}`);
|
|
61
66
|
// Step 5: Generate the runtime microservice graph at the same time
|
|
62
67
|
await generateRuntimeGraph(workspaceRoot);
|
|
63
68
|
// Print summary
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/generate/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;
|
|
1
|
+
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/generate/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;AA2CH,8BAyDC;AAjGD,0DAAwD;AACxD,+DAAiE;AACjE,yDAAgE;AAChE,yDAAmD;AACnD,6DAAoG;AACpG,iEAAgE;AAChE,+DAAgE;AAChE,2DAAiF;AACjF,6DAA6D;AAC7D,2CAAwC;AAUxC;;;;GAIG;AACH,KAAK,UAAU,oBAAoB,CAAC,aAAqB;IACrD,MAAM,MAAM,GAAG,IAAA,kCAAiB,EAAC,aAAa,CAAC,CAAC;IAChD,IAAI,MAAM,CAAC,GAAG,IAAI,MAAM,CAAC,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACjD,OAAO,CAAC,GAAG,CAAC,yEAAyE,CAAC,CAAC;QACvF,OAAO;IACX,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,iEAAiE,CAAC,CAAC;IAC/E,MAAM,KAAK,G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AC,KAAK,CAAC,mBAAmB,GAAG,MAAM,GAAG,qDAAqD,CAAC,CAAC;QACxG,CAAC;QACD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;AACL,CAAC","sourcesContent":["/**\n * Generate Executor\n *\n * Generates the architecture dependency graph and saves it to architecture/dependencies.json.\n *\n * Usage:\n * nx run architecture:generate\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { writeTemplate } from '@webpieces/rules-config';\nimport { generateReducedGraph } from '../../lib/graph-generator';\nimport { sortGraphTopologically } from '../../lib/graph-sorter';\nimport { saveGraph } from '../../lib/graph-loader';\nimport { collectProjectInfo, enrichGraph, MetadataValidationError } from '../../lib/graph-metadata';\nimport { writeVisualization } from '../../lib/graph-visualizer';\nimport { buildWorkspaceModel } from '../../lib/runtime-markers';\nimport { assembleRuntimeGraph, saveRuntimeGraph } from '../../lib/runtime-graph';\nimport { loadRuntimeConfig } from '../../lib/runtime-config';\nimport { toError } from '../../toError';\n\nexport interface GenerateExecutorOptions {\n graphPath?: string;\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\n/**\n * Generate the runtime microservice graph alongside the compile-time graph, so\n * one regenerate produces both committed files. Skipped when the\n * runtime-architecture rule is OFF or no apiProjectPaths are configured.\n */\nasync function generateRuntimeGraph(workspaceRoot: string): Promise<void> {\n const config = loadRuntimeConfig(workspaceRoot);\n if (config.off || config.servicePaths.length === 0) {\n console.log('⏭️ Runtime graph skipped (runtime-architecture OFF or no servicePaths)');\n return;\n }\n console.log('📡 Generating runtime graph from service-contract.json files...');\n const model = await buildWorkspaceModel(workspaceRoot, config.apiProjectPaths, config.servicePaths);\n const runtimeGraph = assembleRuntimeGraph(model, workspaceRoot);\n saveRuntimeGraph(runtimeGraph, workspaceRoot);\n const serviceCount = Object.keys(runtimeGraph.services).length;\n console.log(\n `✅ Runtime graph saved (${serviceCount} services, ${runtimeGraph.runtimeEdges.length} runtime edges)`,\n );\n}\n\nexport default async function runExecutor(\n options: GenerateExecutorOptions,\n context: ExecutorContext\n): Promise<ExecutorResult> {\n const graphPath = options.graphPath;\n const workspaceRoot = context.root;\n\n console.log('\\n📊 Architecture Graph Generator\\n');\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // Step 1: Build the full graph from nx, then transitively reduce it to the view\n console.log(\"📊 Generating dependency graph from nx's project graph...\");\n const reducedGraph = await generateReducedGraph();\n\n // Step 2: Topological sort (to assign levels for visualization)\n console.log('🔄 Computing topological layers...');\n const enhancedGraph = sortGraphTopologically(reducedGraph);\n\n // Step 3: Enrich with AI metadata (framework, shortDescription, file\n // pointers). This VALIDATES (responsibilities.md required per project)\n // and throws before any write, so a failure never clobbers the file.\n console.log('🏷️ Enriching graph with framework + responsibilities metadata...');\n const projectInfos = await collectProjectInfo();\n enrichGraph(enhancedGraph, projectInfos, workspaceRoot);\n\n // Step 4: Save the graph\n console.log('💾 Saving graph to architecture/dependencies.json...');\n saveGraph(enhancedGraph, workspaceRoot, graphPath);\n console.log('✅ Graph saved successfully');\n\n // Step 4b: Write the committed, clickable HTML view next to the JSON so\n // dependencies.html regenerates in lock-step with dependencies.json.\n const vizPaths = writeVisualization(enhancedGraph, workspaceRoot);\n console.log(`✅ Wrote ${vizPaths.htmlPath}`);\n\n // Step 5: Generate the runtime microservice graph at the same time\n await generateRuntimeGraph(workspaceRoot);\n\n // Print summary\n const projectCount = Object.keys(enhancedGraph).length;\n const levels = new Set(Object.values(enhancedGraph).map((e) => e.level));\n console.log(`\\n📈 Graph Summary:`);\n console.log(` Projects: ${projectCount}`);\n console.log(` Levels: ${levels.size} (0-${Math.max(...levels)})`);\n\n return { success: true };\n } catch (err: unknown) {\n const error = toError(err);\n console.error('❌ Graph generation failed:', error.message);\n if (error instanceof MetadataValidationError) {\n const mdPath = writeTemplate(workspaceRoot, 'webpieces.responsibilities.md');\n console.error('');\n console.error('⚠️ *** Refer to ' + mdPath + ' for how to author responsibilities.md files *** ⚠️');\n }\n return { success: false };\n }\n}\n"]}
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
* Validate DI Graph Unchanged Executor
|
|
3
3
|
*
|
|
4
4
|
* Per-project gate that runs AFTER di-graph-generate (via target dependsOn):
|
|
5
|
-
* once the generator has rewritten design.json/design.md, this
|
|
6
|
-
* git whether the files differ from the committed copies. Any difference —
|
|
5
|
+
* once the generator has rewritten design.json/design.md/design.html, this
|
|
6
|
+
* executor asks git whether the files differ from the committed copies. Any difference —
|
|
7
7
|
* modified OR brand-new/untracked — fails the build with a "commit the
|
|
8
8
|
* regenerated files" remediation, so the checked-in DI design DAG can never
|
|
9
9
|
* go stale on main.
|
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
* Validate DI Graph Unchanged Executor
|
|
4
4
|
*
|
|
5
5
|
* Per-project gate that runs AFTER di-graph-generate (via target dependsOn):
|
|
6
|
-
* once the generator has rewritten design.json/design.md, this
|
|
7
|
-
* git whether the files differ from the committed copies. Any difference —
|
|
6
|
+
* once the generator has rewritten design.json/design.md/design.html, this
|
|
7
|
+
* executor asks git whether the files differ from the committed copies. Any difference —
|
|
8
8
|
* modified OR brand-new/untracked — fails the build with a "commit the
|
|
9
9
|
* regenerated files" remediation, so the checked-in DI design DAG can never
|
|
10
10
|
* go stale on main.
|
|
@@ -25,7 +25,7 @@ const child_process_1 = require("child_process");
|
|
|
25
25
|
const path = tslib_1.__importStar(require("path"));
|
|
26
26
|
const toError_1 = require("../../toError");
|
|
27
27
|
const RULE_NAME = 'di-graph';
|
|
28
|
-
const DESIGN_FILES = ['design.json', 'design.md'];
|
|
28
|
+
const DESIGN_FILES = ['design.json', 'design.md', 'design.html'];
|
|
29
29
|
function gitStatusPorcelain(workspaceRoot, projectRoot) {
|
|
30
30
|
const paths = DESIGN_FILES.map((file) => path.posix.join(projectRoot, file));
|
|
31
31
|
const output = (0, child_process_1.execFileSync)('git', ['status', '--porcelain', '--', ...paths], {
|
|
@@ -42,8 +42,8 @@ function reportStale(projectName, projectRoot, status) {
|
|
|
42
42
|
}
|
|
43
43
|
console.error('\nThe DI dependency DAG changed (a constructor/binding was added, removed,');
|
|
44
44
|
console.error('or rewired). To fix:');
|
|
45
|
-
console.error(` 1. Review the diff: git diff -- ${projectRoot}/design.json ${projectRoot}/design.md`);
|
|
46
|
-
console.error(' 2. If intentional, commit the regenerated design.json + design.md');
|
|
45
|
+
console.error(` 1. Review the diff: git diff -- ${projectRoot}/design.json ${projectRoot}/design.md ${projectRoot}/design.html`);
|
|
46
|
+
console.error(' 2. If intentional, commit the regenerated design.json + design.md + design.html');
|
|
47
47
|
console.error(` 3. To turn this gate off, set rules["${RULE_NAME}"].mode="OFF" in webpieces.config.json\n`);
|
|
48
48
|
}
|
|
49
49
|
async function runExecutor(_options, context) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/validate-di-graph-unchanged/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;AAyCH,8BA0CC;;AAhFD,0DAA0E;AAC1E,iDAA6C;AAC7C,mDAA6B;AAC7B,2CAAwC;AAUxC,MAAM,SAAS,GAAG,UAAU,CAAC;AAC7B,MAAM,YAAY,GAAG,CAAC,aAAa,EAAE,WAAW,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/validate-di-graph-unchanged/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;AAyCH,8BA0CC;;AAhFD,0DAA0E;AAC1E,iDAA6C;AAC7C,mDAA6B;AAC7B,2CAAwC;AAUxC,MAAM,SAAS,GAAG,UAAU,CAAC;AAC7B,MAAM,YAAY,GAAG,CAAC,aAAa,EAAE,WAAW,EAAE,aAAa,CAAC,CAAC;AAEjE,SAAS,kBAAkB,CAAC,aAAqB,EAAE,WAAmB;IAClE,MAAM,K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C,CAAC;IAC3C,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;QACZ,OAAO,CAAC,GAAG,CAAC,KAAK,SAAS,KAAK,IAAI,CAAC,MAAM,mDAAmD,CAAC,CAAC;QAC/F,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["/**\n * Validate DI Graph Unchanged Executor\n *\n * Per-project gate that runs AFTER di-graph-generate (via target dependsOn):\n * once the generator has rewritten design.json/design.md/design.html, this\n * executor asks git whether the files differ from the committed copies. Any difference —\n * modified OR brand-new/untracked — fails the build with a \"commit the\n * regenerated files\" remediation, so the checked-in DI design DAG can never\n * go stale on main.\n *\n * Uses `git status --porcelain` (not `git diff --quiet`) so first-time\n * untracked design files also fail CI instead of slipping through.\n *\n * Config (webpieces.config.json, rule key `di-graph`): mode OFF disables;\n * ignoreModifiedUntilEpoch / ignoreRuleWhileOnBranch report but pass.\n *\n * Usage: nx run <project>:validate-di-graph-unchanged\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { loadAndValidate, shouldSkipRule } from '@webpieces/rules-config';\nimport { execFileSync } from 'child_process';\nimport * as path from 'path';\nimport { toError } from '../../toError';\n\nexport interface ValidateDiGraphUnchangedOptions {\n // No options here — config comes from webpieces.config.json at runtime.\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\nconst RULE_NAME = 'di-graph';\nconst DESIGN_FILES = ['design.json', 'design.md', 'design.html'];\n\nfunction gitStatusPorcelain(workspaceRoot: string, projectRoot: string): string {\n const paths = DESIGN_FILES.map((file: string) => path.posix.join(projectRoot, file));\n const output = execFileSync('git', ['status', '--porcelain', '--', ...paths], {\n cwd: workspaceRoot,\n encoding: 'utf-8',\n });\n return output.trim();\n}\n\nfunction reportStale(projectName: string, projectRoot: string, status: string): void {\n console.error(`\\n❌ DI design graph is stale for ${projectName}!`);\n console.error('\\nThe regenerated design files differ from the committed copies:');\n for (const line of status.split('\\n')) {\n console.error(` ${line}`);\n }\n console.error('\\nThe DI dependency DAG changed (a constructor/binding was added, removed,');\n console.error('or rewired). To fix:');\n console.error(` 1. Review the diff: git diff -- ${projectRoot}/design.json ${projectRoot}/design.md ${projectRoot}/design.html`);\n console.error(' 2. If intentional, commit the regenerated design.json + design.md + design.html');\n console.error(` 3. To turn this gate off, set rules[\"${RULE_NAME}\"].mode=\"OFF\" in webpieces.config.json\\n`);\n}\n\nexport default async function runExecutor(\n _options: ValidateDiGraphUnchangedOptions,\n context: ExecutorContext,\n): Promise<ExecutorResult> {\n const shared = loadAndValidate(context.root).resolved;\n const rule = shared.rules.get(RULE_NAME);\n if (rule && rule.isOff) {\n console.log(`\\n⏭️ Skipping validate-di-graph-unchanged (mode: OFF)\\n`);\n return { success: true };\n }\n\n const projectName = context.projectName ?? 'project';\n const projectConfig = context.projectsConfigurations?.projects[projectName];\n const projectRoot = projectConfig?.root ?? '.';\n\n console.log(`\\n🔍 Validating DI design graph unchanged for ${projectName}\\n`);\n\n let status: string;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- chokepoint: outside a git repo the gate warns and passes instead of crashing the build\n try {\n status = gitStatusPorcelain(context.root, projectRoot);\n } catch (err: unknown) {\n const error = toError(err);\n console.warn(`⚠️ Could not check git status (${error.message}) — skipping gate`);\n return { success: true };\n }\n\n if (status === '') {\n console.log('✅ DI design graph matches the committed design.json/design.md\\n');\n return { success: true };\n }\n\n reportStale(projectName, projectRoot, status);\n\n const epoch = rule?.options['ignoreModifiedUntilEpoch'] as number | undefined;\n const branch = rule?.options['ignoreRuleWhileOnBranch'] as string | undefined;\n const skip = shouldSkipRule(epoch, branch);\n if (skip.skip) {\n console.log(`⏳ ${RULE_NAME}: ${skip.reason}. Staleness reported but NOT failing the build.\\n`);\n return { success: true };\n }\n return { success: false };\n}\n"]}
|
|
@@ -31,7 +31,6 @@ async function runExecutor(options, context) {
|
|
|
31
31
|
// Generate visualization
|
|
32
32
|
console.log('🎨 Generating visualization...');
|
|
33
33
|
const vizPaths = (0, graph_visualizer_1.writeVisualization)(graph, workspaceRoot);
|
|
34
|
-
console.log(`✅ Generated: ${vizPaths.dotPath}`);
|
|
35
34
|
console.log(`✅ Generated: ${vizPaths.htmlPath}`);
|
|
36
35
|
// Try to open in browser
|
|
37
36
|
console.log('\n🌐 Opening visualization in browser...');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/visualize/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;AAeH,
|
|
1
|
+
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/visualize/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;AAeH,8BAyCC;AArDD,yDAA0D;AAC1D,iEAAmF;AACnF,2CAAwC;AAUzB,KAAK,UAAU,WAAW,CACrC,OAAiC,EACjC,OAAwB;IAExB,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;IACpC,MAAM,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;IAEnC,OAAO,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;IAEjD,8DAA8D;IAC9D,IAAI,CAAC;QACD,uBAAuB;QACvB,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;QACzC,MAAM,SAAS,GAAG,IAAA,+BAAgB,EAAC,aAAa,EAAE,SAAS,CAAC,CAAC;QAE7D,IAAI,CAAC,SAAS,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,0DAA0D,CAAC,CAAC;YAC1E,OAAO,CAAC,KAAK,CAAC,4CAA4C,CAAC,CAAC;YAC5D,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;QAC9B,CAAC;QACD,MAAM,KAAK,GAAG,SAAS,CAAC,QAAQ,CAAC;QAEjC,yBAAyB;QACzB,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;QAC9C,MAAM,QAAQ,GAAG,IAAA,qCAAkB,EAAC,KAAK,EAAE,aAAa,CAAC,CAAC;QAC1D,OAAO,CAAC,GAAG,CAAC,gBAAgB,QAAQ,CAAC,QAAQ,EAAE,CAAC,CAAC;QAEjD,yBAAyB;QACzB,OAAO,CAAC,GAAG,CAAC,0CAA0C,CAAC,CAAC;QACxD,IAAI,IAAA,oCAAiB,EAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;YACvC,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;QACpC,CAAC;aAAM,CAAC;YACJ,OAAO,CAAC,GAAG,CAAC,2CAA2C,QAAQ,CAAC,QAAQ,EAAE,CAAC,CAAC;QAChF,CAAC;QAED,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,iBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QACxD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;AACL,CAAC","sourcesContent":["/**\n * Visualize Executor\n *\n * Generates visual representations of the architecture graph (DOT + HTML)\n * and opens the visualization in a browser.\n *\n * Usage:\n * nx run architecture:visualize\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { loadBlessedGraph } from '../../lib/graph-loader';\nimport { writeVisualization, openVisualization } from '../../lib/graph-visualizer';\nimport { toError } from '../../toError';\n\nexport interface VisualizeExecutorOptions {\n graphPath?: string;\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\nexport default async function runExecutor(\n options: VisualizeExecutorOptions,\n context: ExecutorContext\n): Promise<ExecutorResult> {\n const graphPath = options.graphPath;\n const workspaceRoot = context.root;\n\n console.log('\\n🎨 Architecture Visualization\\n');\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // Load the saved graph\n console.log('📂 Loading saved graph...');\n const graphFile = loadBlessedGraph(workspaceRoot, graphPath);\n\n if (!graphFile) {\n console.error('❌ No saved graph found at architecture/dependencies.json');\n console.error(' Run: nx run architecture:generate first');\n return { success: false };\n }\n const graph = graphFile.projects;\n\n // Generate visualization\n console.log('🎨 Generating visualization...');\n const vizPaths = writeVisualization(graph, workspaceRoot);\n console.log(`✅ Generated: ${vizPaths.htmlPath}`);\n\n // Try to open in browser\n console.log('\\n🌐 Opening visualization in browser...');\n if (openVisualization(vizPaths.htmlPath)) {\n console.log('✅ Browser opened');\n } else {\n console.log(`⚠️ Could not auto-open. Open manually: ${vizPaths.htmlPath}`);\n }\n\n return { success: true };\n } catch (err: unknown) {\n const error = toError(err);\n console.error('❌ Visualization failed:', error.message);\n return { success: false };\n }\n}\n"]}
|
|
@@ -15,8 +15,12 @@ export declare class DesignVisualizationPaths {
|
|
|
15
15
|
/**
|
|
16
16
|
* Build the full HTML page for a project's DI designs — one section (heading
|
|
17
17
|
* + meta + rendered graph) per controller/root design.
|
|
18
|
+
*
|
|
19
|
+
* `backHref`, when given, renders a "back to architecture" link at the top —
|
|
20
|
+
* used by the committed per-project design.html so a reader who clicked in from
|
|
21
|
+
* dependencies.html can click back out. Omitted for the tmp view.
|
|
18
22
|
*/
|
|
19
|
-
export declare function generateDesignHTML(graph: DiGraph): string;
|
|
23
|
+
export declare function generateDesignHTML(graph: DiGraph, backHref?: string): string;
|
|
20
24
|
/**
|
|
21
25
|
* Write tmp/webpieces/design-<project>.html (+ .dot with all digraphs
|
|
22
26
|
* concatenated, for debugging) and return the paths.
|
|
@@ -40,6 +40,9 @@ function pageStyles() {
|
|
|
40
40
|
return `
|
|
41
41
|
body { margin: 0; padding: 20px; font-family: Arial, sans-serif; background: #f5f5f5; }
|
|
42
42
|
h1 { text-align: center; color: #333; }
|
|
43
|
+
.back { max-width: 95%; margin: 0 auto 8px; }
|
|
44
|
+
.back a { color: #1565C0; text-decoration: none; }
|
|
45
|
+
.back a:hover { text-decoration: underline; }
|
|
43
46
|
h2 { color: #333; margin-bottom: 4px; }
|
|
44
47
|
.meta { color: #777; font-family: monospace; font-size: 13px; margin-bottom: 10px; }
|
|
45
48
|
.section { background: white; padding: 20px; border-radius: 8px;
|
|
@@ -85,11 +88,18 @@ function renderScript(entries) {
|
|
|
85
88
|
/**
|
|
86
89
|
* Build the full HTML page for a project's DI designs — one section (heading
|
|
87
90
|
* + meta + rendered graph) per controller/root design.
|
|
91
|
+
*
|
|
92
|
+
* `backHref`, when given, renders a "back to architecture" link at the top —
|
|
93
|
+
* used by the committed per-project design.html so a reader who clicked in from
|
|
94
|
+
* dependencies.html can click back out. Omitted for the tmp view.
|
|
88
95
|
*/
|
|
89
|
-
function generateDesignHTML(graph) {
|
|
96
|
+
function generateDesignHTML(graph, backHref) {
|
|
90
97
|
const title = `DI Designs — ${graph.project}`;
|
|
91
98
|
const entries = [];
|
|
92
99
|
const sections = [];
|
|
100
|
+
const backLink = backHref
|
|
101
|
+
? `<p class="back"><a href="${htmlEscape(backHref)}">← Back to architecture graph</a></p>`
|
|
102
|
+
: '';
|
|
93
103
|
graph.designs.forEach((design, index) => {
|
|
94
104
|
const id = `graph-${index}`;
|
|
95
105
|
entries.push(new DesignGraphEntry(id, (0, dot_1.generateDesignDot)(design)));
|
|
@@ -105,12 +115,14 @@ function generateDesignHTML(graph) {
|
|
|
105
115
|
return `<!DOCTYPE html>
|
|
106
116
|
<html>
|
|
107
117
|
<head>
|
|
118
|
+
<meta charset="utf-8">
|
|
108
119
|
<title>${htmlEscape(title)}</title>
|
|
109
120
|
<script src="https://cdn.jsdelivr.net/npm/viz.js@2.1.2/viz.js"></script>
|
|
110
121
|
<script src="https://cdn.jsdelivr.net/npm/viz.js@2.1.2/full.render.js"></script>
|
|
111
122
|
<style>${pageStyles()}</style>
|
|
112
123
|
</head>
|
|
113
124
|
<body>
|
|
125
|
+
${backLink}
|
|
114
126
|
<h1>${htmlEscape(title)}</h1>
|
|
115
127
|
${pageLegend()}
|
|
116
128
|
${body}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"design-visualizer.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/lib/di-graph/design-visualizer.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;
|
|
1
|
+
{"version":3,"file":"design-visualizer.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/lib/di-graph/design-visualizer.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AAsFH,gDAwCC;AAMD,4DAmBC;;AArJD,+CAAyB;AACzB,mDAA6B;AAE7B,6CAAyC;AACzC,+BAA0C;AAE1C,MAAa,wBAAwB;IAEb;IACA;IAFpB,YACoB,OAAe,EACf,QAAgB;QADhB,YAAO,GAAP,OAAO,CAAQ;QACf,aAAQ,GAAR,QAAQ,CAAQ;IACjC,CAAC;CACP;AALD,4DAKC;AAED,MAAM,gBAAgB;IAEE;IACA;IAFpB,YACoB,EAAU,EACV,GAAW;QADX,OAAE,GAAF,EAAE,CAAQ;QACV,QAAG,GAAH,GAAG,CAAQ;IAC5B,CAAC;CACP;AAED,SAAS,UAAU,CAAC,IAAY;IAC5B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AACnF,CAAC;AAED,SAAS,UAAU;IACf,OAAO;;;;;;;;;;;;;;;;KAgBN,CAAC;AACN,CAAC;AAED,SAAS,UAAU;IACf,OAAO;;;;;;;;;;;;;WAaA,CAAC;AACZ,CAAC;AAED,SAAS,YAAY,CAAC,OAA2B;IAC7C,OAAO;yBACc,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC;;;;;;;;;;KAU3C,CAAC;A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C,CAAC;IAEjB,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,KAAK,EAAE,WAAW,CAAC,CAAC;IAC/D,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;QAC5B,EAAE,CAAC,SAAS,CAAC,SAAS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IACjD,CAAC;IAED,MAAM,MAAM,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAgB,EAAE,EAAE,CAAC,IAAA,uBAAiB,EAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC7F,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,UAAU,KAAK,CAAC,OAAO,MAAM,CAAC,CAAC;IACpE,EAAE,CAAC,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IAE3C,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,UAAU,KAAK,CAAC,OAAO,OAAO,CAAC,CAAC;IACtE,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,kBAAkB,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC;IAE/D,OAAO,IAAI,wBAAwB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["/**\n * DI Design HTML Visualizer\n *\n * Builds one HTML page per project showing EVERY controller/root design as\n * its own Graphviz graph (rendered client-side with viz.js, same pipeline as\n * the architecture visualization). Output goes to tmp/webpieces/ — a view,\n * never committed (the committed artifacts are design.json/design.md).\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { DiDesign, DiGraph } from './model';\nimport { sortGraph } from './serializer';\nimport { generateDesignDot } from './dot';\n\nexport class DesignVisualizationPaths {\n constructor(\n public readonly dotPath: string,\n public readonly htmlPath: string\n ) {}\n}\n\nclass DesignGraphEntry {\n constructor(\n public readonly id: string,\n public readonly dot: string\n ) {}\n}\n\nfunction htmlEscape(text: string): string {\n return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n}\n\nfunction pageStyles(): string {\n return `\n body { margin: 0; padding: 20px; font-family: Arial, sans-serif; background: #f5f5f5; }\n h1 { text-align: center; color: #333; }\n .back { max-width: 95%; margin: 0 auto 8px; }\n .back a { color: #1565C0; text-decoration: none; }\n .back a:hover { text-decoration: underline; }\n h2 { color: #333; margin-bottom: 4px; }\n .meta { color: #777; font-family: monospace; font-size: 13px; margin-bottom: 10px; }\n .section { background: white; padding: 20px; border-radius: 8px;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin: 20px auto; max-width: 95%; }\n .graph { text-align: center; overflow-x: auto; }\n .legend { margin: 20px auto; max-width: 700px; padding: 15px; background: white;\n border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }\n .legend-item { margin: 8px 0; }\n .legend-box { display: inline-block; width: 20px; height: 20px;\n border: 1px solid #ccc; margin-right: 10px; vertical-align: middle; }\n `;\n}\n\nfunction pageLegend(): string {\n return `<div class=\"legend\">\n <h2>Legend</h2>\n <div class=\"legend-item\"><span class=\"legend-box\" style=\"background: #E3F2FD;\"></span>\n <strong>Controller / root</strong> — level 0, the entry class of the tree</div>\n <div class=\"legend-item\"><span class=\"legend-box\" style=\"background: #F5F5F5;\"></span>\n <strong>Class</strong> — injectable class (constructor injection)</div>\n <div class=\"legend-item\"><span class=\"legend-box\" style=\"background: #FFF3E0;\"></span>\n <strong>Constant / dynamic</strong> — toConstantValue / toDynamicValue leaf</div>\n <div class=\"legend-item\"><span class=\"legend-box\" style=\"background: #FCE4EC; border-style: dashed;\"></span>\n <strong>Unresolved</strong> — token the analyzer could not resolve</div>\n <div class=\"legend-item\" style=\"margin-top: 15px;\">\n <em>One graph per controller/root; a shared dependency appears in each root's tree.\n Edge labels are injection tokens; unlabeled edges are inject-by-type.</em></div>\n </div>`;\n}\n\nfunction renderScript(entries: DesignGraphEntry[]): string {\n return `\n const graphs = ${JSON.stringify(entries)};\n const viz = new Viz();\n for (const g of graphs) {\n viz.renderSVGElement(g.dot)\n .then(element => { document.getElementById(g.id).appendChild(element); })\n .catch(err => {\n console.error(err);\n document.getElementById(g.id).innerHTML = '<pre>' + err + '</pre>';\n });\n }\n `;\n}\n\n/**\n * Build the full HTML page for a project's DI designs — one section (heading\n * + meta + rendered graph) per controller/root design.\n *\n * `backHref`, when given, renders a \"back to architecture\" link at the top —\n * used by the committed per-project design.html so a reader who clicked in from\n * dependencies.html can click back out. Omitted for the tmp view.\n */\nexport function generateDesignHTML(graph: DiGraph, backHref?: string): string {\n const title = `DI Designs — ${graph.project}`;\n const entries: DesignGraphEntry[] = [];\n const sections: string[] = [];\n const backLink = backHref\n ? `<p class=\"back\"><a href=\"${htmlEscape(backHref)}\">← Back to architecture graph</a></p>`\n : '';\n\n graph.designs.forEach((design: DiDesign, index: number) => {\n const id = `graph-${index}`;\n entries.push(new DesignGraphEntry(id, generateDesignDot(design)));\n sections.push(`<div class=\"section\">\n <h2>${htmlEscape(design.root)} — ${design.rootKind}, Level 0…${design.maxLevel}</h2>\n <div class=\"meta\">${htmlEscape(design.file)}</div>\n <div id=\"${id}\" class=\"graph\"></div>\n </div>`);\n });\n\n const body =\n sections.length > 0\n ? sections.join('\\n ')\n : '<div class=\"section\"><em>No DI-registered classes found in this project.</em></div>';\n\n return `<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <title>${htmlEscape(title)}</title>\n <script src=\"https://cdn.jsdelivr.net/npm/viz.js@2.1.2/viz.js\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/viz.js@2.1.2/full.render.js\"></script>\n <style>${pageStyles()}</style>\n</head>\n<body>\n ${backLink}\n <h1>${htmlEscape(title)}</h1>\n ${pageLegend()}\n ${body}\n <script>${renderScript(entries)}</script>\n</body>\n</html>`;\n}\n\n/**\n * Write tmp/webpieces/design-<project>.html (+ .dot with all digraphs\n * concatenated, for debugging) and return the paths.\n */\nexport function writeDesignVisualization(\n graph: DiGraph,\n workspaceRoot: string\n): DesignVisualizationPaths {\n sortGraph(graph);\n\n const outputDir = path.join(workspaceRoot, 'tmp', 'webpieces');\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const allDot = graph.designs.map((design: DiDesign) => generateDesignDot(design)).join('\\n');\n const dotPath = path.join(outputDir, `design-${graph.project}.dot`);\n fs.writeFileSync(dotPath, allDot, 'utf-8');\n\n const htmlPath = path.join(outputDir, `design-${graph.project}.html`);\n fs.writeFileSync(htmlPath, generateDesignHTML(graph), 'utf-8');\n\n return new DesignVisualizationPaths(dotPath, htmlPath);\n}\n"]}
|
|
@@ -17,11 +17,18 @@ export declare function generateDot(graph: EnhancedGraph, title?: string): strin
|
|
|
17
17
|
*/
|
|
18
18
|
export declare function generateHTML(dot: string, title?: string): string;
|
|
19
19
|
interface VisualizationPaths {
|
|
20
|
-
dotPath: string;
|
|
21
20
|
htmlPath: string;
|
|
22
21
|
}
|
|
23
22
|
/**
|
|
24
|
-
* Write visualization
|
|
23
|
+
* Write the committed architecture visualization to architecture/dependencies.html,
|
|
24
|
+
* next to dependencies.json.
|
|
25
|
+
*
|
|
26
|
+
* This is a checked-in artifact, regenerated deterministically by
|
|
27
|
+
* architecture:generate so the boxes stay clickable into each project's
|
|
28
|
+
* design.html. The DOT is embedded in the HTML (rendered client-side by
|
|
29
|
+
* viz.js), so no separate .dot file is committed — same as design.html. Output
|
|
30
|
+
* is deterministic (sorted graph in → same bytes out) so git only shows a diff
|
|
31
|
+
* when the architecture actually changed.
|
|
25
32
|
*/
|
|
26
33
|
export declare function writeVisualization(graph: EnhancedGraph, workspaceRoot: string, title?: string): VisualizationPaths;
|
|
27
34
|
/**
|
|
@@ -54,6 +54,27 @@ function roleBorderAttrs(role) {
|
|
|
54
54
|
function getShortName(name) {
|
|
55
55
|
return name.includes('/') ? name.split('/').pop() : name;
|
|
56
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* Directory (repo-relative) that the committed architecture HTML lives in.
|
|
59
|
+
* Node click-through links are computed relative to this so they resolve when
|
|
60
|
+
* the file is opened straight from the checkout.
|
|
61
|
+
*/
|
|
62
|
+
const ARCH_OUTPUT_DIR = 'architecture';
|
|
63
|
+
/**
|
|
64
|
+
* Click-through href for a node: the project's committed design.html, made
|
|
65
|
+
* relative to architecture/dependencies.html. Returns null when the project has
|
|
66
|
+
* no generated DI design (no design.json → no clickable design page).
|
|
67
|
+
*
|
|
68
|
+
* designFile is repo-relative posix (e.g. 'packages/http/http-api/design.json');
|
|
69
|
+
* we swap the extension and re-root it at architecture/ so the browser resolves
|
|
70
|
+
* '../packages/http/http-api/design.html' from the checkout.
|
|
71
|
+
*/
|
|
72
|
+
function designHtmlHref(designFile) {
|
|
73
|
+
if (!designFile)
|
|
74
|
+
return null;
|
|
75
|
+
const designHtml = designFile.replace(/design\.json$/, 'design.html');
|
|
76
|
+
return path.posix.relative(ARCH_OUTPUT_DIR, designHtml);
|
|
77
|
+
}
|
|
57
78
|
/**
|
|
58
79
|
* Generate Graphviz DOT format from the graph
|
|
59
80
|
*/
|
|
@@ -71,13 +92,17 @@ function generateDot(graph, title = 'Monorepo Dependency Architecture') {
|
|
|
71
92
|
}
|
|
72
93
|
// Nodes: fill colored by framework (libType), border shaped by role; the
|
|
73
94
|
// label shows the framework-role combo (e.g. express-server, all-lib).
|
|
95
|
+
// A node with a generated DI design gets a URL so the rendered SVG box is
|
|
96
|
+
// clickable — it opens that project's committed design.html in a new tab.
|
|
74
97
|
for (const [project, info] of Object.entries(graph)) {
|
|
75
98
|
const shortName = getShortName(project);
|
|
76
99
|
const framework = info.framework ?? 'all';
|
|
77
100
|
const role = info.role ?? 'lib';
|
|
78
101
|
const color = FRAMEWORK_COLORS[framework] ?? DEFAULT_FRAMEWORK_COLOR;
|
|
79
102
|
const border = roleBorderAttrs(role);
|
|
80
|
-
|
|
103
|
+
const href = designHtmlHref(info.designFile);
|
|
104
|
+
const link = href ? `, URL="${href}", target="_blank"` : '';
|
|
105
|
+
dot += ` "${shortName}" [fillcolor="${color}"${border}${link}, label="${shortName}\\n(L${info.level} · ${framework}-${role})"];\n`;
|
|
81
106
|
}
|
|
82
107
|
dot += '\n';
|
|
83
108
|
// Create same-rank subgraphs for each level
|
|
@@ -114,6 +139,7 @@ function generateHTML(dot, title = 'Monorepo Dependency Architecture') {
|
|
|
114
139
|
return `<!DOCTYPE html>
|
|
115
140
|
<html>
|
|
116
141
|
<head>
|
|
142
|
+
<meta charset="utf-8">
|
|
117
143
|
<title>${title}</title>
|
|
118
144
|
<script src="https://cdn.jsdelivr.net/npm/viz.js@2.1.2/viz.js"></script>
|
|
119
145
|
<script src="https://cdn.jsdelivr.net/npm/viz.js@2.1.2/full.render.js"></script>
|
|
@@ -121,6 +147,7 @@ function generateHTML(dot, title = 'Monorepo Dependency Architecture') {
|
|
|
121
147
|
</head>
|
|
122
148
|
<body>
|
|
123
149
|
<h1>${title}</h1>
|
|
150
|
+
<p class="hint">💡 Click any box with a generated DI design to open its <strong>design.html</strong> (what the AI sees inside that project).</p>
|
|
124
151
|
${legend}
|
|
125
152
|
<div id="graph"></div>
|
|
126
153
|
<script>${script}</script>
|
|
@@ -139,6 +166,14 @@ function generateHTMLStyles() {
|
|
|
139
166
|
text-align: center;
|
|
140
167
|
color: #333;
|
|
141
168
|
}
|
|
169
|
+
.hint {
|
|
170
|
+
text-align: center;
|
|
171
|
+
color: #555;
|
|
172
|
+
margin: 0 0 16px;
|
|
173
|
+
}
|
|
174
|
+
/* viz.js renders node URLs as <a> — show they are clickable. */
|
|
175
|
+
#graph a { cursor: pointer; }
|
|
176
|
+
#graph a:hover polygon { stroke-width: 2.5; }
|
|
142
177
|
#graph {
|
|
143
178
|
text-align: center;
|
|
144
179
|
background: white;
|
|
@@ -226,23 +261,26 @@ function generateHTMLScript(dot) {
|
|
|
226
261
|
`;
|
|
227
262
|
}
|
|
228
263
|
/**
|
|
229
|
-
* Write visualization
|
|
264
|
+
* Write the committed architecture visualization to architecture/dependencies.html,
|
|
265
|
+
* next to dependencies.json.
|
|
266
|
+
*
|
|
267
|
+
* This is a checked-in artifact, regenerated deterministically by
|
|
268
|
+
* architecture:generate so the boxes stay clickable into each project's
|
|
269
|
+
* design.html. The DOT is embedded in the HTML (rendered client-side by
|
|
270
|
+
* viz.js), so no separate .dot file is committed — same as design.html. Output
|
|
271
|
+
* is deterministic (sorted graph in → same bytes out) so git only shows a diff
|
|
272
|
+
* when the architecture actually changed.
|
|
230
273
|
*/
|
|
231
274
|
function writeVisualization(graph, workspaceRoot, title = 'Monorepo Dependency Architecture') {
|
|
232
|
-
const outputDir = path.join(workspaceRoot,
|
|
275
|
+
const outputDir = path.join(workspaceRoot, ARCH_OUTPUT_DIR);
|
|
233
276
|
// Ensure directory exists
|
|
234
277
|
if (!fs.existsSync(outputDir)) {
|
|
235
278
|
fs.mkdirSync(outputDir, { recursive: true });
|
|
236
279
|
}
|
|
237
|
-
|
|
238
|
-
const
|
|
239
|
-
const dotPath = path.join(outputDir, 'architecture.dot');
|
|
240
|
-
fs.writeFileSync(dotPath, dot, 'utf-8');
|
|
241
|
-
// Generate HTML
|
|
242
|
-
const html = generateHTML(dot, title);
|
|
243
|
-
const htmlPath = path.join(outputDir, 'architecture.html');
|
|
280
|
+
const html = generateHTML(generateDot(graph, title), title);
|
|
281
|
+
const htmlPath = path.join(outputDir, 'dependencies.html');
|
|
244
282
|
fs.writeFileSync(htmlPath, html, 'utf-8');
|
|
245
|
-
return {
|
|
283
|
+
return { htmlPath };
|
|
246
284
|
}
|
|
247
285
|
/**
|
|
248
286
|
* Open the HTML visualization in the default browser
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph-visualizer.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/graph-visualizer.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;AAiDH,k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AAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC;QAC3C,OAAO,IAAI,CAAC;IAChB,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,6BAA6B;QAC7B,KAAK,GAAG,CAAC;QACT,OAAO,KAAK,CAAC;IACjB,CAAC;AACL,CAAC","sourcesContent":["/**\n * Graph Visualizer\n *\n * Generates visual representations of the architecture graph:\n * - DOT format (for Graphviz)\n * - Interactive HTML (using viz.js)\n *\n * Output files go to tmp/webpieces/ for easy viewing without committing.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { execSync } from 'child_process';\nimport type { EnhancedGraph } from './graph-sorter';\nimport { toError } from '../toError';\n\n/**\n * Framework (libType) colors for visualization — nodes are colored by which\n * client side they target so it is obvious at a glance which projects are\n * Angular, which are Express, and which libraries are shared (\"all\").\n */\nconst FRAMEWORK_COLORS: Record<string, string> = {\n angular: '#FCE4EC', // pink - Angular front-end\n react: '#E3F2FD', // blue - React front-end\n express: '#E8F5E9', // green - Express / server side\n all: '#F5F5F5', // grey - library usable by any side\n};\n\nconst DEFAULT_FRAMEWORK_COLOR = '#FFF3E0'; // orange - unknown/other libType\n\n/**\n * Role border styling — fill stays keyed on framework; the border shape shows a\n * project's ROLE at a glance:\n * server → double border (a runnable server app)\n * client → dashed border (a client app, e.g. angular)\n * designed-lib → bold border (a library with a generated @ApiImplementation design)\n * lib / other → plain thin border\n */\nfunction roleBorderAttrs(role: string): string {\n if (role === 'server') return ', peripheries=2';\n if (role === 'client') return ', style=\"filled,dashed\"';\n if (role === 'designed-lib') return ', penwidth=2';\n return '';\n}\n\n/**\n * Remove scope from name for display\n * '@scope/name' → 'name'\n * 'name' → 'name'\n */\nfunction getShortName(name: string): string {\n return name.includes('/') ? name.split('/').pop()! : name;\n}\n\n/**\n * Generate Graphviz DOT format from the graph\n */\nexport function generateDot(graph: EnhancedGraph, title: string = 'Monorepo Dependency Architecture'): string {\n let dot = 'digraph Architecture {\\n';\n dot += ' rankdir=TB;\\n';\n dot += ' node [shape=box, style=filled, fontname=\"Arial\"];\\n';\n dot += ' edge [fontname=\"Arial\"];\\n\\n';\n\n // Group projects by level\n const levels: Record<number, string[]> = {};\n for (const [project, info] of Object.entries(graph)) {\n if (!levels[info.level]) levels[info.level] = [];\n levels[info.level].push(project);\n }\n\n // Nodes: fill colored by framework (libType), border shaped by role; the\n // label shows the framework-role combo (e.g. express-server, all-lib).\n for (const [project, info] of Object.entries(graph)) {\n const shortName = getShortName(project);\n const framework = info.framework ?? 'all';\n const role = info.role ?? 'lib';\n const color = FRAMEWORK_COLORS[framework] ?? DEFAULT_FRAMEWORK_COLOR;\n const border = roleBorderAttrs(role);\n dot += ` \"${shortName}\" [fillcolor=\"${color}\"${border}, label=\"${shortName}\\\\n(L${info.level} · ${framework}-${role})\"];\\n`;\n }\n\n dot += '\\n';\n\n // Create same-rank subgraphs for each level\n for (const [level, projects] of Object.entries(levels)) {\n dot += ` { rank=same; `;\n projects.forEach((p) => {\n const shortName = getShortName(p);\n dot += `\"${shortName}\"; `;\n });\n dot += '}\\n';\n }\n\n dot += '\\n';\n\n // Create edges (dependencies)\n for (const [project, info] of Object.entries(graph)) {\n const shortName = getShortName(project);\n for (const dep of info.dependsOn || []) {\n const depShortName = getShortName(dep);\n dot += ` \"${shortName}\" -> \"${depShortName}\";\\n`;\n }\n }\n\n dot += '\\n labelloc=\"t\";\\n';\n dot += ` label=\"${title}\\\\n(from architecture/dependencies.json)\";\\n`;\n dot += ' fontsize=20;\\n';\n dot += '}\\n';\n\n return dot;\n}\n\n/**\n * Generate interactive HTML with embedded SVG using viz.js\n */\nexport function generateHTML(dot: string, title: string = 'Monorepo Dependency Architecture'): string {\n const styles = generateHTMLStyles();\n const legend = generateHTMLLegend();\n const script = generateHTMLScript(dot);\n\n return `<!DOCTYPE html>\n<html>\n<head>\n <title>${title}</title>\n <script src=\"https://cdn.jsdelivr.net/npm/viz.js@2.1.2/viz.js\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/viz.js@2.1.2/full.render.js\"></script>\n <style>${styles}</style>\n</head>\n<body>\n <h1>${title}</h1>\n ${legend}\n <div id=\"graph\"></div>\n <script>${script}</script>\n</body>\n</html>`;\n}\n\nfunction generateHTMLStyles(): string {\n return `\n body {\n margin: 0;\n padding: 20px;\n font-family: Arial, sans-serif;\n background: #f5f5f5;\n }\n h1 {\n text-align: center;\n color: #333;\n }\n #graph {\n text-align: center;\n background: white;\n padding: 20px;\n border-radius: 8px;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n }\n .legend {\n margin: 20px auto;\n max-width: 600px;\n padding: 15px;\n background: white;\n border-radius: 8px;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n }\n .legend h2 {\n margin-top: 0;\n }\n .legend-item {\n margin: 8px 0;\n }\n .legend-box {\n display: inline-block;\n width: 20px;\n height: 20px;\n border: 1px solid #ccc;\n margin-right: 10px;\n vertical-align: middle;\n }\n `;\n}\n\nfunction generateHTMLLegend(): string {\n return `<div class=\"legend\">\n <h2>Legend — fill = framework (libType), border = role</h2>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"background: #FCE4EC;\"></span>\n <strong>angular:</strong> Angular front-end\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"background: #E3F2FD;\"></span>\n <strong>react:</strong> React front-end\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"background: #E8F5E9;\"></span>\n <strong>express:</strong> Express / server side\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"background: #F5F5F5;\"></span>\n <strong>all:</strong> Library usable by any side\n </div>\n <div class=\"legend-item\" style=\"margin-top: 12px;\">\n <span class=\"legend-box\" style=\"border: 3px double #333;\"></span>\n <strong>server:</strong> runnable server app (double border)\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"border: 1px dashed #333;\"></span>\n <strong>client:</strong> client app, e.g. angular (dashed border)\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"border: 2px solid #333;\"></span>\n <strong>designed-lib:</strong> library with a generated @ApiImplementation design (bold border)\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"border: 1px solid #ccc;\"></span>\n <strong>lib:</strong> plain library, no generated design (thin border)\n </div>\n <div class=\"legend-item\" style=\"margin-top: 15px;\">\n <em>Each node label shows its dependency level (L#) and framework-role (e.g. express-server, all-lib). Rows are laid out by level (top = no dependencies). Transitive dependencies are allowed but not shown.</em>\n </div>\n </div>`;\n}\n\nfunction generateHTMLScript(dot: string): string {\n return `\n const dot = ${JSON.stringify(dot)};\n const viz = new Viz();\n\n viz.renderSVGElement(dot)\n .then(element => {\n document.getElementById('graph').appendChild(element);\n })\n .catch(err => {\n console.error(err);\n document.getElementById('graph').innerHTML = '<pre>' + err + '</pre>';\n });\n `;\n}\n\ninterface VisualizationPaths {\n dotPath: string;\n htmlPath: string;\n}\n\n/**\n * Write visualization files to tmp/webpieces/\n */\nexport function writeVisualization(\n graph: EnhancedGraph,\n workspaceRoot: string,\n title: string = 'Monorepo Dependency Architecture'\n): VisualizationPaths {\n const outputDir = path.join(workspaceRoot, 'tmp', 'webpieces');\n\n // Ensure directory exists\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n // Generate DOT\n const dot = generateDot(graph, title);\n const dotPath = path.join(outputDir, 'architecture.dot');\n fs.writeFileSync(dotPath, dot, 'utf-8');\n\n // Generate HTML\n const html = generateHTML(dot, title);\n const htmlPath = path.join(outputDir, 'architecture.html');\n fs.writeFileSync(htmlPath, html, 'utf-8');\n\n return { dotPath, htmlPath };\n}\n\n/**\n * Open the HTML visualization in the default browser\n */\nexport function openVisualization(htmlPath: string): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const platform = process.platform;\n let openCommand: string;\n\n if (platform === 'darwin') {\n openCommand = `open \"${htmlPath}\"`;\n } else if (platform === 'win32') {\n openCommand = `start \"\" \"${htmlPath}\"`;\n } else {\n openCommand = `xdg-open \"${htmlPath}\"`;\n }\n\n execSync(openCommand, { stdio: 'ignore' });\n return true;\n } catch (err: unknown) {\n //const error = toError(err);\n void err;\n return false;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"graph-visualizer.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/graph-visualizer.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;AAuEH,kCAyDC;AAKD,oCAsBC;AA8HD,gDAiBC;AAKD,8CAqBC;;AAlUD,+CAAyB;AACzB,mDAA6B;AAC7B,iDAAyC;AAIzC;;;;GAIG;AACH,MAAM,gBAAgB,GAA2B;IAC7C,OAAO,EAAE,SAAS,EAAE,6BAA6B;IACjD,KAAK,EAAE,SAAS,EAAE,2BAA2B;IAC7C,OAAO,EAAE,SAAS,EAAE,iCAAiC;IACrD,GAAG,EAAE,SAAS,EAAE,sCAAsC;CACzD,CAAC;AAEF,MAAM,uBAAuB,GAAG,SAAS,CAAC,CAAC,iCAAiC;AAE5E;;;;;;;GAOG;AACH,SAAS,eAAe,CAAC,IAAY;IACjC,IAAI,IAAI,KAAK,QAAQ;QAAE,OAAO,iBAAiB,CAAC;IAChD,IAAI,IAAI,KAAK,QAAQ;QAAE,OAAO,yBAAyB,CAAC;IACxD,IAAI,IAAI,KAAK,cAAc;QAAE,OAAO,cAAc,CAAC;IACnD,OAAO,EAAE,CAAC;AACd,CAAC;AAED;;;;GAIG;AACH,SAAS,YAAY,CAAC,IAAY;IAC9B,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAG,CAAC,CAAC,CAAC,IAAI,CAAC;AAC9D,CAAC;AAED;;;;GAIG;AACH,MAAM,eAAe,GAAG,cAAc,CAAC;AAEvC;;;;;;;;GAQG;AACH,SAAS,cAAc,CAAC,UAA8B;IAClD,IAAI,CAAC,UAAU;QAAE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AC;IAC3D,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;IAE1C,OAAO,EAAE,QAAQ,EAAE,CAAC;AACxB,CAAC;AAED;;GAEG;AACH,SAAgB,iBAAiB,CAAC,QAAgB;IAC9C,8DAA8D;IAC9D,IAAI,CAAC;QACD,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;QAClC,IAAI,WAAmB,CAAC;QAExB,IAAI,QAAQ,KAAK,QAAQ,EAAE,CAAC;YACxB,WAAW,GAAG,SAAS,QAAQ,GAAG,CAAC;QACvC,CAAC;aAAM,IAAI,QAAQ,KAAK,OAAO,EAAE,CAAC;YAC9B,WAAW,GAAG,aAAa,QAAQ,GAAG,CAAC;QAC3C,CAAC;aAAM,CAAC;YACJ,WAAW,GAAG,aAAa,QAAQ,GAAG,CAAC;QAC3C,CAAC;QAED,IAAA,wBAAQ,EAAC,WAAW,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC;QAC3C,OAAO,IAAI,CAAC;IAChB,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,6BAA6B;QAC7B,KAAK,GAAG,CAAC;QACT,OAAO,KAAK,CAAC;IACjB,CAAC;AACL,CAAC","sourcesContent":["/**\n * Graph Visualizer\n *\n * Generates visual representations of the architecture graph:\n * - DOT format (for Graphviz)\n * - Interactive HTML (using viz.js)\n *\n * Output files go to tmp/webpieces/ for easy viewing without committing.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { execSync } from 'child_process';\nimport type { EnhancedGraph } from './graph-sorter';\nimport { toError } from '../toError';\n\n/**\n * Framework (libType) colors for visualization — nodes are colored by which\n * client side they target so it is obvious at a glance which projects are\n * Angular, which are Express, and which libraries are shared (\"all\").\n */\nconst FRAMEWORK_COLORS: Record<string, string> = {\n angular: '#FCE4EC', // pink - Angular front-end\n react: '#E3F2FD', // blue - React front-end\n express: '#E8F5E9', // green - Express / server side\n all: '#F5F5F5', // grey - library usable by any side\n};\n\nconst DEFAULT_FRAMEWORK_COLOR = '#FFF3E0'; // orange - unknown/other libType\n\n/**\n * Role border styling — fill stays keyed on framework; the border shape shows a\n * project's ROLE at a glance:\n * server → double border (a runnable server app)\n * client → dashed border (a client app, e.g. angular)\n * designed-lib → bold border (a library with a generated @ApiImplementation design)\n * lib / other → plain thin border\n */\nfunction roleBorderAttrs(role: string): string {\n if (role === 'server') return ', peripheries=2';\n if (role === 'client') return ', style=\"filled,dashed\"';\n if (role === 'designed-lib') return ', penwidth=2';\n return '';\n}\n\n/**\n * Remove scope from name for display\n * '@scope/name' → 'name'\n * 'name' → 'name'\n */\nfunction getShortName(name: string): string {\n return name.includes('/') ? name.split('/').pop()! : name;\n}\n\n/**\n * Directory (repo-relative) that the committed architecture HTML lives in.\n * Node click-through links are computed relative to this so they resolve when\n * the file is opened straight from the checkout.\n */\nconst ARCH_OUTPUT_DIR = 'architecture';\n\n/**\n * Click-through href for a node: the project's committed design.html, made\n * relative to architecture/dependencies.html. Returns null when the project has\n * no generated DI design (no design.json → no clickable design page).\n *\n * designFile is repo-relative posix (e.g. 'packages/http/http-api/design.json');\n * we swap the extension and re-root it at architecture/ so the browser resolves\n * '../packages/http/http-api/design.html' from the checkout.\n */\nfunction designHtmlHref(designFile: string | undefined): string | null {\n if (!designFile) return null;\n const designHtml = designFile.replace(/design\\.json$/, 'design.html');\n return path.posix.relative(ARCH_OUTPUT_DIR, designHtml);\n}\n\n/**\n * Generate Graphviz DOT format from the graph\n */\nexport function generateDot(graph: EnhancedGraph, title: string = 'Monorepo Dependency Architecture'): string {\n let dot = 'digraph Architecture {\\n';\n dot += ' rankdir=TB;\\n';\n dot += ' node [shape=box, style=filled, fontname=\"Arial\"];\\n';\n dot += ' edge [fontname=\"Arial\"];\\n\\n';\n\n // Group projects by level\n const levels: Record<number, string[]> = {};\n for (const [project, info] of Object.entries(graph)) {\n if (!levels[info.level]) levels[info.level] = [];\n levels[info.level].push(project);\n }\n\n // Nodes: fill colored by framework (libType), border shaped by role; the\n // label shows the framework-role combo (e.g. express-server, all-lib).\n // A node with a generated DI design gets a URL so the rendered SVG box is\n // clickable — it opens that project's committed design.html in a new tab.\n for (const [project, info] of Object.entries(graph)) {\n const shortName = getShortName(project);\n const framework = info.framework ?? 'all';\n const role = info.role ?? 'lib';\n const color = FRAMEWORK_COLORS[framework] ?? DEFAULT_FRAMEWORK_COLOR;\n const border = roleBorderAttrs(role);\n const href = designHtmlHref(info.designFile);\n const link = href ? `, URL=\"${href}\", target=\"_blank\"` : '';\n dot += ` \"${shortName}\" [fillcolor=\"${color}\"${border}${link}, label=\"${shortName}\\\\n(L${info.level} · ${framework}-${role})\"];\\n`;\n }\n\n dot += '\\n';\n\n // Create same-rank subgraphs for each level\n for (const [level, projects] of Object.entries(levels)) {\n dot += ` { rank=same; `;\n projects.forEach((p) => {\n const shortName = getShortName(p);\n dot += `\"${shortName}\"; `;\n });\n dot += '}\\n';\n }\n\n dot += '\\n';\n\n // Create edges (dependencies)\n for (const [project, info] of Object.entries(graph)) {\n const shortName = getShortName(project);\n for (const dep of info.dependsOn || []) {\n const depShortName = getShortName(dep);\n dot += ` \"${shortName}\" -> \"${depShortName}\";\\n`;\n }\n }\n\n dot += '\\n labelloc=\"t\";\\n';\n dot += ` label=\"${title}\\\\n(from architecture/dependencies.json)\";\\n`;\n dot += ' fontsize=20;\\n';\n dot += '}\\n';\n\n return dot;\n}\n\n/**\n * Generate interactive HTML with embedded SVG using viz.js\n */\nexport function generateHTML(dot: string, title: string = 'Monorepo Dependency Architecture'): string {\n const styles = generateHTMLStyles();\n const legend = generateHTMLLegend();\n const script = generateHTMLScript(dot);\n\n return `<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <title>${title}</title>\n <script src=\"https://cdn.jsdelivr.net/npm/viz.js@2.1.2/viz.js\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/viz.js@2.1.2/full.render.js\"></script>\n <style>${styles}</style>\n</head>\n<body>\n <h1>${title}</h1>\n <p class=\"hint\">💡 Click any box with a generated DI design to open its <strong>design.html</strong> (what the AI sees inside that project).</p>\n ${legend}\n <div id=\"graph\"></div>\n <script>${script}</script>\n</body>\n</html>`;\n}\n\nfunction generateHTMLStyles(): string {\n return `\n body {\n margin: 0;\n padding: 20px;\n font-family: Arial, sans-serif;\n background: #f5f5f5;\n }\n h1 {\n text-align: center;\n color: #333;\n }\n .hint {\n text-align: center;\n color: #555;\n margin: 0 0 16px;\n }\n /* viz.js renders node URLs as <a> — show they are clickable. */\n #graph a { cursor: pointer; }\n #graph a:hover polygon { stroke-width: 2.5; }\n #graph {\n text-align: center;\n background: white;\n padding: 20px;\n border-radius: 8px;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n }\n .legend {\n margin: 20px auto;\n max-width: 600px;\n padding: 15px;\n background: white;\n border-radius: 8px;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n }\n .legend h2 {\n margin-top: 0;\n }\n .legend-item {\n margin: 8px 0;\n }\n .legend-box {\n display: inline-block;\n width: 20px;\n height: 20px;\n border: 1px solid #ccc;\n margin-right: 10px;\n vertical-align: middle;\n }\n `;\n}\n\nfunction generateHTMLLegend(): string {\n return `<div class=\"legend\">\n <h2>Legend — fill = framework (libType), border = role</h2>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"background: #FCE4EC;\"></span>\n <strong>angular:</strong> Angular front-end\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"background: #E3F2FD;\"></span>\n <strong>react:</strong> React front-end\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"background: #E8F5E9;\"></span>\n <strong>express:</strong> Express / server side\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"background: #F5F5F5;\"></span>\n <strong>all:</strong> Library usable by any side\n </div>\n <div class=\"legend-item\" style=\"margin-top: 12px;\">\n <span class=\"legend-box\" style=\"border: 3px double #333;\"></span>\n <strong>server:</strong> runnable server app (double border)\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"border: 1px dashed #333;\"></span>\n <strong>client:</strong> client app, e.g. angular (dashed border)\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"border: 2px solid #333;\"></span>\n <strong>designed-lib:</strong> library with a generated @ApiImplementation design (bold border)\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"border: 1px solid #ccc;\"></span>\n <strong>lib:</strong> plain library, no generated design (thin border)\n </div>\n <div class=\"legend-item\" style=\"margin-top: 15px;\">\n <em>Each node label shows its dependency level (L#) and framework-role (e.g. express-server, all-lib). Rows are laid out by level (top = no dependencies). Transitive dependencies are allowed but not shown.</em>\n </div>\n </div>`;\n}\n\nfunction generateHTMLScript(dot: string): string {\n return `\n const dot = ${JSON.stringify(dot)};\n const viz = new Viz();\n\n viz.renderSVGElement(dot)\n .then(element => {\n document.getElementById('graph').appendChild(element);\n })\n .catch(err => {\n console.error(err);\n document.getElementById('graph').innerHTML = '<pre>' + err + '</pre>';\n });\n `;\n}\n\ninterface VisualizationPaths {\n htmlPath: string;\n}\n\n/**\n * Write the committed architecture visualization to architecture/dependencies.html,\n * next to dependencies.json.\n *\n * This is a checked-in artifact, regenerated deterministically by\n * architecture:generate so the boxes stay clickable into each project's\n * design.html. The DOT is embedded in the HTML (rendered client-side by\n * viz.js), so no separate .dot file is committed — same as design.html. Output\n * is deterministic (sorted graph in → same bytes out) so git only shows a diff\n * when the architecture actually changed.\n */\nexport function writeVisualization(\n graph: EnhancedGraph,\n workspaceRoot: string,\n title: string = 'Monorepo Dependency Architecture'\n): VisualizationPaths {\n const outputDir = path.join(workspaceRoot, ARCH_OUTPUT_DIR);\n\n // Ensure directory exists\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const html = generateHTML(generateDot(graph, title), title);\n const htmlPath = path.join(outputDir, 'dependencies.html');\n fs.writeFileSync(htmlPath, html, 'utf-8');\n\n return { htmlPath };\n}\n\n/**\n * Open the HTML visualization in the default browser\n */\nexport function openVisualization(htmlPath: string): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const platform = process.platform;\n let openCommand: string;\n\n if (platform === 'darwin') {\n openCommand = `open \"${htmlPath}\"`;\n } else if (platform === 'win32') {\n openCommand = `start \"\" \"${htmlPath}\"`;\n } else {\n openCommand = `xdg-open \"${htmlPath}\"`;\n }\n\n execSync(openCommand, { stdio: 'ignore' });\n return true;\n } catch (err: unknown) {\n //const error = toError(err);\n void err;\n return false;\n }\n}\n"]}
|
package/src/plugin.js
CHANGED
|
@@ -302,12 +302,13 @@ function createGenerateTarget(graphPath) {
|
|
|
302
302
|
cache: false,
|
|
303
303
|
outputs: [
|
|
304
304
|
'{workspaceRoot}/architecture/dependencies.json',
|
|
305
|
+
'{workspaceRoot}/architecture/dependencies.html',
|
|
305
306
|
'{workspaceRoot}/architecture/runtime-dependencies.json',
|
|
306
307
|
],
|
|
307
308
|
options: { graphPath },
|
|
308
309
|
metadata: {
|
|
309
310
|
technologies: ['nx'],
|
|
310
|
-
description: 'Generate the architecture dependency graph and the runtime microservice graph',
|
|
311
|
+
description: 'Generate the architecture dependency graph (+ clickable dependencies.html) and the runtime microservice graph',
|
|
311
312
|
},
|
|
312
313
|
};
|
|
313
314
|
}
|
package/src/plugin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.js","sourceRoot":"","sources":["../../../../../packages/tooling/nx-webpieces-rules/src/plugin.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;GAgBG;;;AA4MH,sDASC;AAnND,+BAAqC;AACrC,2BAAgC;AAQhC,uDAI2B;AAC3B,yDAG4B;AAmE5B,MAAM,eAAe,GAAwC;IACzD,YAAY,EAAE;QACV,OAAO,EAAE,IAAI;QACb,UAAU,EAAE,gCAAgC;QAC5C,eAAe,EAAE,EAAE;KACtB;IACD,SAAS,EAAE;QACP,OAAO,EA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CAAC,CAAC;IACnC,CAAC,CAAC,CAAC;AACP,CAAC;AAED;;GAEG;AACH,kBAAe,EAAE,aAAa,EAAb,qBAAa,EAAE,CAAC","sourcesContent":["/**\n * Unified Nx Inference Plugin for @webpieces/nx-webpieces-rules\n *\n * This plugin automatically creates targets for:\n * 1. Workspace-level architecture validation (generate, visualize, validate-*)\n * 2. Per-project circular dependency checking\n *\n * Install with: nx add @webpieces/nx-webpieces-rules\n *\n * Usage:\n * Add to nx.json plugins array:\n * {\n * \"plugins\": [\"@webpieces/nx-webpieces-rules\"]\n * }\n *\n * Then all targets appear automatically without manual project.json configuration.\n */\n\nimport { dirname, join } from 'path';\nimport { existsSync } from 'fs';\nimport type {\n CreateNodesV2,\n CreateNodesContextV2,\n CreateNodesResultV2,\n CreateNodesResult,\n TargetConfiguration,\n} from '@nx/devkit';\nimport {\n createVisualizeRuntimeTarget,\n createValidateRuntimeArchitectureTarget,\n createValidateRuntimeMarkersTarget,\n} from './runtime-targets';\nimport {\n createDiGraphGenerateTarget,\n createValidateDiGraphUnchangedTarget,\n} from './di-graph-targets';\n\n/**\n * Circular dependency checking options\n */\nexport interface CircularDepsOptions {\n enabled?: boolean;\n targetName?: string;\n excludePatterns?: string[];\n}\n\n/**\n * Validation options for architecture checks\n */\nexport interface ValidationOptions {\n noCycles?: boolean;\n noSkipLevelDeps?: boolean;\n architectureUnchanged?: boolean;\n validatePackageJson?: boolean;\n validateNewMethods?: boolean;\n validateModifiedMethods?: boolean;\n validateModifiedFiles?: boolean;\n validateVersionsLocked?: boolean;\n validateTsInSrc?: boolean;\n validateNxWiring?: boolean;\n runtimeArchitecture?: boolean;\n diGraph?: boolean;\n newMethodsMaxLines?: number;\n modifiedAndNewMethodsMaxLines?: number;\n modifiedFilesMaxLines?: number;\n /**\n * Validation mode for method/file size limits:\n * - STRICT: All limits enforced, disable comments ignored\n * - NORMAL: Limits enforced, disable comments with dates work\n * - OFF: Skip size validations entirely (for fast iteration)\n */\n validationMode?: 'STRICT' | 'NORMAL' | 'OFF';\n}\n\n/**\n * Feature flags for workspace targets\n */\nexport interface FeatureOptions {\n generate?: boolean;\n visualize?: boolean;\n visualizeRuntime?: boolean;\n}\n\n/**\n * Workspace-level configuration options\n */\nexport interface WorkspaceOptions {\n enabled?: boolean;\n targetPrefix?: string;\n graphPath?: string;\n validations?: ValidationOptions;\n features?: FeatureOptions;\n}\n\n/**\n * Configuration for @webpieces/nx-webpieces-rules Nx plugin\n */\nexport interface ArchitecturePluginOptions {\n circularDeps?: CircularDepsOptions;\n workspace?: WorkspaceOptions;\n}\n\nconst DEFAULT_OPTIONS: Required<ArchitecturePluginOptions> = {\n circularDeps: {\n enabled: true,\n targetName: 'validate-no-file-import-cycles',\n excludePatterns: [],\n },\n workspace: {\n enabled: true,\n targetPrefix: 'arch:',\n graphPath: 'architecture/dependencies.json',\n validations: {\n noCycles: true,\n // Retired: the architecture graph is now auto-reduced in `generate`, so the\n // committed graph can never contain a skip-level edge. Defaults off; the\n // executor is a no-op kept for one release. See validate-no-skiplevel-deps.\n noSkipLevelDeps: false,\n architectureUnchanged: true,\n validatePackageJson: true,\n validateNewMethods: true,\n validateModifiedMethods: true,\n validateModifiedFiles: true,\n validateVersionsLocked: true,\n validateTsInSrc: true,\n validateNxWiring: true,\n runtimeArchitecture: true,\n diGraph: true,\n newMethodsMaxLines: 30,\n modifiedAndNewMethodsMaxLines: 80,\n modifiedFilesMaxLines: 900,\n validationMode: 'NORMAL',\n },\n features: {\n generate: true,\n visualize: true,\n visualizeRuntime: true,\n },\n },\n};\n\nfunction normalizeOptions(\n options: ArchitecturePluginOptions | undefined,\n): Required<ArchitecturePluginOptions> {\n const circularDeps = {\n ...DEFAULT_OPTIONS.circularDeps,\n ...options?.circularDeps,\n };\n\n const workspace = {\n ...DEFAULT_OPTIONS.workspace,\n ...options?.workspace,\n validations: {\n ...DEFAULT_OPTIONS.workspace.validations,\n ...options?.workspace?.validations,\n },\n features: {\n ...DEFAULT_OPTIONS.workspace.features,\n ...options?.workspace?.features,\n },\n };\n\n return {\n circularDeps,\n workspace,\n } as Required<ArchitecturePluginOptions>;\n}\n\nasync function createNodesFunction(\n projectFiles: readonly string[],\n options: ArchitecturePluginOptions | undefined,\n context: CreateNodesContextV2,\n): Promise<CreateNodesResultV2> {\n const opts = normalizeOptions(options);\n const results: CreateNodesResultV2 = [];\n\n // Add workspace-level architecture targets\n addArchitectureProject(results, projectFiles, opts, context);\n\n // Add per-project targets (circular-deps, ci, runtime-markers)\n addPerProjectTargets(results, projectFiles, opts, context);\n\n return results;\n}\n\nfunction addArchitectureProject(\n results: CreateNodesResultV2,\n projectFiles: readonly string[],\n opts: Required<ArchitecturePluginOptions>,\n context: CreateNodesContextV2,\n): void {\n if (!opts.workspace.enabled) return;\n\n const archDirPath = join(context.workspaceRoot, 'architecture');\n if (!existsSync(archDirPath)) return;\n\n const workspaceTargets = createWorkspaceTargetsWithoutPrefix(opts);\n if (Object.keys(workspaceTargets).length === 0) return;\n\n const result: CreateNodesResult = {\n projects: {\n architecture: {\n name: 'architecture',\n root: 'architecture',\n targets: workspaceTargets,\n },\n },\n };\n\n const firstProjectFile = projectFiles[0];\n if (firstProjectFile) {\n results.push([firstProjectFile, result] as const);\n }\n}\n\n\n// A project sits inside a NESTED git repo (e.g. a clone under repositories/) when any of its\n// ancestor dirs — up to but NOT including the workspace root — contains a `.git`. Such projects are\n// separate repos, not part of THIS workspace's graph, so they must not get inferred targets (that is\n// what drags foreign clones into `nx affected`). Same repo-boundary signal the AI guards use.\nexport function isInsideNestedGitRepo(workspaceRoot: string, projectRoot: string): boolean {\n let dir = projectRoot;\n while (dir && dir !== '.' && dir !== '/') {\n if (existsSync(join(workspaceRoot, dir, '.git'))) return true;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return false;\n}\n\nfunction addPerProjectTargets(\n results: CreateNodesResultV2,\n projectFiles: readonly string[],\n opts: Required<ArchitecturePluginOptions>,\n context: CreateNodesContextV2,\n): void {\n // Track processed project roots to avoid duplicates when both files exist\n const processedRoots = new Set<string>();\n\n for (const projectFile of projectFiles) {\n const isProjectJson = projectFile.endsWith('project.json');\n const isPackageJson = projectFile.endsWith('package.json');\n\n if (!isProjectJson && !isPackageJson) continue;\n\n const projectRoot = dirname(projectFile);\n\n // Skip root (workspace manifest, not a project)\n if (projectRoot === '.') continue;\n\n // Skip projects inside a nested git repo (vendored clones under repositories/): they are\n // separate repos and must not be swept into this workspace's `nx affected` graph.\n if (isInsideNestedGitRepo(context.workspaceRoot, projectRoot)) continue;\n\n // Skip if we've already processed this project root\n if (processedRoots.has(projectRoot)) continue;\n\n // For package.json, skip if project.json also exists in same directory\n // (prefer project.json - it will be processed separately)\n if (isPackageJson) {\n const projectJsonPath = join(context.workspaceRoot, projectRoot, 'project.json');\n if (existsSync(projectJsonPath)) continue;\n }\n\n processedRoots.add(projectRoot);\n\n const targets = buildPerProjectTargets(isProjectJson, projectRoot, opts);\n\n if (Object.keys(targets).length === 0) continue;\n\n const result: CreateNodesResult = {\n projects: {\n [projectRoot]: {\n targets,\n },\n },\n };\n\n results.push([projectFile, result] as const);\n }\n}\n\n/**\n * Build the target map for one project. Most targets are project.json-only\n * (package.json-only projects may not have TypeScript source); `ci` goes on all.\n */\nfunction buildPerProjectTargets(\n isProjectJson: boolean,\n projectRoot: string,\n opts: Required<ArchitecturePluginOptions>,\n): Record<string, TargetConfiguration> {\n const targets: Record<string, TargetConfiguration> = {};\n\n // Add circular-deps target ONLY for project.json projects\n if (isProjectJson && opts.circularDeps.enabled) {\n if (!isExcluded(projectRoot, opts.circularDeps.excludePatterns!)) {\n const targetName = opts.circularDeps.targetName!;\n targets[targetName] = createCircularDepsTarget(projectRoot, targetName);\n }\n }\n\n // Add per-project runtime-marker validation (validates this project's\n // service-contract.json against its own api-project deps, independently).\n if (isProjectJson && opts.workspace.validations!.runtimeArchitecture) {\n targets['validate-runtime-markers'] = createValidateRuntimeMarkersTarget();\n }\n\n // Per-project DI design DAG: regenerate design.json/design.md on every build,\n // then gate the build on the committed copies being current.\n if (isProjectJson && opts.workspace.validations!.diGraph) {\n targets['di-graph-generate'] = createDiGraphGenerateTarget();\n targets['validate-di-graph-unchanged'] = createValidateDiGraphUnchangedTarget();\n }\n\n // Add ci target to ALL projects (both project.json and package.json)\n targets['ci'] = createCiTarget();\n\n return targets;\n}\n\n/**\n * Nx V2 Inference Plugin\n * Matches project.json and package.json files to create targets\n */\nexport const createNodesV2: CreateNodesV2<ArchitecturePluginOptions> = [\n // Pattern to match project.json and package.json files\n '**/{project,package}.json',\n\n // Inference function\n createNodesFunction,\n];\n\n/**\n * Build list of enabled validation target names for validate-complete dependency chain\n */\nfunction buildValidationTargetsList(\n validations: Required<ArchitecturePluginOptions>['workspace']['validations'],\n): string[] {\n const targets: string[] = [];\n if (validations!.noCycles) targets.push('validate-no-architecture-cycles');\n if (validations!.architectureUnchanged) targets.push('validate-architecture-unchanged');\n if (validations!.noSkipLevelDeps) targets.push('validate-no-skiplevel-deps');\n if (validations!.validatePackageJson) targets.push('validate-packagejson');\n // Use combined validate-code instead of 3 separate targets\n if (\n validations!.validateNewMethods ||\n validations!.validateModifiedMethods ||\n validations!.validateModifiedFiles\n ) {\n targets.push('validate-code');\n }\n if (validations!.validateVersionsLocked) targets.push('validate-versions-locked');\n if (validations!.validateTsInSrc) targets.push('validate-ts-in-src');\n if (validations!.validateNxWiring) targets.push('validate-nx-wiring');\n if (validations!.runtimeArchitecture) targets.push('validate-runtime-architecture');\n return targets;\n}\n\n/**\n * Create workspace-level architecture validation targets WITHOUT prefix\n * Used for virtual 'architecture' project\n */\nfunction createWorkspaceTargetsWithoutPrefix(\n opts: Required<ArchitecturePluginOptions>,\n): Record<string, TargetConfiguration> {\n const targets: Record<string, TargetConfiguration> = {};\n const graphPath = opts.workspace.graphPath!;\n const validations = opts.workspace.validations!;\n\n // Add help target (always available)\n targets['help'] = createHelpTarget();\n\n if (opts.workspace.features!.generate) {\n targets['generate'] = createGenerateTarget(graphPath);\n }\n if (opts.workspace.features!.visualize) {\n targets['visualize'] = createVisualizeTargetWithoutPrefix(graphPath);\n }\n if (opts.workspace.features!.visualizeRuntime) {\n targets['visualize-runtime'] = createVisualizeRuntimeTarget();\n }\n if (validations.noCycles) {\n targets['validate-no-architecture-cycles'] = createValidateNoCyclesTarget();\n }\n if (validations.architectureUnchanged) {\n targets['validate-architecture-unchanged'] = createValidateUnchangedTarget(graphPath);\n }\n if (validations.noSkipLevelDeps) {\n targets['validate-no-skiplevel-deps'] = createValidateNoSkipLevelTarget();\n }\n if (validations.validatePackageJson) {\n targets['validate-packagejson'] = createValidatePackageJsonTarget();\n }\n // Use combined validate-code instead of 3 separate targets\n // Options come from webpieces.config.json at the workspace root\n // (loaded via @webpieces/rules-config; same source of truth as @webpieces/ai-hook-rules)\n if (\n validations.validateNewMethods ||\n validations.validateModifiedMethods ||\n validations.validateModifiedFiles\n ) {\n targets['validate-code'] = createValidateCodeTarget();\n }\n if (validations.validateVersionsLocked) {\n targets['validate-versions-locked'] = createValidateVersionsLockedTarget();\n }\n if (validations.validateTsInSrc) {\n targets['validate-ts-in-src'] = createValidateTsInSrcTarget();\n }\n if (validations.validateNxWiring) {\n targets['validate-nx-wiring'] = createValidateNxWiringTarget();\n }\n if (validations.runtimeArchitecture) {\n targets['validate-runtime-architecture'] = createValidateRuntimeArchitectureTarget();\n }\n\n // Add validate-complete target that runs all enabled validations\n const validationTargets = buildValidationTargetsList(validations);\n if (validationTargets.length > 0) {\n targets['validate-complete'] = createValidateCompleteTarget(validationTargets);\n }\n\n return targets;\n}\n\nfunction createGenerateTarget(graphPath: string): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:generate',\n cache: false,\n outputs: [\n '{workspaceRoot}/architecture/dependencies.json',\n '{workspaceRoot}/architecture/runtime-dependencies.json',\n ],\n options: { graphPath },\n metadata: {\n technologies: ['nx'],\n description:\n 'Generate the architecture dependency graph and the runtime microservice graph',\n },\n };\n}\n\nfunction createVisualizeTargetWithoutPrefix(graphPath: string): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:visualize',\n dependsOn: ['generate'],\n options: { graphPath },\n metadata: {\n technologies: ['nx'],\n description: 'Generate visual representations of the architecture graph',\n },\n };\n}\n\nfunction createValidateNoCyclesTarget(): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-no-architecture-cycles',\n cache: true,\n inputs: ['{workspaceRoot}/**/project.json', '{workspaceRoot}/architecture/dependencies.json'],\n metadata: {\n technologies: ['nx'],\n description: 'Validate the architecture has no circular project dependencies',\n },\n };\n}\n\nfunction createValidateUnchangedTarget(graphPath: string): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-architecture-unchanged',\n cache: false,\n inputs: ['default', '{workspaceRoot}/architecture/dependencies.json'],\n options: { graphPath },\n metadata: {\n technologies: ['nx'],\n description: 'Validate the architecture matches the saved blessed graph',\n },\n };\n}\n\nfunction createValidateNoSkipLevelTarget(): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-no-skiplevel-deps',\n cache: true,\n inputs: ['{workspaceRoot}/**/project.json', '{workspaceRoot}/architecture/dependencies.json'],\n metadata: {\n technologies: ['nx'],\n description: 'Validate no project has redundant transitive dependencies',\n },\n };\n}\n\nfunction createValidatePackageJsonTarget(): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-packagejson',\n cache: true,\n inputs: ['{workspaceRoot}/**/project.json', '{workspaceRoot}/**/package.json'],\n metadata: {\n technologies: ['nx'],\n description: 'Validate package.json dependencies match project.json build dependencies',\n },\n };\n}\n\nfunction createValidateNewMethodsTarget(\n maxLines: number,\n mode: 'STRICT' | 'NORMAL' | 'OFF',\n): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-new-methods',\n cache: false, // Don't cache - depends on git state\n inputs: ['default'],\n options: { max: maxLines, mode },\n metadata: {\n technologies: ['nx'],\n description: `Validate new methods do not exceed ${maxLines} lines (only runs in affected mode)`,\n },\n };\n}\n\nfunction createValidateModifiedMethodsTarget(\n maxLines: number,\n mode: 'STRICT' | 'NORMAL' | 'OFF',\n): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-modified-methods',\n cache: false, // Don't cache - depends on git state\n inputs: ['default'],\n options: { max: maxLines, mode },\n metadata: {\n technologies: ['nx'],\n description: `Validate new and modified methods do not exceed ${maxLines} lines (encourages gradual cleanup)`,\n },\n };\n}\n\nfunction createValidateModifiedFilesTarget(\n maxLines: number,\n mode: 'STRICT' | 'NORMAL' | 'OFF',\n): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-modified-files',\n cache: false, // Don't cache - depends on git state\n inputs: ['default'],\n options: { max: maxLines, mode },\n metadata: {\n technologies: ['nx'],\n description: `Validate modified files do not exceed ${maxLines} lines (encourages keeping files small)`,\n },\n };\n}\n\n/**\n * Create combined validate-code target\n * Options come from webpieces.config.json at the workspace root\n * (loaded by the executor via @webpieces/rules-config — same source of truth as @webpieces/ai-hook-rules)\n */\nfunction createValidateCodeTarget(): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-code',\n cache: false, // Don't cache - depends on git state\n inputs: ['default', '{workspaceRoot}/webpieces.config.json', {'runtime': 'node -e \"process.stdout.write(String(Math.random()))\"'}],\n // No options here - they come from webpieces.config.json at runtime\n metadata: {\n technologies: ['nx'],\n description: 'Combined validation for new methods, modified methods, and file sizes',\n },\n };\n}\n\nfunction createValidateVersionsLockedTarget(): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-versions-locked',\n cache: true,\n inputs: ['{workspaceRoot}/**/package.json'],\n metadata: {\n technologies: ['nx'],\n description:\n 'Validate package.json versions are locked (no semver ranges) and consistent across projects',\n },\n };\n}\n\nfunction createValidateTsInSrcTarget(): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-ts-in-src',\n cache: false,\n inputs: ['default', '{workspaceRoot}/webpieces.config.json', {'runtime': 'node -e \"process.stdout.write(String(Math.random()))\"'}],\n metadata: {\n technologies: ['nx'],\n description: 'Validate all .ts files in projects are inside the src/ directory',\n },\n };\n}\n\nfunction createValidateNxWiringTarget(): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-nx-wiring',\n cache: false, // Cheap; depends on nx.json + project graph, not worth caching\n inputs: ['{workspaceRoot}/nx.json'],\n metadata: {\n technologies: ['nx'],\n description: 'Validate the webpieces validators are wired into the build via nx.json dependsOn',\n },\n };\n}\n\nfunction createValidateCompleteTarget(validationTargets: string[]): TargetConfiguration {\n return {\n executor: 'nx:noop',\n cache: true,\n dependsOn: validationTargets,\n metadata: {\n technologies: ['nx'],\n description: 'Run all architecture validations (cycles, unchanged, skip-level deps)',\n },\n };\n}\n\n/**\n * Create per-project ci target - Gradle-style composite target\n * Runs lint, build, and test in parallel\n * (with test depending on build via targetDefaults)\n *\n * NOTE: Type checking is done by the build target (@nx/js:tsc) during compilation.\n */\nfunction createCiTarget(): TargetConfiguration {\n return {\n executor: 'nx:noop',\n cache: true,\n dependsOn: ['lint', 'build', 'test'],\n metadata: {\n technologies: ['nx'],\n description: 'Run all CI checks: lint, build, and test (Gradle-style composite target)',\n },\n };\n}\n\nfunction createHelpTarget(): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:help',\n cache: false, // Never cache - always show help output\n metadata: {\n technologies: ['nx'],\n description: 'Display help for @webpieces/nx-webpieces-rules commands and targets',\n },\n };\n}\n\n/**\n * Create per-project circular dependency checking target.\n *\n * Uses the `validate-no-file-import-cycles` executor (which bundles madge as a\n * dependency) rather than a runtime `npx madge` fetch. The executor reads\n * webpieces.config.json so the gate can be turned on/off (`mode`) and\n * time-boxed (`ignoreModifiedUntilEpoch`) like every other webpieces rule.\n *\n * Note `projectRoot` is intentionally unused now — the executor derives the\n * project root from the Nx context — but the param is kept for call-site\n * symmetry with the rest of the per-project target factories.\n */\nfunction createCircularDepsTarget(_projectRoot: string, _targetName: string): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-no-file-import-cycles',\n cache: true,\n inputs: ['default'],\n outputs: [] as string[],\n metadata: {\n technologies: ['madge'],\n description: 'Check for circular file-import dependencies using madge',\n },\n };\n}\n\n/**\n * Check if a project should be excluded based on patterns\n */\nfunction isExcluded(projectRoot: string, excludePatterns: string[]): boolean {\n if (excludePatterns.length === 0) {\n return false;\n }\n\n // Simple glob matching (could be enhanced with minimatch if needed)\n return excludePatterns.some((pattern) => {\n // Convert glob pattern to regex\n const regexPattern = pattern\n .replace(/\\*\\*/g, '.*') // ** matches any path\n .replace(/\\*/g, '[^/]*'); // * matches any string except /\n\n const regex = new RegExp(`^${regexPattern}$`);\n return regex.test(projectRoot);\n });\n}\n\n/**\n * Export plugin as default for Nx\n */\nexport default { createNodesV2 };\n"]}
|
|
1
|
+
{"version":3,"file":"plugin.js","sourceRoot":"","sources":["../../../../../packages/tooling/nx-webpieces-rules/src/plugin.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;GAgBG;;;AA4MH,sDASC;AAnND,+BAAqC;AACrC,2BAAgC;AAQhC,uDAI2B;AAC3B,yDAG4B;AAmE5B,MAAM,eAAe,GAAwC;IACzD,YAAY,EAAE;QACV,OAAO,EAAE,IAAI;QACb,UAAU,EAAE,gCAAgC;QAC5C,eAAe,EAAE,EAAE;KACtB;IACD,SAAS,EAAE;QACP,OAAO,EAAE,IAAI;QACb,YAAY,EAAE,OAAO;QACrB,SAAS,EAAE,gCAAgC;QAC3C,WAAW,EAAE;YACT,QAAQ,EAAE,IAAI;YACd,4EAA4E;YAC5E,yEAAyE;YACzE,4EAA4E;YAC5E,eAAe,EAAE,KAAK;YACtB,qBAAqB,EAAE,IAAI;YAC3B,mBAAmB,EAAE,IAAI;YACzB,kBAAkB,EAAE,IAAI;YACxB,uBAAuB,EAAE,IAAI;YAC7B,qBAAqB,EAAE,IAAI;YAC3B,sBAAsB,EAAE,IAAI;YAC5B,eAAe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,EAAE;YACN,YAAY,EAAE,CAAC,IAAI,CAAC;YACpB,WAAW,EAAE,qEAAqE;SACrF;KACJ,CAAC;AACN,CAAC;AAED;;;;;;;;;;;GAWG;AACH,SAAS,wBAAwB,CAAC,YAAoB,EAAE,WAAmB;IACvE,OAAO;QACH,QAAQ,EAAE,8DAA8D;QACxE,KAAK,EAAE,IAAI;QACX,MAAM,EAAE,CAAC,SAAS,CAAC;QACnB,OAAO,EAAE,EAAc;QACvB,QAAQ,EAAE;YACN,YAAY,EAAE,CAAC,OAAO,CAAC;YACvB,WAAW,EAAE,yDAAyD;SACzE;KACJ,CAAC;AACN,CAAC;AAED;;GAEG;AACH,SAAS,UAAU,CAAC,WAAmB,EAAE,eAAyB;IAC9D,IAAI,eAAe,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC/B,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,oEAAoE;IACpE,OAAO,eAAe,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE;QACpC,gCAAgC;QAChC,MAAM,YAAY,GAAG,OAAO;aACvB,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,sBAAsB;aAC7C,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,gCAAgC;QAE9D,MAAM,KAAK,GAAG,IAAI,MAAM,CAAC,IAAI,YAAY,GAAG,CAAC,CAAC;QAC9C,OAAO,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACnC,CAAC,CAAC,CAAC;AACP,CAAC;AAED;;GAEG;AACH,kBAAe,EAAE,aAAa,EAAb,qBAAa,EAAE,CAAC","sourcesContent":["/**\n * Unified Nx Inference Plugin for @webpieces/nx-webpieces-rules\n *\n * This plugin automatically creates targets for:\n * 1. Workspace-level architecture validation (generate, visualize, validate-*)\n * 2. Per-project circular dependency checking\n *\n * Install with: nx add @webpieces/nx-webpieces-rules\n *\n * Usage:\n * Add to nx.json plugins array:\n * {\n * \"plugins\": [\"@webpieces/nx-webpieces-rules\"]\n * }\n *\n * Then all targets appear automatically without manual project.json configuration.\n */\n\nimport { dirname, join } from 'path';\nimport { existsSync } from 'fs';\nimport type {\n CreateNodesV2,\n CreateNodesContextV2,\n CreateNodesResultV2,\n CreateNodesResult,\n TargetConfiguration,\n} from '@nx/devkit';\nimport {\n createVisualizeRuntimeTarget,\n createValidateRuntimeArchitectureTarget,\n createValidateRuntimeMarkersTarget,\n} from './runtime-targets';\nimport {\n createDiGraphGenerateTarget,\n createValidateDiGraphUnchangedTarget,\n} from './di-graph-targets';\n\n/**\n * Circular dependency checking options\n */\nexport interface CircularDepsOptions {\n enabled?: boolean;\n targetName?: string;\n excludePatterns?: string[];\n}\n\n/**\n * Validation options for architecture checks\n */\nexport interface ValidationOptions {\n noCycles?: boolean;\n noSkipLevelDeps?: boolean;\n architectureUnchanged?: boolean;\n validatePackageJson?: boolean;\n validateNewMethods?: boolean;\n validateModifiedMethods?: boolean;\n validateModifiedFiles?: boolean;\n validateVersionsLocked?: boolean;\n validateTsInSrc?: boolean;\n validateNxWiring?: boolean;\n runtimeArchitecture?: boolean;\n diGraph?: boolean;\n newMethodsMaxLines?: number;\n modifiedAndNewMethodsMaxLines?: number;\n modifiedFilesMaxLines?: number;\n /**\n * Validation mode for method/file size limits:\n * - STRICT: All limits enforced, disable comments ignored\n * - NORMAL: Limits enforced, disable comments with dates work\n * - OFF: Skip size validations entirely (for fast iteration)\n */\n validationMode?: 'STRICT' | 'NORMAL' | 'OFF';\n}\n\n/**\n * Feature flags for workspace targets\n */\nexport interface FeatureOptions {\n generate?: boolean;\n visualize?: boolean;\n visualizeRuntime?: boolean;\n}\n\n/**\n * Workspace-level configuration options\n */\nexport interface WorkspaceOptions {\n enabled?: boolean;\n targetPrefix?: string;\n graphPath?: string;\n validations?: ValidationOptions;\n features?: FeatureOptions;\n}\n\n/**\n * Configuration for @webpieces/nx-webpieces-rules Nx plugin\n */\nexport interface ArchitecturePluginOptions {\n circularDeps?: CircularDepsOptions;\n workspace?: WorkspaceOptions;\n}\n\nconst DEFAULT_OPTIONS: Required<ArchitecturePluginOptions> = {\n circularDeps: {\n enabled: true,\n targetName: 'validate-no-file-import-cycles',\n excludePatterns: [],\n },\n workspace: {\n enabled: true,\n targetPrefix: 'arch:',\n graphPath: 'architecture/dependencies.json',\n validations: {\n noCycles: true,\n // Retired: the architecture graph is now auto-reduced in `generate`, so the\n // committed graph can never contain a skip-level edge. Defaults off; the\n // executor is a no-op kept for one release. See validate-no-skiplevel-deps.\n noSkipLevelDeps: false,\n architectureUnchanged: true,\n validatePackageJson: true,\n validateNewMethods: true,\n validateModifiedMethods: true,\n validateModifiedFiles: true,\n validateVersionsLocked: true,\n validateTsInSrc: true,\n validateNxWiring: true,\n runtimeArchitecture: true,\n diGraph: true,\n newMethodsMaxLines: 30,\n modifiedAndNewMethodsMaxLines: 80,\n modifiedFilesMaxLines: 900,\n validationMode: 'NORMAL',\n },\n features: {\n generate: true,\n visualize: true,\n visualizeRuntime: true,\n },\n },\n};\n\nfunction normalizeOptions(\n options: ArchitecturePluginOptions | undefined,\n): Required<ArchitecturePluginOptions> {\n const circularDeps = {\n ...DEFAULT_OPTIONS.circularDeps,\n ...options?.circularDeps,\n };\n\n const workspace = {\n ...DEFAULT_OPTIONS.workspace,\n ...options?.workspace,\n validations: {\n ...DEFAULT_OPTIONS.workspace.validations,\n ...options?.workspace?.validations,\n },\n features: {\n ...DEFAULT_OPTIONS.workspace.features,\n ...options?.workspace?.features,\n },\n };\n\n return {\n circularDeps,\n workspace,\n } as Required<ArchitecturePluginOptions>;\n}\n\nasync function createNodesFunction(\n projectFiles: readonly string[],\n options: ArchitecturePluginOptions | undefined,\n context: CreateNodesContextV2,\n): Promise<CreateNodesResultV2> {\n const opts = normalizeOptions(options);\n const results: CreateNodesResultV2 = [];\n\n // Add workspace-level architecture targets\n addArchitectureProject(results, projectFiles, opts, context);\n\n // Add per-project targets (circular-deps, ci, runtime-markers)\n addPerProjectTargets(results, projectFiles, opts, context);\n\n return results;\n}\n\nfunction addArchitectureProject(\n results: CreateNodesResultV2,\n projectFiles: readonly string[],\n opts: Required<ArchitecturePluginOptions>,\n context: CreateNodesContextV2,\n): void {\n if (!opts.workspace.enabled) return;\n\n const archDirPath = join(context.workspaceRoot, 'architecture');\n if (!existsSync(archDirPath)) return;\n\n const workspaceTargets = createWorkspaceTargetsWithoutPrefix(opts);\n if (Object.keys(workspaceTargets).length === 0) return;\n\n const result: CreateNodesResult = {\n projects: {\n architecture: {\n name: 'architecture',\n root: 'architecture',\n targets: workspaceTargets,\n },\n },\n };\n\n const firstProjectFile = projectFiles[0];\n if (firstProjectFile) {\n results.push([firstProjectFile, result] as const);\n }\n}\n\n\n// A project sits inside a NESTED git repo (e.g. a clone under repositories/) when any of its\n// ancestor dirs — up to but NOT including the workspace root — contains a `.git`. Such projects are\n// separate repos, not part of THIS workspace's graph, so they must not get inferred targets (that is\n// what drags foreign clones into `nx affected`). Same repo-boundary signal the AI guards use.\nexport function isInsideNestedGitRepo(workspaceRoot: string, projectRoot: string): boolean {\n let dir = projectRoot;\n while (dir && dir !== '.' && dir !== '/') {\n if (existsSync(join(workspaceRoot, dir, '.git'))) return true;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return false;\n}\n\nfunction addPerProjectTargets(\n results: CreateNodesResultV2,\n projectFiles: readonly string[],\n opts: Required<ArchitecturePluginOptions>,\n context: CreateNodesContextV2,\n): void {\n // Track processed project roots to avoid duplicates when both files exist\n const processedRoots = new Set<string>();\n\n for (const projectFile of projectFiles) {\n const isProjectJson = projectFile.endsWith('project.json');\n const isPackageJson = projectFile.endsWith('package.json');\n\n if (!isProjectJson && !isPackageJson) continue;\n\n const projectRoot = dirname(projectFile);\n\n // Skip root (workspace manifest, not a project)\n if (projectRoot === '.') continue;\n\n // Skip projects inside a nested git repo (vendored clones under repositories/): they are\n // separate repos and must not be swept into this workspace's `nx affected` graph.\n if (isInsideNestedGitRepo(context.workspaceRoot, projectRoot)) continue;\n\n // Skip if we've already processed this project root\n if (processedRoots.has(projectRoot)) continue;\n\n // For package.json, skip if project.json also exists in same directory\n // (prefer project.json - it will be processed separately)\n if (isPackageJson) {\n const projectJsonPath = join(context.workspaceRoot, projectRoot, 'project.json');\n if (existsSync(projectJsonPath)) continue;\n }\n\n processedRoots.add(projectRoot);\n\n const targets = buildPerProjectTargets(isProjectJson, projectRoot, opts);\n\n if (Object.keys(targets).length === 0) continue;\n\n const result: CreateNodesResult = {\n projects: {\n [projectRoot]: {\n targets,\n },\n },\n };\n\n results.push([projectFile, result] as const);\n }\n}\n\n/**\n * Build the target map for one project. Most targets are project.json-only\n * (package.json-only projects may not have TypeScript source); `ci` goes on all.\n */\nfunction buildPerProjectTargets(\n isProjectJson: boolean,\n projectRoot: string,\n opts: Required<ArchitecturePluginOptions>,\n): Record<string, TargetConfiguration> {\n const targets: Record<string, TargetConfiguration> = {};\n\n // Add circular-deps target ONLY for project.json projects\n if (isProjectJson && opts.circularDeps.enabled) {\n if (!isExcluded(projectRoot, opts.circularDeps.excludePatterns!)) {\n const targetName = opts.circularDeps.targetName!;\n targets[targetName] = createCircularDepsTarget(projectRoot, targetName);\n }\n }\n\n // Add per-project runtime-marker validation (validates this project's\n // service-contract.json against its own api-project deps, independently).\n if (isProjectJson && opts.workspace.validations!.runtimeArchitecture) {\n targets['validate-runtime-markers'] = createValidateRuntimeMarkersTarget();\n }\n\n // Per-project DI design DAG: regenerate design.json/design.md on every build,\n // then gate the build on the committed copies being current.\n if (isProjectJson && opts.workspace.validations!.diGraph) {\n targets['di-graph-generate'] = createDiGraphGenerateTarget();\n targets['validate-di-graph-unchanged'] = createValidateDiGraphUnchangedTarget();\n }\n\n // Add ci target to ALL projects (both project.json and package.json)\n targets['ci'] = createCiTarget();\n\n return targets;\n}\n\n/**\n * Nx V2 Inference Plugin\n * Matches project.json and package.json files to create targets\n */\nexport const createNodesV2: CreateNodesV2<ArchitecturePluginOptions> = [\n // Pattern to match project.json and package.json files\n '**/{project,package}.json',\n\n // Inference function\n createNodesFunction,\n];\n\n/**\n * Build list of enabled validation target names for validate-complete dependency chain\n */\nfunction buildValidationTargetsList(\n validations: Required<ArchitecturePluginOptions>['workspace']['validations'],\n): string[] {\n const targets: string[] = [];\n if (validations!.noCycles) targets.push('validate-no-architecture-cycles');\n if (validations!.architectureUnchanged) targets.push('validate-architecture-unchanged');\n if (validations!.noSkipLevelDeps) targets.push('validate-no-skiplevel-deps');\n if (validations!.validatePackageJson) targets.push('validate-packagejson');\n // Use combined validate-code instead of 3 separate targets\n if (\n validations!.validateNewMethods ||\n validations!.validateModifiedMethods ||\n validations!.validateModifiedFiles\n ) {\n targets.push('validate-code');\n }\n if (validations!.validateVersionsLocked) targets.push('validate-versions-locked');\n if (validations!.validateTsInSrc) targets.push('validate-ts-in-src');\n if (validations!.validateNxWiring) targets.push('validate-nx-wiring');\n if (validations!.runtimeArchitecture) targets.push('validate-runtime-architecture');\n return targets;\n}\n\n/**\n * Create workspace-level architecture validation targets WITHOUT prefix\n * Used for virtual 'architecture' project\n */\nfunction createWorkspaceTargetsWithoutPrefix(\n opts: Required<ArchitecturePluginOptions>,\n): Record<string, TargetConfiguration> {\n const targets: Record<string, TargetConfiguration> = {};\n const graphPath = opts.workspace.graphPath!;\n const validations = opts.workspace.validations!;\n\n // Add help target (always available)\n targets['help'] = createHelpTarget();\n\n if (opts.workspace.features!.generate) {\n targets['generate'] = createGenerateTarget(graphPath);\n }\n if (opts.workspace.features!.visualize) {\n targets['visualize'] = createVisualizeTargetWithoutPrefix(graphPath);\n }\n if (opts.workspace.features!.visualizeRuntime) {\n targets['visualize-runtime'] = createVisualizeRuntimeTarget();\n }\n if (validations.noCycles) {\n targets['validate-no-architecture-cycles'] = createValidateNoCyclesTarget();\n }\n if (validations.architectureUnchanged) {\n targets['validate-architecture-unchanged'] = createValidateUnchangedTarget(graphPath);\n }\n if (validations.noSkipLevelDeps) {\n targets['validate-no-skiplevel-deps'] = createValidateNoSkipLevelTarget();\n }\n if (validations.validatePackageJson) {\n targets['validate-packagejson'] = createValidatePackageJsonTarget();\n }\n // Use combined validate-code instead of 3 separate targets\n // Options come from webpieces.config.json at the workspace root\n // (loaded via @webpieces/rules-config; same source of truth as @webpieces/ai-hook-rules)\n if (\n validations.validateNewMethods ||\n validations.validateModifiedMethods ||\n validations.validateModifiedFiles\n ) {\n targets['validate-code'] = createValidateCodeTarget();\n }\n if (validations.validateVersionsLocked) {\n targets['validate-versions-locked'] = createValidateVersionsLockedTarget();\n }\n if (validations.validateTsInSrc) {\n targets['validate-ts-in-src'] = createValidateTsInSrcTarget();\n }\n if (validations.validateNxWiring) {\n targets['validate-nx-wiring'] = createValidateNxWiringTarget();\n }\n if (validations.runtimeArchitecture) {\n targets['validate-runtime-architecture'] = createValidateRuntimeArchitectureTarget();\n }\n\n // Add validate-complete target that runs all enabled validations\n const validationTargets = buildValidationTargetsList(validations);\n if (validationTargets.length > 0) {\n targets['validate-complete'] = createValidateCompleteTarget(validationTargets);\n }\n\n return targets;\n}\n\nfunction createGenerateTarget(graphPath: string): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:generate',\n cache: false,\n outputs: [\n '{workspaceRoot}/architecture/dependencies.json',\n '{workspaceRoot}/architecture/dependencies.html',\n '{workspaceRoot}/architecture/runtime-dependencies.json',\n ],\n options: { graphPath },\n metadata: {\n technologies: ['nx'],\n description:\n 'Generate the architecture dependency graph (+ clickable dependencies.html) and the runtime microservice graph',\n },\n };\n}\n\nfunction createVisualizeTargetWithoutPrefix(graphPath: string): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:visualize',\n dependsOn: ['generate'],\n options: { graphPath },\n metadata: {\n technologies: ['nx'],\n description: 'Generate visual representations of the architecture graph',\n },\n };\n}\n\nfunction createValidateNoCyclesTarget(): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-no-architecture-cycles',\n cache: true,\n inputs: ['{workspaceRoot}/**/project.json', '{workspaceRoot}/architecture/dependencies.json'],\n metadata: {\n technologies: ['nx'],\n description: 'Validate the architecture has no circular project dependencies',\n },\n };\n}\n\nfunction createValidateUnchangedTarget(graphPath: string): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-architecture-unchanged',\n cache: false,\n inputs: ['default', '{workspaceRoot}/architecture/dependencies.json'],\n options: { graphPath },\n metadata: {\n technologies: ['nx'],\n description: 'Validate the architecture matches the saved blessed graph',\n },\n };\n}\n\nfunction createValidateNoSkipLevelTarget(): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-no-skiplevel-deps',\n cache: true,\n inputs: ['{workspaceRoot}/**/project.json', '{workspaceRoot}/architecture/dependencies.json'],\n metadata: {\n technologies: ['nx'],\n description: 'Validate no project has redundant transitive dependencies',\n },\n };\n}\n\nfunction createValidatePackageJsonTarget(): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-packagejson',\n cache: true,\n inputs: ['{workspaceRoot}/**/project.json', '{workspaceRoot}/**/package.json'],\n metadata: {\n technologies: ['nx'],\n description: 'Validate package.json dependencies match project.json build dependencies',\n },\n };\n}\n\nfunction createValidateNewMethodsTarget(\n maxLines: number,\n mode: 'STRICT' | 'NORMAL' | 'OFF',\n): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-new-methods',\n cache: false, // Don't cache - depends on git state\n inputs: ['default'],\n options: { max: maxLines, mode },\n metadata: {\n technologies: ['nx'],\n description: `Validate new methods do not exceed ${maxLines} lines (only runs in affected mode)`,\n },\n };\n}\n\nfunction createValidateModifiedMethodsTarget(\n maxLines: number,\n mode: 'STRICT' | 'NORMAL' | 'OFF',\n): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-modified-methods',\n cache: false, // Don't cache - depends on git state\n inputs: ['default'],\n options: { max: maxLines, mode },\n metadata: {\n technologies: ['nx'],\n description: `Validate new and modified methods do not exceed ${maxLines} lines (encourages gradual cleanup)`,\n },\n };\n}\n\nfunction createValidateModifiedFilesTarget(\n maxLines: number,\n mode: 'STRICT' | 'NORMAL' | 'OFF',\n): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-modified-files',\n cache: false, // Don't cache - depends on git state\n inputs: ['default'],\n options: { max: maxLines, mode },\n metadata: {\n technologies: ['nx'],\n description: `Validate modified files do not exceed ${maxLines} lines (encourages keeping files small)`,\n },\n };\n}\n\n/**\n * Create combined validate-code target\n * Options come from webpieces.config.json at the workspace root\n * (loaded by the executor via @webpieces/rules-config — same source of truth as @webpieces/ai-hook-rules)\n */\nfunction createValidateCodeTarget(): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-code',\n cache: false, // Don't cache - depends on git state\n inputs: ['default', '{workspaceRoot}/webpieces.config.json', {'runtime': 'node -e \"process.stdout.write(String(Math.random()))\"'}],\n // No options here - they come from webpieces.config.json at runtime\n metadata: {\n technologies: ['nx'],\n description: 'Combined validation for new methods, modified methods, and file sizes',\n },\n };\n}\n\nfunction createValidateVersionsLockedTarget(): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-versions-locked',\n cache: true,\n inputs: ['{workspaceRoot}/**/package.json'],\n metadata: {\n technologies: ['nx'],\n description:\n 'Validate package.json versions are locked (no semver ranges) and consistent across projects',\n },\n };\n}\n\nfunction createValidateTsInSrcTarget(): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-ts-in-src',\n cache: false,\n inputs: ['default', '{workspaceRoot}/webpieces.config.json', {'runtime': 'node -e \"process.stdout.write(String(Math.random()))\"'}],\n metadata: {\n technologies: ['nx'],\n description: 'Validate all .ts files in projects are inside the src/ directory',\n },\n };\n}\n\nfunction createValidateNxWiringTarget(): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-nx-wiring',\n cache: false, // Cheap; depends on nx.json + project graph, not worth caching\n inputs: ['{workspaceRoot}/nx.json'],\n metadata: {\n technologies: ['nx'],\n description: 'Validate the webpieces validators are wired into the build via nx.json dependsOn',\n },\n };\n}\n\nfunction createValidateCompleteTarget(validationTargets: string[]): TargetConfiguration {\n return {\n executor: 'nx:noop',\n cache: true,\n dependsOn: validationTargets,\n metadata: {\n technologies: ['nx'],\n description: 'Run all architecture validations (cycles, unchanged, skip-level deps)',\n },\n };\n}\n\n/**\n * Create per-project ci target - Gradle-style composite target\n * Runs lint, build, and test in parallel\n * (with test depending on build via targetDefaults)\n *\n * NOTE: Type checking is done by the build target (@nx/js:tsc) during compilation.\n */\nfunction createCiTarget(): TargetConfiguration {\n return {\n executor: 'nx:noop',\n cache: true,\n dependsOn: ['lint', 'build', 'test'],\n metadata: {\n technologies: ['nx'],\n description: 'Run all CI checks: lint, build, and test (Gradle-style composite target)',\n },\n };\n}\n\nfunction createHelpTarget(): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:help',\n cache: false, // Never cache - always show help output\n metadata: {\n technologies: ['nx'],\n description: 'Display help for @webpieces/nx-webpieces-rules commands and targets',\n },\n };\n}\n\n/**\n * Create per-project circular dependency checking target.\n *\n * Uses the `validate-no-file-import-cycles` executor (which bundles madge as a\n * dependency) rather than a runtime `npx madge` fetch. The executor reads\n * webpieces.config.json so the gate can be turned on/off (`mode`) and\n * time-boxed (`ignoreModifiedUntilEpoch`) like every other webpieces rule.\n *\n * Note `projectRoot` is intentionally unused now — the executor derives the\n * project root from the Nx context — but the param is kept for call-site\n * symmetry with the rest of the per-project target factories.\n */\nfunction createCircularDepsTarget(_projectRoot: string, _targetName: string): TargetConfiguration {\n return {\n executor: '@webpieces/nx-webpieces-rules:validate-no-file-import-cycles',\n cache: true,\n inputs: ['default'],\n outputs: [] as string[],\n metadata: {\n technologies: ['madge'],\n description: 'Check for circular file-import dependencies using madge',\n },\n };\n}\n\n/**\n * Check if a project should be excluded based on patterns\n */\nfunction isExcluded(projectRoot: string, excludePatterns: string[]): boolean {\n if (excludePatterns.length === 0) {\n return false;\n }\n\n // Simple glob matching (could be enhanced with minimatch if needed)\n return excludePatterns.some((pattern) => {\n // Convert glob pattern to regex\n const regexPattern = pattern\n .replace(/\\*\\*/g, '.*') // ** matches any path\n .replace(/\\*/g, '[^/]*'); // * matches any string except /\n\n const regex = new RegExp(`^${regexPattern}$`);\n return regex.test(projectRoot);\n });\n}\n\n/**\n * Export plugin as default for Nx\n */\nexport default { createNodesV2 };\n"]}
|